EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Sessions in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Sessions in PHP

Sessions in PHP

Introduction on PHP sessions

Sessions are used within web applications. The use of session in PHP is to make the data available across different pages of a website. The data or information like name, address, etc is carried from one page to another user session. This session information is used for authentication purposes. Like the cookies are stored on the clients’ browser, the session data is stored on the server in a temporary directory.

To begin a session we use session_start() function. And when the session starts its lasts for 24 minutes by default which is 1440 in seconds. A session is identified by session identifiers or SID which is a unique number to identify each user.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Create Sessions?

session_start() is the function used to start a session. If a session already exists it will use the same session, else it will create a new session. This function is always called at the beginning of each page. After the function is called, we can start storing values in the session variables, but not before that. PHP stores information of the user in a super global variable $_SESSION.

To know what is the path of the directory where sessions are stored, we have a directive called session_save_path in the php.ini file to store the path. Also, the session_id prints the id associated with the current session. It is a unique randomly generated number.

Let us look at the below program.

In this program, when you print this session variable using the print_r($_SESSION), all the set session data is printed. The output is in the form of an associative array of key-value pairs.

In this example, we first start the session using session_start() function, initialize variables and assign it to session variables using _SESSION[‘name’] = $name, print the super global array. We also print the unique session id value also with the session_id() function.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,731 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example

Code:

<?php
// example to start session
//beginning a session
// no arguments are passed to this function
session_start();
//initializing variables
$name = 'Neha';$age = 28;
//storing values in session
$_SESSION['name'] = $name;
$_SESSION['age'] = $age;
// printing session valuesprint_r($_SESSION);
//using the session id
echo '<br > The session_id is ';
echo session_id();
?>

Output:

sessions in PHP 1

How to Delete Sessions?

Following is an example for delete session:

Example

Session_destroy() function is used to destroy a session. This function destroys the complete session. To unset a single session variable we can use unset() function.

In this example, we print the session data first to know what the session holds then we destroy the already set session variables using the unset() function. Here we destroy both the set session variables like the name and the age. And after destroying we print the session again, and see that it returns an empty array, meaning the variables have been unset and the session does not exist anymore.

Code:

<?php
//example to unset session variables
//starting a session
session_start();
print_r($_SESSION);
//before destroying the session
//printing the session
unset($_SESSION['name']);
unset($_SESSION['age']);
echo 'Session destroyed';
//after destroying the session
//printing the session
print_r($_SESSION);
?>

Output:

sessions in PHP 2

How to Destroy Session?

In the following example, we are destroying a session.

To destroy the session we will first check the session value and then destroy the session. and again print the session which will be an empty array as the session does not exist.

Example #1

Code:

<?php
//example to destroy session
//starting a session
session_start();
//to completely destroy a session
session_destroy();
echo 'Session destroyed';
//after destroying the session
//printing the session
echo '<br />';
print_r($_SESSION);
?>

Output:

destroyed array

Here, in the program, we see that in the first line we start the session and initialize the count variable to 0. next we check whether a session variable is set or not. here we check one condition whether a session name page_views is set if yes then increment the count variable value by one and if not then initialize the count value to one.

Example #2

Code:

<?php
session_start();
$count = 0;
if(!isset($_SESSION['page_views'])) {
$_SESSION['page_views'] = 1;
$count = $_SESSION['page_views'];
} else {
$_SESSION['page_views'] = $_SESSION['page_views'] + 1 ;
$count = $_SESSION['page_views'];
}
?>
<html>
<head><title>Finding count of page views</title></head>
<body>
<?php echo '<br>'. 'The count of page views '. $count;
?>
</body>
</html>

Output:

count page views

How to Turn on Auto Session in Php?

To turn on auto sessions in php we have to make a change in the configuration file which is php.ini.

Where php.ini is a default configuration file

Sessions do not start on their own automatically, to make a session work automatically we have to do the following, but once done the session is started automatically for all the files and closes after the default time is over.

So in the php.ini file, we will search for

session.auto_start = 0

and set the value to 1 like this

session.auto_start = 1

This will help PHP to start sessions automatically.

Importance of session

Some importance of session are penned below.

  • Like $_COOKIE, we have $_SESSION, which is a superglobal variable and stored over the server.
  • In case the cookies are not supported by the browser of the user, we can use the session. Each session has a unique id assigned to it as per the user visit on the website.
  • In terms of storing data, the session stores more data than a cookie can store.
  • The session is used to carry information from one page to another.
  • The session can be used to get the count of visitors to the website.
  • The session is used for authentication purposes also.
  • Session IDs generated is unique.

Conclusion

In this article, it is explained what is a session, how the session works, how do we create the session, how do we delete a particular session.

Also, it is explained how do we make the sessions work starting automatically by setting the directive session.auto_start() value to 1.

Then with an example, it was explained how to count, how many times the page has been viewed using sessions. Also, it is explained what is the importance of session and how it is useful for different purposes.

Recommended Articles

This is a guide to Sessions in PHP. Here we discuss the basic concept, how to Create Sessions and Delete Sessions in PHP with the given examples. You may also have a look at the following articles to learn more –

  1. Encapsulation in PHP
  2. PHP Magic Constants
  3. Overloading in PHP
  4. Constructor in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More