简体   繁体   中英

Different session id between php pages

I want to share a variable between pages through the $SESSION variable. In file1.php I have

<?php session_start();
   require_once('connect.php');
   global $gb;
   $_SESSION['myvar'] = "somestring";
   // Some other code
?>

And in my second fille2.php I have

<?php session_start();
   require_once('connect.php');
   $myvar = $_SESSION['myvar'];
?>

and $myvar is empty. I first make an ajax call to file1.php and then file2.php. I've tried echoing session_id() and it's different. What's wrong here?

Edit: I am calling my server side PHP script from localhost and using Chrome with the CORS plugin enabled if that matters

I'm not sure what you mean, but If I have understood properly, both files are being called by an js script using AJAX. If you could include the js code where the call is being done, that would be really helpful. Anyway, I'm pretty sure that the second file is being downloaded before the first one. Something you can do to workaround this is to abstract both session_start() and the $_SESSION['myvar'] variable declaration in another file or in the top of your current file, for example in a file called 'session_init.php' It should look like this :

session_init.php :

<?php

//init session and session variable
session_start(); 
/* $_SESSION['myvar'] = 'value'; */ 

your current file (the file where you are making the AJAX request) :

<?php

//include this folder on the top of the page where the ajax petition is made
require_once('session_init.php');
$_SESSION['myvar'] = 'Some Value';
?>

<script type="text/javascript">

  //js code to make ajax petitio to file 1

  $.ajax({

    //parameters and other stuff

    success : function(resp){

          //js code to make ajax petition to file 2
          $.ajax({

             //parameters and other stuff
          });
      }
  })
 </script>

Now $_SESSION['myvar'] should be accessible in both files as long as you declare session_start() at the top of each file. Remember that is not a good practice to nest AJAX petitions. Also you can take a different approach to send the data trough the files, for example, sending the value of 'myvar' as a parameter on the AJAX request.

It sounds like you're not calling session_start() from the file making the AJAX calls, which will result in two different sessions. That, or you're regenerating the session ID somewhere within connect.php

If that doesn't help you resolve your issue, then please provide all relevant code so I can attempt to reproduce it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM