You don’t need to know about cookies (though we have an article on cookies here) to get through this article or to use sessions. Just keep in mind that they usually automatically use and set cookies, and like cookies you have to do certain things before the first output is sent (including doctype, <html>, or any whitspace).

The main thing you need to do is start a session before output is started. Also, for those familiar with it, output buffering can help give you more flexibility with where session_start() or setcookie() are used.


You should probably also call session_cache_expire(); right before to set the expiration time you want.

session_cache_expire(30); //the session will expire in 30 minutes
session_start(); //start the session for this page

Usually these are called like that every time a page starts. session_cache_expire() accepts the number of minutes, not seconds, till the stored information will expire. Let’s expand this to actually set some session variables.

//those functions should be called every page
$_SESSION['user_name'] = 'Robert Downey';
$_SESSION['user_login_time'] = time();
$_SESSION['user_language'] = 'English';
//setting those variables should be done once though, then they will be available on every page load like so:
$user_name_local = $_SESSION['user_name'];

Simple right? The $_SESSION variable handles everything automatically, making your shopping cart, message board, or other script run smoothly.

if($_GET['log_out'] == 'yes') {

After calling session_unset() the session data is cleared, the user would be logged out, and there is no need to make the session expire or something like you might do with cookies. Be aware that you can call unset($_SESSION[‘user_name’]) to unset that session variable, but it is advised that you should not use unset($_SESSION), use the session_unset() function described here.