I'm currently working to protect a form I created in PHP/HTML/Javascript from CSRF attacks. I have a class that does two things - one function that generates and returns a random token, and another function that checks if the token exists within the current session and if the tokens are equal. The first one I'll leave out because all it does is generate a token.
public static function checkToken($token) {
if(!empty($_SESSION['token']) && $token === $_SESSION['token'])) {
unset($_SESSION['token']);
return true;
}
return false;
}
On the main page where the form is - I start a session and check if the name of my submit button is equal to its value (which it gains upon submission):
if($_POST['submit_app'] == "Submit" && $_POST['token']) {
if(Token::checkToken($_POST['token'])) {
echo 'Token OK';
} else {
die();
}
}
I have purposely altered the token in the Web Development Tools in Google Chrome(F12), yet the form still seems to proceed to my processing page (written in php). Would using die();
not prevent the other processing form from.. processing? How can I stop the data from being submitted if the tokens do not match?
I know PHP is a server-side language so I may have to do something else to prevent submission, but I'm trying to think of a way I can kill the script before it ever process the data on the form if the tokens aren't the same.