Click here to Skip to main content
15,888,106 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
The below snippet occurs when a user enters correct credentials which should start a session and goes to the index.php page. It goes to the index page as expected but it is not starting the session:

Login.php:
PHP
if($validUser) {
session_start()
   $_SESSION['id'] = 'Test';
   $_SESSION['username'] = $row['username'];
   header("Location: /index.php");
}


Index.php:
PHP
<?php 

echo $_SESSION['id'];
echo $_SESSION['username'];
echo session_status();

?>


Index.php just returns a 1 for the session_status(). What am I missing?

What I have tried:

I haven't really tried anything, I thought the only thing required to start a session is session_start()
Posted
Updated 19-May-23 2:13am
v2
Comments
Rebecca2002 17-May-23 3:42am    
the second page also needs to have session_start(); DOCS: https://www.php.net/manual/en/function.session-start.php

1 solution

You need to start your page with a session, it cannot be used elsewhere in your code, it must also be on all of your pages where you make a reference to '$_SESSION'.

At the top of your page BEFORE any code, add the following -

if (session_status() == PHP_SESSION_NONE) {
	session_start();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900