Reputation: 2209
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
Upvotes: 1
Views: 966
Reputation: 51
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.
Upvotes: 2
Reputation: 6252
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.
Upvotes: 1