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

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