Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to set & unset session variable in codeigniter ?
Next article icon

PHP | Unset Session Variable

Last Updated : 20 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Whenever data are stored using cookies, there is a possibility of a hacker to insert some harmful data in the user’s computer to harm any application. So its always advisable to use PHP sessions to store information on the server than on a computer. Whenever data is needed across many pages of a website or application, PHP Session is used.

This session creates a temporary file in a folder that stores registered variables with their values which are made available for the entire website. This Session ends when the user logs out of the site or browser. Every different user is given unique session IDs that are linked to an individual’s posts or emails.

<?php    session_start();    echo session_id();  ?>

Note: The session IDs are randomly generated by the PHP engine which is difficult to make out.

Example: The following PHP function unregisters or clears a session variable whenever $_SESSION is used in some code. It is mostly used for destroying a single session variable.

  • Syntax:
        unset($_SESSION['variable_name']);  
  • Program 1 :




    <!DOCTYPE html>
    <html>
      
    <head>
        <style>
            body {
                width: 450px;
                height: 300px;
                margin: 10px;
                float: left;
            }
              
            .height {
                height: 10px;
            }
        </style>
    </head>
      
    <body>
        <h1 style="color:green">GeeksforGeeks</h1>
        <b> PHP Unset session variables </b>
        <div class="height"> </div>
    <?php
         
    // start a new session 
    session_start(); 
            
    // Check if the session name exists 
    if( isset($_SESSION['name']) ) { 
        echo 'Session name is set.'.'<br>'; 
    } 
    else { 
        echo 'Please set the session name !'.'<br>'; 
    } 
     echo'<br>';
     $_SESSION['name'] = 'John'; 
       
      //unset($_SESSION['name']);     
     echo "Session Name : ".$_SESSION['name'].'<br>'; 
        
    ?> 
    </body>
    </html>
     
     
  • Output: When we comment on unset($_SESSION[‘name’]), then you get the following output .

Note: The PHP session_start() function is always written in the beginning of any code.

  • When we do unset($_SESSION[‘name’]), by un-commenting the required line in the example program, you get the following output.
        unset($_SESSION['name']);          //echo "Session Name : ".$_SESSION['name'];    
  • Output:
  • If you want to destroy all the session variables, then use the following PHP function.
    session_destroy();
  • If you want to clear or free up the space occupied by session variables for other use, the following PHP function is used.
    session_unset();
  • Program 2:




    <!DOCTYPE html>
    <html>
       
    <head>
        <title>Unset Session Variable </title>
    </head>
       
    <body>
        <h1 style="color:green">GeeksforGeeks</h1>
        <b> Unset previous session of user</b>
        <?php
         echo '<br>';
         echo '<br>';
         if(isset($_SESSION["user_name"]))
         { echo "Welcome "; echo $_SESSION["user_name"]; }
        ?>
            <form>
                Input your name here:
                <input type="text" id="user_id" name="user_id">
                <input type=submit value=Submit>
            </form>
            <form action="#">
                <input type="submit" name="submit"
                       value="Unset"
                       onclick="UnsetPreviousSession()">
            </form>
        <?php 
       
        session_start();
       
        if(!isset($_SESSION["user_name"]) && (!empty($_GET['user_id'])))
        {
            $_SESSION["user_name"] = $_GET["user_id"];
        }
        else
        { 
            UnsetPreviousSession();
        }
        function UnsetPreviousSession()
        {
           unset($_SESSION['user_name']); 
        }
        ?>
    </body>
       
    </html>
     
     
  • Output: After clicking the Unset button, the following output screen is visible for re-entry which shows the previous session variable is unset.


Next Article
How to set & unset session variable in codeigniter ?

G

geetanjali16
Improve
Article Tags :
  • PHP
  • Web Technologies
  • PHP-Misc

Similar Reads

  • How to Use Session Variables with NodeJS?
    When building web applications with NodeJS, managing session data becomes an important task, especially for things like user authentication, shopping carts, or temporary data storage. In this article, we will explore how to use session variables in NodeJS. What are Session Variables?Session variable
    5 min read
  • How to register a variable in PHP session ?
    The PHP session is required so that you can store the user information and use it on different pages of the browser. Approach: It creates a session with the name or any other useful information you want to store and access on different pages. Even after your page is closed you can access the informa
    3 min read
  • How to set & unset session variable in codeigniter ?
    The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command. $this->load->library('session'); Set the session v
    2 min read
  • PHP | Sessions
    PHP sessions are a tool used to store user-specific data across multiple pages during a single visit to a website. They solve the problem of maintaining a state in a stateless environment, where each page load is independent. Without sessions, a website would not be able to remember user information
    7 min read
  • PHP Variables
    A variable in PHP is a container used to store data such as numbers, strings, arrays, or objects. The value stored in a variable can be changed or updated during the execution of the script. All variable names start with a dollar sign ($).Variables can store different data types, like integers, stri
    5 min read
  • JSP - Session Tracking
    Session tracking is essential in web development to maintain user state and data as they navigate across different pages of a web application. JSP (JavaServer Pages) provides various mechanisms to implement session tracking, allowing web applications to associate requests with specific users and ret
    7 min read
  • JavaScript sessionStorage
    JavaScript sessionStorage is a web storage technique that stores data for the duration of a page session. The sessionStorage object lets you store key/value pairs in the browser. It allows setting, retrieving, and managing data that persists only until the browser tab or window is closed, ensuring d
    4 min read
  • Variables and Datatypes in PHP
    A variable in PHP is a container used to store data. The value of a variable can change during program execution. PHP variables start with a dollar sign ($), followed by the variable name. $name = "GFG";$age = 30;Declaring Variables in PHPTo declare a variable, you simply use the dollar sign followe
    4 min read
  • PHP SplObjectStorage unserialize() Function
    The SplObjectStorage::unserialize() function is an inbuilt function in PHP which is used to unserialize the storage from its serialize string representation. Syntax: void SplObjectStorage::unserialize( $serilize ) Parameters: This function accepts a single parameter $serialize which specifies the st
    1 min read
  • What is the use of the $_REQUEST variable in PHP ?
    Uses of PHP $_REQUEST: The PHP $_REQUEST is a PHP superglobal variable that is used to collect the data after submitting the HTML forms as the $_REQUEST variable is useful to read the data from the submitted HTML open forms.$_REQUEST is an associative array that by default contains contents of an $_
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences