coder
coder

Reputation: 843

how to use session in php?

I am creating a login module in php. I am using session variables for that. On the top of the file, I write session_start();

Then when my login password is authenticated, I write $_SESSION["username"] = $_POST["userid"]

now do I need to do something else as well to ensure that the session that got started sustains?? because as soon as it logs in, it logs out automatically? does it mean the session expires as soon as I log in?? In that case what should I do to make the session sustain??

Upvotes: 1

Views: 1750

Answers (5)

Alex
Alex

Reputation: 370

At the top, put session_start(); also on each page you want to use session, you need this function.

The session sustains as long as you didn't remove the session or close the browser, not sure whether it will expire sometime. To check whether you are still logged in, you can access the session using $username = $_SESSION['username'];, or the function isset($_SESSION['username']) also helps.

Upvotes: 0

Abhishek
Abhishek

Reputation: 836

Put session_start(); at the top of page where you will use the session variables. And be sure you don't unset session in you login script.

Upvotes: 1

Tomasz Kowalczyk
Tomasz Kowalczyk

Reputation: 10477

No, session is meant to stay between the requests. If you read $_SESSION['username'] on next request, it will contain the data you saved in previous request. Obviously, you need to put session_start(); at the beginning of every page you want to interact with it.

Upvotes: 1

Macros
Macros

Reputation: 7119

You need session_start(); at the top of all files you are going to access Session data in

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

session_start() doesn't start the session, it starts the session engine. It must be run on every page you want to have access to the session on.

Upvotes: 0

Related Questions