Raja Gopal Raja Gopal - 21 days ago 5
PHP Question

PHP session notice:undefined index

I am trying to pass a value using session from one page to another but it says


Notice: Undefined index: user_id in path\file.php on line 61


The file where i am creating session is as follows

// checking for session, if not then start session
if(!isset($_SESSION)) {
session_start();
}
// assigning user_id to session var
$_session['user_id']=$row['user_id'];


This is the code by which, i am accessing session var:

if(!isset($_SESSION)) {
session_start();
}
// trying to access session var (previously defined)
$user_id=$_session['user_id'];


Where i am making mistake. Kindly guide me please

Answer

It should be $_SESSION not $_session.

 $_SESSION['user_id']=$row['user_id'];

 $user_id = $_SESSION['user_id'];

$_SESSION is a global variable and should be written in capital. When you are using the variable with small letters, in that case it doesn't get the variable because its never been defined and doesn't have the key user_id and hence you get the error. Hope this helps.