php - Protect form with session token -
i wrote script protect form session token; script not work if try validate form fields before checking token. me figure out wrong script please?
<?php session_start(); class token { public static function generate() { return $_session['token'] = base64_encode(openssl_random_pseudo_bytes(15)); } public static function check($token) { if (isset($_session['token']) && $token === $_session['token']) { unset($_session['token']); return true; } return false; } } ?> <?php $display_form = false; if (isset($_post['submit'])) { $username = $_post['username']; $userpass = $_post['userpass']; if (strlen($username) < 4) { $error_name = 'required'; $display_form = true; $validation_error = true; } if (strlen($userpass) < 8) { $error_pass = 'required'; $display_form = true; $validation_error = true; } if (!$validation_error) { if (token::check($_post['token'])) { echo 'process form'; } else { echo 'invalid security token'; } } } else { $display_form = true; } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <?php if ($display_form == true) { ?> <form method="post" action="<?php echo htmlspecialchars($_server['request_uri']); ?>"> <input type="hidden" name="token" value="<?php echo token::generate(); ?>"> <input type="text" name="username" id="" placeholder="username"> <?php echo $error_name; ?> <br> <input type="password" name="userpass" id="" placeholder="password"> <?php echo $error_pass; ?> <br> <input type="submit" name="submit" value="sign in"> </form> </body> </html> <?php } ?>
this code hard read. can't tell when if statements start , end. stop using classes everything. use procedural programming big boy.
your issue simple one. $validation_error
not initialized in outer scope. meaning not saved between if statments.
to fix add $validation_error = false
@ outer scope:
... $display_form = false; $validation_error = false; // right here if (isset($_post['submit'])) { $username = $_post['username']; $userpass = $_post['userpass']; ...
Comments
Post a Comment