Menu Content/Inhalt
PHP Sessions Introduction PDF Print E-mail
Written by Raymond Fain   
Tuesday, 10 July 2007
Introduction to PHP Sessions.

 

Developing applications that use PHP sessions is straightforward. Sessions are used primarly to store information that will be used at a later time. Each session has identification, store variables in the session, and are reusable at later times. In this tutorial I will go over the basics to PHP sessions.

PHP sessions are ready to go with PHP and do not take much to get them going. PHP sessions uses disk-based files to store the sessions.

Starting a Session

<?php
start_session
();
?>

 

The first time a user requests a script with this function in it, PHP generates a new session ID and creates an empty file to store session variables in. When the user has called on the function many times, PHP will reuse the first generated one. However, because the cookie being sent as part of the HTTP headers in the response to the browser, you need to have this before an other existing code.

Session Variables

Once you have initiated the session, you are free to enter in the data.

<?php
start_session
();

$_SESSION['name'] = "Raymond";

?>

Once the start_session() function has been called, PHP provides access to session variables through the superglobal associative array $_SESSION. To unset a sessions variable, you can use the function unset() as shown here:

<?php

start_session
();

$_SESSION['count'] = 1;

echo 
$_SESSION['count'];

unset(
$_SESSION['count']);

?>

You can also remove all the session variables by setting $_SESSION = array();

Ending a Session

At some point in an application you may need to end the session. Calling on session_destroy() function will destroy all sessions and remove the session file. This is good practice in using session_destroy() when you need to log people out and redirects to another page.

After getting a good handle on sessions check out the more advanced tutorials on PHP sessions to grasp strategies and some up-to-date applications used by online stores.

Last Updated ( Tuesday, 31 July 2007 )
 
Next >

Who's Online

Advertise