Jesin's Blog

Welcome to the Portal of Technology

  • Facebook
  • GitHub
  • RSS
  • Twitter
  • Home
  • Categories
    • Domains
    • Linux
    • Networking
    • PHP
    • Virtualization
    • Web Design
    • Web Servers
    • Windows
  • WordPress Plugins
    • Custom Error Pages
    • HTTP Digest Authentication
    • Mailgun Email Validator
  • Toolbox
    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool
  • About Me
  • Contact Me
  • Sitemap
Home ›
PHP ›
PHP Sessions Tutorial

PHP Sessions Tutorial

March 8, 2011 PHP Jesin A Leave a Comment

php category thumbnail

This PHP sessions tutorial explains how sessions work, commonly used PHP session handling functions and how to use then. A session is the time duration that starts from the time a user visits a website and ends when he/she leaves the website. Usually when we use PHP variables they can be accessed only in the script in which they are used but sessions variables can be accessed by all PHP scripts which are accessed during that “session” Sessions greatly help in personalizing an user’s experience on a website, they can also be used to create Login pages using PHP. We’ll first see how PHP sessions work.

How do PHP sessions work ?

When a session is started by a PHP script a session cookie is sent to the client a.k.a. browser requesting the script. This session cookie named PHPSESSID by default contains a 32 character “session” ID which is set to expire when the session ends.

PHP session cookie
Firefox shows the PHP session cookie. Notice the content which contains the session ID and expires which says end of the session

On the server-side a file named sess_X (replace X with the 32 character session ID) is created in the location specified in session.save_path setting in the php.ini file. This is C:\WINDOWS\Temp for windows and /var/lib/php/session in Linux. This file contains the names of all session variables and their respective values. So when a user whose browser contains the session ID 7iisicf6j2fde3tfverbh9she3 accesses the website the server checks for the file named sess_7iisicf6j2fde3tfverbh9she3 in its session save path and accordingly uses the variables in that file.

PHP Session Functions

Some of the commonly used session functions are explained here

session_start() This function starts a session or resumes a session if it already exists. This should be used at the beginning of any script which uses a session. If this function is not called none of the session variables can be accessed. When this function is called for the first time a cookie is set named PHPSESSID (default name) containing the session ID.

session_id() This function sets or the current session ID. If this function is called without any parameters it returns the current session ID. If a string is specified session_id(“jb4jkjk4b3j6basd”) it will set the session ID to the one specified.

session_name() This function sets or gets the session name. The default name is PHPSESSID if this function is called without parameters it returns the current session name. If a string is passed as a parameter it is set as the session name session_name(“WebsiteSess”) To set a session name this function should be called before the session_start() function.

session_destroy() This destroys all session variables. This function is mainly used in logout pages to delete all session variables. The session_destroy() must be called AFTER the session_start() function else variables will NOT be removed.

$_SESSION This is not a function it is a global array variable which contains all session variables and their values. Session variables are created by assigning values to the index of this variable. e.g $_SESSION[‘username’]=”Jesin” The index value of $_SESSION is user defined.

An example for PHP Sessions

Lets create a small script spanning over 3 pages which outline how sessions can be used to pass data between pages.

<?php
session_start();
print "Session start. Session variable is " . session_id() . " and session name is " . session_name();
$_SESSION['name']="Jesin";
print "The session variable 'name' contains " . $_SESSION['name'];
?>
<?php
session_start();
if(isset($_SESSION['name']))
{
print "Your name is " . $_SESSION['name'];
}
else
{
print "You directly visited this page";
}
?>
<?php
session_start();
print "The session variable name contains ".$_SESSION['name'];
print "<br>We'll now destroy all variables";
session_destroy();
print "<br>The session variable name contains ".$_SESSION['name'];
?>

Create these three pages when you visit the first page a session is created, its ID and name are displayed a session variable named “name” is created with value “Jesin” When you visit Page2.php it checks whether the session variable “name” is set and displays the name assigned in the first page. Now visiting the third page will display the value of the variable first and then destroy it. Now when it displays the session variable again nothing is shown. Now go to Page2.php you’ll see the line “You directly visited this page” because the session variables are destroyed.

Some things to take note while using sessions. All scripts using sessions must start with the function session_start() including the script which destroys the session. Any number of session variables can be defined using $_SESSION variable. For more PHP session functions see http://php.net/manual/en/ref.session.php

Related posts:

php category thumbnailPHP Captcha Tutorial php category thumbnailCreating a PHP MySQL Login Page Script php category thumbnailHow to display IP Address in PHP php category thumbnailPHP include() vs require() php category thumbnailHow to use PHP to minify HTML output

Tags: php

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Get a wealth of information delivered to your inbox. Subscribe and never miss a single article.

  • Tutorials and howtos
  • Code, scripts and commands
  • Online Tools

* No spam, unsubscribe anytime

Hire Me

  • SSL installation and hardening (A+ on Qualys SSL test)
  • Apache & Nginx configuration
  • Email deliverability improvement (10/10 on Mail Tester & MailGenius)
  • WordPress customization, optimization and migration
  • and much more…

    Tools

    • DNS Lookup Tool
    • htdigest Generator Tool Online
    • htpasswd Generator Tool Online
    • HTTP Headers Lookup Tool
    • MD5 Encryption Tool
    • Open Port Check Tool
    • SHA-1 Encryption Tool
    • URL Encoding/Decoding Tool

    Nav

    • Home
    • About Me
    • Contact Me
    • Privacy Policy
    • Sitemap
    Vultr SSD VPS

    Creative Commons License
    Jesin's Blog by Jesin A is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
    Based on a work at websistent.com.