within index.php, I have placed this at the top
<?php
session_start();
function generate_secure_token($length = 16)
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
$_SESSION['csrf_token'] = generate_secure_token();
$token = $_SESSION['csrf_token'];
?>
Within my form I then have a hidden field
<input type="hidden" name="csrf_token" id="csrf_token" value="<?php echo $token; ?>">
Within my Javascript I make an Ajax request
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "php/process.php",
dataType: "json",
data: {
'csrf_token': $("#csrf_token").val()
}
}).done(function(response) {
if (response === 'success') {
window.location.replace("thanks.php");
}
}).fail(function(jqXHR, textStatus) {
return false;
});
}
And then finally within process.php I check the CSRF
<?php
session_start();
$errors = array();
$userData = array();
if (!isset($_POST['csrf_token']) ||
empty($_POST['csrf_token']) ||
$_POST['csrf_token'] != $_SESSION['csrf_token']) {
$errors['csrf_token'] = 'Something went wrong';
}
if (!empty($errors)) {
echo json_encode('failure');
sendErrorEmail($errors, "Validation", $userData, __LINE__);
} else {
//Do something
}
I have noticed that I am getting a lot of error emails relating to the CSRF token not being set. Within sendErrorEmail
I am sending myself the browser information for those that fail, and I have noticed that 90% of them are IPhone or Android.
Is there anything specific to this code that may not work within smart phones?
Thanks