Session does not work as expected in Ajax and PHP request

Asked

Viewed 398 times

0

Well I have a main page index php. where the person executes an action and makes a request POST with Ajax. In this main file I create a session with some data that I want to keep safer 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>

Has a second page request.php, where I send the requisition ajax with JSON return. Nessa second page I do a check if the token of session is the same that was passed to the requisition AJAX, and just being the same to continue the code.

Example: request.php

<?php if ($_SESSION['EXAMPLE']['token'] == $_POST['token']) {...}

However, in the second page the session token arrives different than it was before. Let’s say that on the main page "index php." the token created in the session was "12345abcExampleToken", is also passed to date of AJAX also, but on the second page it arrives as "789452hjkhToken", is another totally different, as if the index php. a new token had been started and a new token had been created.

Well, I’d like to know why this is happening. And if there is a safer solution ("if this way I am using is really safe"), please could share me?

Note - Edition: The token is generated through a function of Static Class, I thought I’d let you know, in case this had anything to do with!

class Example
{
    public static function getToken(): string
    {
        return 'createToken';
    }
}

and I wear it like this in session:

$_SESSION['EXAMPLE'] = [
    'token' => Example::getToken(),
    'other' => 'stringEtc'
];
  • in $.post, the token is being sent correctly but in request.php in session is incorrect?

  • @Everson yes, it’s coming in different. I did an "echo" to display Session as soon as it was created and I also see the $.post, and of course the request.php too. But in her comes different

  • One of the ways to try to figure out where the problem is is to check the post sent through the inspect on the network tab by looking at the post data. You can then echo in php as soon as the token is generated, so you can compare the two

  • @Isac How can I do that? "inspect on the network tab"

  • Open the inspecting doing botão direito followed by Inspecionar. As a general rule this corresponds to F12 in most browsers. In this inspection window the Network (Network) tab is usually 3rd in Chrome, and displays all the requests that have been made and shows the data sent/received. Just click on anyone to see the specific information of that request.

  • I did the test, and I swapped the "token" for "date/time" and the "request.php" is 2.3 seconds longer. Example: index.php 2017-08-18 23:22:35 --- request.php 2017-08-18 23:22:37. This happens whether I made the request or not, because I waited a few seconds to make the request and see if it was at this time, but continued 2 to 3 seconds difference

  • It would be better to put the right code to analyze. Because to me it seems like you’re calling again getToken() , maybe it’s just to use include

  • @Wéllingthonm.Souza added the code, and really I use include/require, has how I solve this?

  • Some things are without comment as I’m adding now

Show 4 more comments

2 answers

0


I figured out what was causing it! I don’t know why this happens, but it was a html element which had the attribute style with the background empty as follows:

<section class="..." style="background: url('') center;"></section>

Maybe it’s because he’s calling the page again

0

Let us exemplify, that this code would be yours index php.

session_start();
$_SESSION['TOKEN'] = md5(time()); // Gera o Token e salva na sessão
echo "O TOKEN É: " . $_SESSION['TOKEN']; // imprime a Sessão Token na tela

Here would be your request.php, if she is including the index php. will automatically generate another Token and overwrite the $_SESSION['TOKEN']

include "index.php";
if ($_SESSION['TOKEN'] == $_POST['TOKEN']) {
    // isso daria errado, porque ? porque fez o include da index.php
}

My recommendation, is you create a new file, example: resquest2.php and perform only data check

if ($_SESSION['TOKEN'] == $_POST['TOKEN']) {
    // isso daria certo, porque ? porque não fez o include da index.php
}

Abservation:

If you call the method getToken() that you’re in class Example in his index php. you cannot call this method again in your request.php, because it will overwrite the previous TOKEN.

Example:

Example::getToken(); // Estaria sobrescrevendo a $_SESSION['TOKEN']
if ($_SESSION['TOKEN'] == $_POST['TOKEN']) {
    // isso daria errado.
}
  • It really makes sense, but I’m not including the index.php =/ the includes that I’m doing at the beginning both of index.php, how much of request.php, are 2 files in which I start some things, such as the session_start, database connection and call with autoload from Poser pros namespaces, which includes Example::getToken(). So these might be doing this? because I do include him in index.php and in request.php tb, as I could solve?

  • You just can’t perform the method getToken() in request.php, because it creates another hash and overwrites the previous one.

  • I’ll put it in the answer so I can be clearer.

  • Well, I took a test instead of by getToken, I used the rand() php, at index he generated me 28077, already in the request 19593. I use the session_start() with include in both, but session req_token is given value only in the index, has something in mind?

  • This is the request header, if anything serves :) https://prnt.sc/gabw9e

  • Let’s talk on chat

  • Finally found out, thank you so much for helping :D

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.