Any data you have stored is forgotten just when the page has been sent to the client and the connection is closed. Tiny bits of information, a web site could store on the client's machine that were sent back to the web site each time a new page was requested. Each cookie could only be read by the web site that had written it, meaning that it was a secure way to store information across pages. Cookies allow people to track how often a visitor came to their site, what they did on the site, and such, and many people believed that cookies signal the end of privacy on the web.

Sessions originate from cookies as a way of storing data on the server side. In order to set up a unique identifier on the client, sessions still use a small cookie. This cookie simply holds a value that uniquely identifies the client to the server, and corresponds to a data file on the server.

Sessions

Sessions is started with session_start() function and it may be temrinated (stopped) with session_destroy().

Syntax for PHP session

<?php
    session_start();
?>

Example of PHP session

// starting a session
<?php
    session_start();
?>    
    
// HTML
<!DOCTYPE html>
<html>
<body>
<?php
    session_unset(); // removes all session stored variables
    session_destroy(); // destroys the session after used
?>
</body>
</html>

Cookies

Cookies store a variable (or variables) in a web browser for a specified time period.

Syntax for PHP cookie

<?php
    setcookie(variable, variable's value, expiration time)
?>

Example of setting PHP cookie

<?php
    $cookie_var = "username";
    $cookie_val = "admin";
    setcookie($cookie_var, $cookie_val, time()+(86400*10), "/"); //86400 (setting for 10 days)
?>

<html>
<body>
<?php
    if(!isset($_COOKIE[$cookie_var])) 
    {
        echo "Cookie is not set";
    }
    else {
        echo "Cookie " .  $cookie_var . " value is: " . $_COOKIE[$cookie_var]; 
    }
?>
</body>
</html>

Example of deleting PHP cookie

<?php
    $cookie_var = "username";
    $cookie_val = "admin";
    setcookie($cookie_var, $cookie_val, time() - 3600); //-3600 means it has expired
?>

<html>
<body>
<?php
    if(!isset($_COOKIE[$cookie_var])) 
    {
        echo "Cookie is deleted";
    }
?>
</body>
</html>

Example of checking PHP cookie if enabled

<?php
    $cookie_var = "username";
    $cookie_val = "admin";
    setcookie($cookie_var, $cookie_val, time() + 3600); //3600 = 1 hour)
?>

<html>
<body>
<?php
    if(count($_COOKIE) > 0) 
    {
        echo "Cookie is enabled";
    }
    else {
        echo "Cookie is disabled";
    }
?>
</body>
</html>

 

›› go to examples ››