user580950 user580950 - 5 months ago 9
PHP Question

Session Value changes in PHP

I have a PHP page fbridge.php which sets a session value

<?php
$_SESSION['type']="EMP";

?>
<script type="text/javascript">

window.location="index.php";

</script>


The page then redirects to index.php which has the following code

<?
echo "1=".$_SESSION['type'];
session_start();
if($_SESSION['sessions_id']!=session_id())
{
header('Location: login.php');
exit;
}
echo "2=".$_SESSION['type'];
?>


The problem is 1= is Always blank and 2=Always print some value that is not EMP.

Not sure what the problem is.

Answer

The session_start() should be called before accessing or modifying session variables

FIRST:

   <?php
        session_start();
        $_SESSION['type']="EMP";
        header("Location:index.php"); //This is better than javascript ?
    ?>

SECOND:

<?
    session_start();
    echo "1=".$_SESSION['type'];
    if($_SESSION['sessions_id']!=session_id()) 
    {
        header('Location: login.php');
        die("Browser doesn't support redirect"):
    }
    echo "2=".$_SESSION['type'];
?>