13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing Simple Sessions<br />

513<br />

Registering Session Variables<br />

The way you register session variables has recently changed in <strong>PHP</strong>. Session variables<br />

have been stored in the superglobal array $_SESSION since <strong>PHP</strong> 4.1.To create a session<br />

variable, you simply set an element in this array, as follows:<br />

$_SESSION[‘myvar’] = 5;<br />

The session variable you have just created will be tracked until the session ends or until<br />

you manually unset it.The session may also naturally expire based on the<br />

session.gc_maxlifetime setting in the php.ini file.This setting determines the<br />

amount of time (in seconds) that a session will last before it is ended by the garbage collector.<br />

Using Session Variables<br />

To bring session variables into scope so that they can be used, you must first start a session<br />

calling session_start().You can then access the variable via the $_SESSION superglobal<br />

array—for example, as $_SESSION[‘myvar’].<br />

When you are using an object as a session variable, it is important that you include<br />

the class definition before calling session_start() to reload the session variables.This<br />

way, <strong>PHP</strong> knows how to reconstruct the session object.<br />

On the other h<strong>and</strong>, you need to be careful when checking whether session variables<br />

have been set (via, say, isset() or empty()). Remember that variables can be set by the<br />

user via GET or POST.You can check a variable to see whether it is a registered session<br />

variable by checking in $_SESSION.<br />

You can check this directly using the following, for example:<br />

if (isset($_SESSION[‘myvar’])) ...<br />

Unsetting Variables <strong>and</strong> Destroying the Session<br />

When you are finished with a session variable, you can unset it.You can do this directly<br />

by unsetting the appropriate element of the $_SESSION array, as in this example:<br />

unset($_SESSION[‘myvar’]);<br />

Note that the use of session_unregister() <strong>and</strong> session_unset() is no longer<br />

required <strong>and</strong> is not recommended.These functions were used prior to the introduction<br />

of $_SESSION.<br />

You should not try to unset the whole $_SESSION array because doing so will effectively<br />

disable sessions.To unset all the session variables at once, use<br />

$_SESSION = array();<br />

When you are finished with a session, you should first unset all the variables <strong>and</strong><br />

then call<br />

session_destroy();<br />

to clean up the session ID.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!