Tuesday, February 24

How do PHP sessions work in PHP, and how are they used?

In the general situation :

    1. the session id is sent to the user when his session is created.
    2. it is stored in a cookie (called, by default, PHPSESSID)
    3. that cookie is sent by the browser to the server with each request
    4. the server (PHP) uses that cookie, containing the session_id, to know which file corresponds to that user.
    5. The data in the sessions files is the content of $_SESSION, serialized (ie, represented as a string -- with a function such as serialize) ; and is un-serialized when the file is loaded by PHP, to populate the $_SESSION array.


Sometimes, the session id is not stored in a cookie, but sent in URLs, too -- but that's quite rare, nowadays.


For more informations, you can take a look at the Session Handling section of the manual, that gives some useful informations.

For instance, there is a page about Passing the Session ID, which explains how the session id is passed from page to page, using a cookie, or in URLs -- and which configuration options affect this.


Start a PHP Session:

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.


<?php

    // Start the session
    session_start();
    
    // Set session variables
    $_SESSION["favcolor"] = "green";

?>

Get PHP Session Variable Values:

<?php
    // Echo session variables that were set on previous page
    echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
    
    //Another way to show all the session variable values for a user session is to run the following code:
    print_r($_SESSION);
?>

Modify a PHP Session Variable:

To change a session variable, just overwrite it:

<?php
    // to change a session variable, just overwrite it 
    $_SESSION["favcolor"] = "yellow";
    print_r($_SESSION);
?>

Destroy a PHP Session:

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

<?php
    // remove all session variables
    session_unset(); 
    
    // destroy the session 
    session_destroy(); 
?>

No comments:

Post a Comment