Cookies and Sessions Handling in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Cookies and Sessions Handling in PHP

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

There are three steps involved in identifying returning users −

  • Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
  • Browser stores this information on local machine for future use.
  • When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.

This blog will teach you how to set cookies, how to access them and how to delete them.

The Anatomy of a Cookie

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −

HTTP/1.1 200 OKDate: Fri, 04 Feb 2000 21:03:38 GMTServer: Apache/1.3.9 (UNIX) PHP/4.0b3Set-Cookie: name=xyz; 
expires=Friday, 04-Feb-07 22:03:38 GMT;                 
path=/; 
domain=tecklearn.comConnection: closeContent-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to “forget” the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server.The browser’s headers might look something like this −

GET / HTTP/1.0Connection: Keep-AliveUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)Host: zink.demon.co.uk:1126Accept: image/gif, */*Accept-Encoding: gzipAccept-Language: enAccept-Charset: iso-8859-1,*,utf-8Cookie: name=xyz

A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS[“name”].

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments −

  • Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value − This sets the value of the named variable and is the content that you actually want to store.
  • Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Following example will create two cookies name and age these cookies will be expired after one hour.

<?php  
setcookie("name", "John Watkin", time()+3600, "/","", 0);   
setcookie("age", "36", time()+3600, "/", "",  0);
?>
<html>      
<head>      
<title>Setting Cookies with PHP</title>   
</head>      
<body>      
<?php 
echo "Set Cookies"
?>   
</body>   
</html>

Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.

<html>     
<head>      
<title>Accessing Cookies with PHP</title>  
</head>     
<body>            
<?php        
echo $_COOKIE["name"]. "<br />";                  
/* is equivalent to */        
echo $HTTP_COOKIE_VARS["name"]. "<br />";                
echo $_COOKIE["age"] . "<br />";                  
/* is equivalent to */         
echo $HTTP_COOKIE_VARS["age"] . "<br />";      
?>         
</body>
</html>

You can use isset() function to check if a cookie is set or not.

<html>      
<head>      
<title>Accessing Cookies with PHP</title>   
</head>      
<body>            
<?php         
if( isset($_COOKIE["name"]))           
echo "Welcome " . $_COOKIE["name"] . "<br />";                  
else            
echo "Sorry... Not recognized" . "<br />";      
?>        
</body>
</html>

Deleting Cookie with PHP

Officially, to delete a cookie you should call setcookie() with the name argument only but this does not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired −

<?php   setcookie( "name", "", time()- 60, "/","", 0);   setcookie( "age", "", time()- 60, "/","", 0);?><html>      <head>      <title>Deleting Cookies with PHP</title>   </head>      <body>      <?php echo "Deleted Cookies" ?>   </body>   </html>

PHP – Sessions

An alternative way to make data accessible across the various pages of an entire website is to use a PHP Session.

A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.

The location of the temporary file is determined by a setting in the php.ini file called session.save_path. Before using any session variable make sure you have setup this path.

When a session is started following things happen −

  • PHP first creates a unique identifier for that particular session which is a random string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
  • A cookie called PHPSESSID is automatically sent to the user’s computer to store unique session identification string.
  • A file is automatically created on the server in the designated temporary directory and bears the name of the unique identifier prefixed by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.

When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the unique session identifier string from the PHPSESSID cookie and then looks in its temporary directory for the file bearing that name and a validation can be done by comparing both values.

A session ends when the user loses the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.

Starting a PHP Session

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.

The following example starts a session then register a variable called counter that is incremented each time the page is visited during the session.

Make use of isset() function to check if session variable is already set or not.

Put this code in a test.php file and load this file many times to see the result −

<?php

   session_start();

  

   if( isset( $_SESSION['counter'] ) ) {

      $_SESSION['counter'] += 1;

   }else {

      $_SESSION['counter'] = 1;

   }

              

   $msg = "You have visited this page ".  $_SESSION['counter'];

   $msg .= "in this session.";

?>




<html>

  

   <head>

      <title>Setting up a PHP session</title>

   </head>

  

   <body>

      <?php  echo ( $msg ); ?>

   </body>

  

</html>

It will produce the following result −

You have visited this page 1in this session.

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −

<?php

   unset($_SESSION['counter']);

?>

Here is the call which will destroy all the session variables −

<?php

   session_destroy();

?>

Turning on Auto Session

You don’t need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.

Sessions without cookies

There may be a case when a user does not allow to store cookies on their machine. So there is another method to send session ID to the browser.

Alternatively, you can use the constant SID which is defined if the session started. If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you can embed it unconditionally into URLs.

The following example demonstrates how to register a variable, and how to link correctly to another page using SID.
<?php

session_start();

if (isset($_SESSION[‘counter’])) {

$_SESSION[‘counter’] = 1;

}else {

$_SESSION[‘counter’]++;

}

$msg = “You have visited this page “.  $_SESSION[‘counter’];

$msg .= “in this session.”;

echo ( $msg );

?>

<p>

To continue  click following link <br />

<a  href = “nextpage.php?<?php echo htmlspecialchars(SID); ?>”>

</p>

It will produce the following result −

You have visited this page 1in this session.

To continue click following link

The htmlspecialchars() may be used when printing the SID in order to prevent XSS related attacks.

So, this brings us to the end of blog. This Tecklearn ‘Cookies and Sessions Handling in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Cookies and Sessions Handling in PHP"

Leave a Message

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