Simple way to prevent Cross-site Request Forgery in php.
//trying to prevent CSRF attacks
function checkCSRF($key=''){
//correct referer or empty sent by browser, checkign the form
if ( (!empty($_SESSION['token_'.$key])) && (!empty($_POST['token_'.$key])) ) {
if ($_SESSION['token_'.$key] == $_POST['token_'.$key]) {//same token session than form
return true;
}
}
return false;
}
//create an input with a token that we check later to prevent CSRF
function createCSRF($key){
//$key variable allows us to have more than 1 form per page and to have more than 1 tab opened with different items
$token = md5($key.uniqid(rand(), true));//unique form token
$_SESSION['token_'.$key] = $token;
return '';
}
Usage:
Creation
Check correct request:
if (checkCSRF('form1'))
{
echo 'everyhing good ;)';
}
else
{
echo 'bad really bad';
}
Hope it’s useful 😉