...

View Full Version : Check if SESSION exists after login



archipuir
12-20-2010, 05:01 PM
Hello,

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:


<?php

session_start(); // Creates a session

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


Here is the code of my second page:



<?php

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";}
?>

Fumigator
12-20-2010, 05: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.

archipuir
12-20-2010, 05:55 PM
Hi,

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



<?php
session_start();
?>

Fumigator
12-20-2010, 07: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.

archipuir
12-20-2010, 08:07 PM
Thanks,

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.

Fumigator
12-20-2010, 08: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:

http://us2.php.net/manual/en/function.session-destroy.php

The reaper
12-20-2010, 08:36 PM
Changing:


if (isset($_SESSION))


to


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

//

}

Should do the trick.

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum