I'm new to PHP, so apologies if this is an amateur mistake. I am attempting to add a simple CSRF check for a basic contact form.
I am following the instructions under 8 Cross-site request forgery on this page: http://www.phpfreaks.com/tutorial/php-security
It passes security when the html page is refreshed, but the first time it does not. The error it provides the first time is: "Undefined index: token". So I guess it's somehow not writing the token to Session the first time?
Any assistance you can provide would be greatly appreciated. Thank you.
PHP to set up token called in the HEAD of HTML page with include:
<?php
function generateFormToken() {
session_start();
$_SESSION['token'] = uniqid(md5(microtime()), true);
}
?>
Form (simplified):
<?php generateFormToken(); ?>
<form method="post" action="php/formsubmit.php">
<fieldset>
<!-- fields -->
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>">
</fieldset>
<input type="submit" value="Submit" >
</form>
formsubmit.php:
<?php
session_start();
$isToken = $_SESSION['token'];
if ($_POST['token'] !== $isToken) {
die('Security failed');
} else {
... run validation etc.