0

I'm trying to learn how to use Sessions to maintain state between pages.

I think my problem is that I dont know how to escape properly. When I load the page im not getting the SID at the end of the url, instead I'm getting this:

mytestsite.com/login.php?<?php echo SID;?>

I have session_start() at the top of every page. And the session initialy works as I see the login name appear on the page and the Register and Login links, but then when I click to another page the session is not maintained.

The main site nav is dynamically createdusing an array($nav) and foreach loop. Here too I'm not sure how to echo the url and php SID constant. I don't think my syntax is correct.

//LOGIN BAR
echo "<nav id='statusBar'>";

echo "<ul>";

if(isset($_SESSION['userIn']) && $_SESSION['userIn'] != ''){

    echo "<li id='userLo'>Log Out</li>";
    echo "<li id='userLi'>User Logged In: " . $_SESSION['userIn'] . "</li>";

}   else{

    echo '<li><a href="registration.php?<?php echo SID;?>">Register</a></li>';

    echo '<li><a href="login.php?<?php echo SID;?>">Login</a></li>';

}


echo "</ul>";


echo "</nav>";

//START MAIN MENU
echo "<nav id='nav'> ";

$nav = array();

$nav['index.php?<?php echo SID;?>'] = 'Home';
$nav['public1.php?<?php echo SID;?>'] = 'Public 1';
$nav['public2.php?<?php echo SID;?>'] = 'Public 2';
$nav['members.php?<?php echo SID;?>'] = 'Members';


//CREATE UNORDERED LIST
echo '<ul>';

foreach ($nav as $key => $navValues) {
    echo "<li>";
    echo "<a href='$key'>$navValues</a>";
    echo "</li>";

}
echo '</ul>';

echo "</nav>";
  • 1
    You never need to nest `` while already inside PHP code (it's a syntax error). Since you're using single-quoted strings there, concatenate: `echo '
  • .......href="registration.php?' . SID . '"...
  • ';` but it is not cler what the value of `SID` is expected to be. Are you trying to append a session ID? There is no need to place it in the URL -- PHP sets and manages a session cookie automatically. – Michael Berkowski Jul 28 '15 at 19:23
  • About `session_start()` and not persisting to other pages... If it is indeed on every script, be sure you have also enabled `display_errors` (always when developing and testing code). At the top of your scripts or includes: `error_reporting(E_ALL); ini_set('display_errors', 1);`. Sessions failing when `session_start()` is present is often due to [the Headers already sent error](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Michael Berkowski Jul 28 '15 at 19:26