Example: How to use Cross-Site Request Forgery (CSRF) form protection

  1. 1: <?php
  2. 2:  
  3. 3: /**
  4. 4:  * Nette\Forms Cross-Site Request Forgery (CSRF) protection example.
  5. 5:  */
  6. 6:  
  7. 7:  
  8. 8: require_once '../../Nette/loader.php';
  9. 9:  
  10. 10:  
  11. 11:  
  12. 13:  
  13. 14:  
  14. 15:  
  15. 16: $form new Form;
  16. 17:  
  17. 18: $form->addProtection('Security token did not match. Possible CSRF attack.'3);
  18. 19:  
  19. 20: $form->addHidden('id')->setDefaultValue(123);
  20. 21: $form->addSubmit('submit1''Delete item');
  21. 22:  
  22. 23:  
  23. 24:  
  24. 25: // Step 2: Check if form was submitted?
  25. 26: if ($form->isSubmitted()) {
  26. 27:  
  27. 28:     // Step 2c: Check if form is valid
  28. 29:     if ($form->isValid()) {
  29. 30:         echo '<h2>Form was submitted and successfully validated</h2>';
  30. 31:  
  31. 32:         $values $form->getValues();
  32. 33:         Debug::dump($values);
  33. 34:  
  34. 35:         // this is the end, my friend :-)
  35. 36:         if (empty($disableExit)) exit;
  36. 37:     }
  37. 38: }
  38. 39:  
  39. 40:  
  40. 41:  
  41. 42: // Step 3: Render form
  42. 43: ?>
  43. 44: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  44. 45: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  45. 46: <head>
  46. 47:     <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  47. 48:     <meta http-equiv="content-language" content="en" />
  48. 49:  
  49. 50:     <title>Nette\Forms CSRF protection example | Nette Framework</title>
  50. 51:  
  51. 52:     <style type="text/css">
  52. 53:     <!--
  53. 54:     .required {
  54. 55:         color: darkred
  55. 56:     }
  56. 57:  
  57. 58:     fieldset {
  58. 59:         padding: .5em;
  59. 60:         margin: .3em 0;
  60. 61:         background: #EAF3FA;
  61. 62:         border: 1px solid #b2d1eb;
  62. 63:     }
  63. 64:  
  64. 65:     input.button {
  65. 66:         font-size: 120%;
  66. 67:     }
  67. 68:  
  68. 69:     th {
  69. 70:         width: 8em;
  70. 71:         text-align: right;
  71. 72:     }
  72. 73:     -->
  73. 74:     </style>
  74. 75: </head>
  75. 76:  
  76. 77: <body>
  77. 78:     <h1>Nette\Forms CSRF protection example</h1>
  78. 79:  
  79. 80:     <?php echo $form ?>
  80. 81: </body>
  81. 82: </html>