Working with PHP Sessions and Cookies

Working With PHP Cookie and Sessions

PHP Sessions

A session is a way to store information (in the form of variables) to be used across multiple pages.


The PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

Starting with PHP session

For starting a php session use the builtin function session_start(). This function is used in the between the php tags, as follow:


<h3>Starting up a session</h3>

<hr />


session_start(); // start up your PHP session!

Save it as session1.php

Output of the above script

To run the code Open the XAMPP server an start the services like Apache and MySQL. Open the browser and type: http://localhost/yourfoldername/session.php

PHP Session Start Syntax

Storing a session variable

In this section we will use the correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

PHP script for storing session

<h3>Storing the session in the variable</h3>

<hr />

$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data

Save it as session2.php

Output of above script

To run the code, Open the XAMPP or wamp server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/session2.php

Storing a session variable in php

PHP session with isset() function

Here in this section, session is created with the help of isset(). We create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1

PHP script

<h3>Storing the session in the variable isset()</h3>

<hr />

else $_SESSION['views']=1;
echo "Views=". $_SESSION['views'];

Save it as isset.php


To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/isset.php

PHP Session Checking

If you hit the same URL again and again the counter for session will incremented.

PHP Session Increment Check

Increment Using PHP Session

Destroying a PHP session

Destroying a session is also a very important part so if you wish to delete some session data, you can use the unset() or the session_destroy() function.The unset() function is used to free the specified session variable:


You can also completely destroy the session by calling the session_destroy() function:


Note: session_destroy() will reset your session and you will lose all your stored session data.

Tracking Previous Visits to a Page

Let’s now put all this theory in context, by building a simple application that demonstrates how sessions work. This next example uses a session to record every visit made by a user to a Web page. On each visit, the script prints the dates and times of all previous visits and adds a record for the current visit to the session.

Here’s the code (visits.php):

<?php // start session session_start(); ?>

Tracking Previous Visits To A Page

<h2>Tracking Previous Visits To A Page</h2>

if (!isset($_SESSION['visits'])) {

echo 'This is your first visit.';

} else {

echo 'You previously visited this page on: ';

foreach ($_SESSION['visits'] as $v) {

echo date('d M Y h:i:s', $v) . '';




// add current date/time stamp to session array
$_SESSION['visits'][] = time();

To see this script in action, visit the Web page a few times, and you should see a growing list containing records of all your previous visits. This list remains available so long as you don’t close the browser window—so even if you visit a few other sites and then return to this script, you’ll still see the records of all your previous visits. Once you close the browser, however, the session cookie will be destroyed and the list will begin a new.

User Visit Tracking Using PHP

This script works by creating a session every time a user visits the page, and storing the timestamp of the user’s visits in the session variable $_SESSION[‘visits’]. On each subsequent visit, the session is recreated, the array containing the timestamps of previous visits is restored, and a foreach loop is used to iterate over this array and print its records in human-readable date and time format.

Cookies in PHP

Now we are going learn how to deal with cookies; first of all we need to know “what is the meaning of cookies” ?

A cookie is object used to identify the user by his/her computer. Cookies are small strings of data created by a Web server but stored on the client. In addition to having names and values, cookies have an expiration time. Cookies are often used to track user information.


A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too.

For this purpose you must install a XAMPP server.

Creating Your First PHP Cookie

For creating the very first cookies with PHP, we used the setcookie() function. This is a built in function in php.



Now we will understand the meaning of these arguments, the explanation of name, value and expiration are given below:

  • name: The name of your cookie. You will use this name to later retrieve your cookie, so don’t forget it.
  • value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
  • expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

This is the PHP script to set the cookies for the particular user :

PHP cookies info

<h3>Setting up cookies</h3>

<hr />

 setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth)

with in php scripting

<hr />

//Calculate 30 days in the future

//seconds * minutes * hours * days + current time

$oneMonth = 60 * 60 * 24 * 30 + time();

setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth);

<hr />

 Cookies enabled............

$oneMonth = 60 * 60 * 24 * 30 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth);

Save it as abc.php.

Output of above php scripting

Type http://localhost/yourfoldername/abc.php at your browser, here your output look like:

PHP Cookie Starting Syntax

PHP script to retrieve the information

 PHP cookies info


<hr />

<?php if(isset($_COOKIE['lastVisit']))
       $visit = $_COOKIE['lastVisit'];
       echo " you got stale cookies!";
 echo "Welcome back!
 You last visited on ". $visit;

Save it as ref.php.


Type http://localhost/yourfoldername/ref.php at your browser, here your output look like :

PHP Cookie Testing

Destroying the cookies

To destroy the cookie, simply use setcookie again, only set the expiration date to be in the past. Here is an example:

$past = time() - 60; //this makes the time 60 seconds ago
setcookie(lastVisit, date("G:i - m/d/y"), $past);

Remember: Cookies need to be set in the header. This means they must be sent before any HTML is set to the page, or they will not work.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

Leave a Reply

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