Reputation: 41
I'm a little confused on what session ID's in PHP actually are, and what they are useful for. I am coding a website with user information, register, and login. In login script tutorials in PHP, many people include session_start(). They also check that the current session ID matches that stored in the database for the users (stored during login) and if they do not, they log the user out (redirect to login page by setting header).
What exactly is the function/usefulness of session ID's? And how do I incorporate them into my login script without creating a redirect loop?
Thanks for any help.
Upvotes: 1
Views: 2611
Reputation: 171
In brief, a session id identifies a browser.
Since http itself is stateless, every request like loading a page is independent from any previous request.
To overcome this circumstance, you use session_start() to instruct the web server to send a cookie to the browser or, when a cookie exists, tell php the current session id which was saved in the cookie previously.
A session id itself is a randomly generated unique string, only used to track if a browser is already known to the server.
If there is someone visiting a site the very first time, it works like this:
From now on with every following request the browser sends it's session id from the cookie. In this case, phps session_start() picks it up, looks if this session id exists and if so, makes it available to your script.
PHP stores, usually in files on the server, variables "inside a session". That means, via $_SESSION['somevalue'] you can get and set values, e.g. $_SESSION['logged_in'] indicating if the user is logged in.
That whole task of sending an appropriate header to the browser for setting a cookie, reading back the header from a request, storing variables in a file that is named after the session id is wrapped into session_start() for your convenience.
Storing the session id in the database is useful if for some reason you don't want to use the PHP default, which is storing them into text files.
There are many tutorials on the web on how to build a login form with sessions and php. Maybe this tutorial is something you like.
The principle is always the same:
If it isn't clear by now, a session is only a way to remember stuff for a single browser between two different pages. (via $_SESSION)
Upvotes: 8