// Generate session id and csrf token
$session_id = uniqid();
$csrf_token = uniqid() . $session_id;
// set session_id, csrf_token and username(this is optional and used // for saving votes) cookies
setcookie('session_id', $session_id, time() + (86400 * 30), "/");
setcookie('csrf_token', $csrf_token, time() + (86400 * 30), "/");
setcookie('username', $username, time() + (86400 * 30), "/");
$(document).ready(function(){
$("#csrf_token").val(getCookie("csrf_token"));
});
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
// Validate the csrf token cookie and the csrf_token submitted along
// with the form
if($_COOKIE['csrf_token'] == $_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