Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable: _SESSION when sending variables via post through JavaScript trigger

Tags:

php

session

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.

Thing is, this PHP file is purely a backend script and is POSTed to when a JavaScript function is triggered. When the POST call attempts to cause the script in the second PHP file to be executed the error log is reporting that:

_SESSION is an undefined variable.

I've tried calling start_session() and session_regenerate_id() at the top of the second PHP file but the issue has persisted.

I'm assuming what is going on is that because it's in a POST this PHP file is in its own session as I am still able to do this $_COOKIE[ini_get('session.name')].

The information that I am trying to pass to the second PHP file isn't anything that needs to be secured but it would be nice to know in the future how to do this: call a PHP file via a POST and still have my session variables.

like image 861
keybored Avatar asked Aug 29 '11 23:08

keybored


5 Answers

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.

like image 73
deceze Avatar answered Nov 06 '22 12:11

deceze


session_start();  

is the answer of most of topic like this. i have been struggling with this issue and i solve my problem with this code

    if (version_compare(PHP_VERSION, '5.4.0', '<')) {
        if(session_id() == '') {session_start();}
    } else  {
       if (session_status() == PHP_SESSION_NONE) {session_start();}
    }
like image 37
Gorkem Yontem Avatar answered Nov 06 '22 12:11

Gorkem Yontem


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']
like image 4
robertparkerx Avatar answered Nov 06 '22 10:11

robertparkerx


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.

like image 3
Ashahmali Avatar answered Nov 06 '22 11:11

Ashahmali


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.

like image 1
Dung Dinh Avatar answered Nov 06 '22 11:11

Dung Dinh