PHP: Persistence

This page forms the code summary of 09.persistence.html, part of the Webscripting1 — Serverside Webscripting course, part of the Professional Bachelor ICT study programme, taught at Odisee, Ghent, Belgium. The materials and this summary were developed by Bram(us) Van Damme, lecturer ICT at Odisee, who blogs over at bram.us and Twitters as @bramus. The materials and this summary may be used freely, as long as credit to Bramus is present and a clear an upfront link to ikdoeict.be remains in place. Suggestions and additions may be mailed to Bramus, or sent via a pull request on GitHub.

Cookies

Reading a cookie

The client will send all eligible cookies available along with the request head and PHP will automagically make all sent-in cookies available in $_COOKIE

$color = (string) isset($_COOKIE['color']) ? $_COOKIE['color'] : '#FFFFFF';

Setting a cookie

Use setcookie()

setcookie('color', $value, time() + 24*60*60*7);

Remember that the cookie won't immediately become available in $_COOKIE as setcookie() is merely an instruction for the client to create the cookie upon receival of the generated response

Deleting a cookie

Set the cookie with an expiry date set in the past.

setcookie('color', $value, time() - 24*60*60*7);

Sessions

Starting/Continuing a session

Use session_start() to start or continue a previous session. PHP will look for a sent-in PHPSESSID (usually sent in automatically via a cookie) and will continue that session (viz. it will populate $_SESSION with the previously saved data). If PHPSESSID is empty a new PHPSESSID with empty $_SESSION will be generated.

session_start();

You only need to start the session once for the PHP file. It is recommended to start it at the very top, just beneath the includes/requires.

All code below won't work if you don't start the session first!

Storing sessiondata

Push an entry onto $_SESSION, like you would manipulate a regular array

$_SESSION['name'] = 'Bramus!';

Getting sessiondata

$name = isset($_SESSION['name']) ? $_SESSION['name'] : 'stranger';

Removing sessiondata

unset($_SESSION['name']);

Stopping a session

foreach ($_SESSION as $key => $value) unset($_SESSION[$key]);
session_destroy();