Csrf Prevention in PHP

csrf.php 


<?php

session_start();

function csrf_token(){

$csrf_token=md5(uniqid(rand(0,99999),true));

$_SESSION['_token'] = $csrf_token;

return $csrf_token; 

}


function csrf_validate(){

if(array_key_exists('_token', $_POST)){

$sent_token=$_POST['_token'];

}else{

die('No Token Found');

}

if($sent_token ==$_SESSION['_token']){

echo 'Token Valid Request Valid';

}else{

die("Invalid Token".$_SERVER['REMOTE_ADDR']);

}


}


test.php



<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

<h1>CSRF Attack</h1>

<?php

require_once __DIR__.'/csrf.php';

?>


<hr>

<form action="test-code.php" method="post">


<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">


<p>Enter the Email:

<input type="text" name="email"/>

</p>

<p>

<input type="submit" name="submit" />

</p>

</form>

</body>

</html>

csrf prevention