In my index.php file I call session_start()
and set a couple of session variables. In a second PHP file I would like to access these session variables.
you must include
<?php session_start();?>
at the beginning of your document, this will start the SESSION ENGINE and enable you to set session variables (ie. $_SESSION['var1'], $_SESSION['var2'], etc)
If you're wanting to get values from a $_POST you could relate the two together by :
$_SESSION['var1'] = $_POST['answer1']
Add the following code to the file browse.php:
error_reporting( error_reporting() & ~E_NOTICE );
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('GMT');
}
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
if(session_id() == '') {session_start();}
} else {
if (session_status() == PHP_SESSION_NONE) {session_start();}
}
It will work fine.
I came faced with this problem, and after trying a lot of things, I just included session_start() on the second script and it worked.
I also encountered the same problem recently. I could not access the contents of the $_SESSION variable.
1) This was as a result of trying to access the $_SESSION variable before the declaration of session_start();
In my own case, I had already started a session in a header.php file. But I was accessing the $_SESSION variable before the include statement. Example;
<?php
$username = $_SESSION['username'];
//do some logical operation!!!
?>
<?php include("header.php");?>
instead of doing something like this
<?php include("header.php");?>
<?php
$username = $_SESSION['username'];
//do some logical operation!!!
?>
2) Another thing that may cause this problem, maybe a failure to start a session at the top of all the files that may require access to the $_SESSION variable using
session_start();
Hope this helps anybody that stumbles on the same problem. Although this is coming at a late hour.
There's nothing special whatsoever about POST requests and sessions.
You just need to call session_start
at the top of every file request you want to use sessions in, that's it.
Try again with that in mind, it ought to work.
session_start() is the answer. And here's one more way of going about it:
<?php
if (session_id() == "")
session_start(); ?>
This will ensure that a new session is started only if you do not have a current session on already. And ofcourse, as others have said, make sure to place this at the top of the html.