Im using a script for generat token with link of website but i have always problem with the first refresh the next time all is good
session_start();
$link = 'http://localhost/';
$id_user = '123456789';
function getToken($name = '', $key)
{
session_start();
$token = sha1(uniqid());
$_SESSION[$name.'_token'] = $token;
return $token;
}
function checkToken($name = '', $post)
{
session_start();
global $link, $id_user;
if(isset($_SESSION[$name.'_token']) && isset($_POST[$post]))
{
if(sha1($link.$id_user.$_SESSION[$name.'_token']) == $_POST[$post])
{
return true;
}
else {
return false;
}
}
else {
return false;
}
}
First i create new token if empty or is not ajax call I use link, id user and unique token for verify is good or noot
if(empty($_SESSION['new_token']) || !$_REQUEST['ajax'] AND empty($_POST)) {
$tokenUnique = sha1($link.$id_user.getToken('new'));
} else {
$tokenUnique = sha1($link.$id_user.$_SESSION['new_token']);
}
And in ajax post i use this for view if checkToken is good
if(checkToken('new', 'token_hidden') == false) {
die('error token');
}
<input type="hidden" name="token_hidden" value="<?=$tokenUnique?>" />
U have solution for secure ajax or complet my code ? Thanks
Jquery
$.ajax({
type: "POST",
data: $(div).serialize(),
url: 'file.php?ajax=1',
success: function(data) {
var obj = JSON.parse(data);
}
});