Well I have a main page index.php where the person performs an action and performs a POST with Ajax request. In this main file I create a session with some data that I want to keep more secure and not be visible and others for confirmations.
Example: index.php
<?php
// exemplo da sessão
$_SESSION['EXAMPLE'] = [
'token' => '123456abcExample',// SEMPRE UM NOVO E ÚNICO TOKEN É GERADO AO CARREGAR A PÁGINA index.php
'other' => 'stringEtc'
];
?>
...
<script>
// exemplo da requisição ajax - no mesmo site
// página "http://example.com/url/index.php" e a outra "http://example.com/url/request.php"
$.post('http://example.com/url/request.php', {
'example' => 'string',
'token' => $_SESSION['EXAMPLE']['token']
}, function (response) {
// code
}, 'json');
</script>
You have a second page request.php , where I send the ajax request with JSON return. On this second page I check if the token is the same as the AJAX request , and just being the same to continue the code.
Example: request.php
<?php if ($_SESSION['EXAMPLE']['token'] == $_POST['token']) {...}
However, on the second page the session token arrives different than it was before. Let's say that in the main index.php page the token created in the session was 12345abcExampleToken , it is also passed in AJAX's date , but on the second page it arrives as "789452hjkhToken" , or another totally different one, as if index.php had been started again and a new token was created.
Well, I'd like to know why this might be happening. And if there is a more secure solution ("if this way I'm using is really safe"), could you please share me?
Note - The token is generated through a Static Class function, I found it good to inform,
class Example
{
public static function getToken(): string
{
return 'createToken';
}
}
and I use this in the session:
$_SESSION['EXAMPLE'] = [
'token' => Example::getToken(),
'other' => 'stringEtc'
];