Sessions are a useful web technology that are used on just about every interactive site out there. Sessions are an important part of all PHP development. A session is a useful method of keeping track of a user’s browser throughout different page requests. The session is dealt with via a cookie sent to the user’s browser, with an expiry time of 0, that is to say, as soon as the browser window is closed, the cookie is destroyed and the session is over.
Examples when you might use a session:
It is important that a PHP developer also know what not to do in a session:
A session can be created easily with:
page1.php
<?php
session_start();
$_SESSION['time'] = time();
$_SESSION['data'] = “test data!”;
echo ‘<a href=”page2″>Click here!</a>’
?>
The constant SID becomes defined and contains the session ID. This is useful if you need to pass it through GET or POST from one page to another in the event that cookies are disabled/blocked.
page2.php:
<?php
session_start();
if ($_COOKIE["PHPSESSID"])
{
echo ‘This session was started at: ‘ . date(’Y m d H:i:s’, $_SESSION['time']) . ‘<br />’;
echo ‘This session contains some data: ‘ . $_SESSION['data'] . ‘<br />’;
session_destroy();
} else {
echo ‘The session was not started. Either you didn’t come here from page1.php or your browser does not support cookies<br />’;
}
?>
session_destroy() will terminate the current session and remove the cookies associated with it.
Note that I’m using $_COOKIE["PHPSESSID"] to determine whether we have a session cookie. If we do the session has been started, otherwise it hasn’t. Also note that cookies are sent and received in the header portion of the HTTP request. For this reason, sessions must be started before any other data is output to the browser. $_COOKIE["PHPSESSID"] will also not be available on the same page that set the cookie itself, only subsequent ones.
Tags: PHP, PHP, PHP Developer, sessions, session_destroy, session_start, web
You must be logged in to post a comment.