View Full Version : Check if SESSION exists after login

12-20-2010, 06:01 PM

I have a login page that redirects to my second page after login. The session is created in the login page. In my second page I need to check if there is a valid session, without creating a new one. Is it possible to check it, without adding session_start() in my second page, so that no new session is created?

Here is the code of my login page:


session_start(); // Creates a session

$_SESSION["username"] = $username;
header("Location: secondpage.php");

Here is the code of my second page:


session_start(); // How can I remove this line, so that it doesn't create a new session?

if (isset($_SESSION)) {print "session exists";} // Checks if session exists
else {print "session does not exist";}

12-20-2010, 06:20 PM
The function session_start() does not create a "new" session every time it is called; it will check the HTTP request header for existing session data and make it available to your script if it's there. It's required for sessions to work properly.

12-20-2010, 06:55 PM

why does session_start(); create a new cookie named PHPSESSID, when I execute the following code?


12-20-2010, 08:20 PM
By default PHP sessions uses cookies and if the session does not exist then session_start() creates a cookie like you are seeing. If the session already exists session_start() uses that cookie.

12-20-2010, 09:07 PM

can I disable that session_start() creates a cookie if it is not on the login page?

My goal is to only give a session cookie to the persons who log in, and those who don't log in shouldn't get one only because I want to check if they have one.

12-20-2010, 09:31 PM
Not really, since the only way you can check $_SESSION is by starting session. But, you can destroy the session if there are no login credentials found. The best way to destroy a session is discussed in the PHP manual here:


The reaper
12-20-2010, 09:36 PM

if (isset($_SESSION))


if (isset($_SESSION["username"])) {
// code



Should do the trick.

12-20-2010, 10:17 PM
You'll still need session_start() up top which will create a cookie.