// Generate session id and csrf token 
$session_id = uniqid();
$csrf_token = uniqid() . $session_id;
$sessions[$username] = $session_id;
$csrf_tokens[$session_id] = $csrf_token;
// Save session and csrf token
file_put_contents(‘./database/sessions.txt’, ‘<?php return ‘ . var_export($sessions, true) . ‘;’); file_put_contents(‘./database/csrf_tokens.txt’, ‘<?php return ‘ . var_export($csrf_tokens, true) . ‘;’);
// set session_id and username cookies
setcookie(‘session_id’, $session_id, time() + (86400 * 30), “/”); setcookie(‘username’, $username, time() + (86400 * 30), “/”);
$(document).ready(function(){
$.ajax({
url: "./server/csrf.php",
type: "POST",
success: function(data){
$("#csrf_token").val(data);
},
error: function(err){
}});
});
// Return the csrf token based on the session id  if(!isset($_COOKIE[‘session_id’])) {
echo “Error! Please Login!”;
} else {
echo $csrf_tokens[$_COOKIE[‘session_id’]];
}
// Validate the stored csrf token and the token sent by the client
if($csrf_tokens[$_COOKIE['session_id']] == $_POST["csrf_token"]){
$votes[$_COOKIE['username']] = $_POST["vote"];
file_put_contents('./database/votes.txt', '<?php return ' . var_export($votes, true) . ';');
header("location: ../home.php?success=Your vote was succuessfully saved !");
}else{
header("location: ../home.php?error=Failed! Please login and try again!");
}

--

--

Live to code | Senior Software Engineer @ WSO2

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store