Session Help

When a user logs in, a session starts, containing the ID assigned to them upon registration. When I try an print that page in “home.php”, it doesn’t show up. Any help?

This is all the code before it assigns the session variable.


<?php
require("includes/connect.php");
require("includes/redirect.php");

$resultUser = mysql_query(
    sprintf(
        "SELECT Username FROM sq_users WHERE Username = '%s'",
        mysql_real_escape_string($_POST['username'])
    )
);
if(0 !== mysql_num_rows($resultUser)){
	$resultUser = mysql_query(
    	sprintf(
        	"SELECT ID,Username,Passwd FROM sq_users WHERE Username = '%s'",
       	 	mysql_real_escape_string($_POST['username'])
    	)
	);
	$passFlat = $_POST['passwd'];
	$pass = md5($passFlat);
	
	$row = mysql_fetch_row($resultUser);
	
	if($pass == $row[2]){
		session_start();
		$_SESSION['id'] = $row[0];
		
		header('Location: '. $root . $home);
		mysql_close($con);
		exit;
	}

This is the “home.php” code.


<?php
echo "User ID = ". $_SESSION['id'];
?>

You have to session_start() in every script that needs to access $_SESSION

You need to call session_start() before you can set, or read session variables. You need to do this for each script execution(web page request).

Thanks for the help!

No. When you set a $_SESSION var it is stored in a file on the server (how it manages to live between page requests). You call session_start() so php will read that file back into the $_SESSION array for access in the current script.

session_start() is needed at the top and then you can set session variables.