Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is PHP session_start()

Tags:

Does it start a current session based on cookies? Got that from the PHP website. How does PHP control the session? If I start a session when a user opens up my login page, what do I even use that session for? Can I use the current session to get info about the logged in user?

like image 371
Scott Avatar asked Oct 25 '10 14:10

Scott


People also ask

What is PHP session_start () and session_destroy () function?

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called. Note: You do not have to call session_destroy() from usual code.

Where should the session_start () function be used?

Every page that will use the session information on the website must be identified by the session_start() function. This initiates a session on each PHP page. The session_start function must be the first thing sent to the browser or it won't work properly. It must precede any HTML tags.

What is $_ session in PHP?

PHP $_SESSION is an associative array that contains all session variables. It is used to set and get session variable values.

How PHP session is created and destroyed?

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.


1 Answers

The PHP session system lets you store securely data in the $_SESSION global array. A typical example is to store the user's identifier in the session when they type in their password:

if ($user = try_login($login, $password))    $_SESSION['user'] = $user; 

Then, you can access that information on all other pages:

if (isset($_SESSION['user']))   // logged in !   echo user_name($_SESSION['user']); 

The data is stored on the server, so there is no risk of tampering (on the other hand, mind your disk usage).

Starting the session lets the current request use $_SESSION. If this is the user's first visit, the array will be empty and a new session cookie will be sent for you.

Closing the session merely prevents the current request from using $_SESSION, but the data stays around for the next requests.

Destroying the session throws away all the data, forever. The sessions are destroyed a certain duration after the last visit (usually around 30 minutes).

like image 146
Victor Nicollet Avatar answered Jan 05 '23 17:01

Victor Nicollet