I'm trying to implement CSRF protection to a webform. Its a one page website that captures data, posts it to a PHP file which then emails me the information. The webpage functions as intended (minus the security).
I'm having the following issues:
- I can't work out how to implement the PHP code to set the token; converting index.html to index.php loads a blank body. I think that resolving this would likely fix my issues.
- When I try and call token.php from jQuery, I get a 403 error.
- When I try and run the script in a 1-pixel iframe, I get a 500 error (I assume as it's being run on HTML).
token.php
<?php
session_start();
if (empty($_SESSION['token'])) {
$_SESSION['token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['token'];
?>
formsubmit.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['token'])) {
if (hash_equals($_SESSION['token'], $_POST['token'])) {
$emailbody = 'Name: ' . $_POST['m_title'] . ' ' . $_POST['m_firstname'] . ' ' . $_POST['m_surname'] . "
"
. 'Email: ' . $_POST['m_email'] . "
"
. 'Phone: ' . $_POST['m_phone'] . "
"
. 'D.O.B: ' . $_POST['m_dob_day'] . ' ' . $_POST['m_dob_month'] . ' ' . $_POST['m_dob_year'] . "
"
. 'Postcode: ' . $_POST['m_postcode'] . "
"
. 'Lenders: ' . $_POST['m_bank1'] . ',' . $_POST['m_bank2'] . ',' . $_POST['m_bank3'] . ',' . $_POST['m_bank4'] . ',' . $_POST['m_bank5'] . ',' . $_POST['m_bank6'] . ',' . $_POST['m_bank7'] . ',' . $_POST['m_bank8'];
mail('**removed**', 'Web Lead', $emailbody);
header('Location: **removed**/thankyou');
exit();
}
else {
echo "token invalid";
}
}
else {
echo "token blank";
}
}
else {
echo "invalid request";
}
?>
My jQuery attempt in index.html
<script>
$(document).ready(function() {
$.get('token.php');
});
</script>
Provided the PHP above is not riddled with errors, I had assumed that successfully converting it to index.php would resolve my issues, but I am having difficulty doing so.