PHP session lost after redirecting the page

I was inserting some data and was trying to show my success message using SESSION variables in PHP. my code segment of samplepage.php was like this:

if(isset($_POST["Add"]))
{
    $txtName=$_POST['txtName'];
    $txtKey= $_POST["txtKey"];
         
    //when submit button is add
    if($btnValue=="Add")
    {
        if($txtName<>"") //Permission Name can't be blank
        {
            $query = "insert into Table(NAME, KEY) values('$txtName','$txtKey')" ;
            $st = oci_parse($conn, $query);                             
            $success = oci_execute($st,OCI_DEFAULT); // oci as db is oracle here
            oci_commit($conn);
             
            if($success ==1)
            {
            $_SESSION['MySuccessMsg'] = "Data Added Successfully!";
            header('Location: samplepage.php');
            } 
                
               }
         
        }
}

and below this segment I was catching the $_SESSION[‘MySuccessMsg’] in a div in top of my HTML body:

                if(isset($_SESSION['MySuccessMsg'])) // receiving SESSION message .
		{ $msg = $_SESSION['MySuccessMsg'];}				
                echo "<strong>".$msg1."</strong>";  } 
                unset($_SESSION['MySuccessMsg']); //unset session variable
?> 

so every time the page was redirected after $success==1 condition segment, I found no data in $msg.

Later I found a help and realized, it is of 2 cases:

1) make sure session_start() is at the top of the page.
2) use exit() right after where the page is redirected from.

so my new code segment of insert becomes:

     if($success ==1)
     {
	$_SESSION['MySuccessMsg'] = "Data Added Successfully!";
	header('Location: permission.php');
	exit(); // this one is important to keep the session variable hold data even after re-direct	
     }  

NOTE: even if we redirect the page, it still executes the code till the end. therefore my session variable was being unset. so, EXIT() function works here not to unset the variable and code stops execution and moves to the redirected page immediately.

thanks to: stackoverflow

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s