Write php program to delete session

In this tutorial you will learn how to store certain data on the server on a temporary basis using PHP session.

What is a Session

Although you can store data using cookies but it has some security issues. Since cookies are stored on user's computer it is possible for an attacker to easily modify a cookie content to insert potentially harmful data in your application that might break your application.

Also every time the browser requests a URL to the server, all the cookie data for a website is automatically sent to the server within the request. It means if you have stored 5 cookies on user's system, each having 4KB in size, the browser needs to upload 20KB of data each time the user views a page, which can affect your site's performance.

You can solve both of these issues by using the PHP session. A PHP session stores data on the server rather than user's computer. In a session based environment, every user is identified through a unique number called session identifier or SID. This unique session ID is used to link each user with their own information on the server like emails, posts, etc.

Tip: The session IDs are randomly generated by the PHP engine which is almost impossible to guess. Furthermore, because the session data is stored on the server, it doesn't have to be sent with every browser request.

Starting a PHP Session

Before you can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user.

The PHP code in the example below simply starts a new session.

The session_start() function first checks to see if a session already exists by looking for the presence of a session ID. If it finds one, i.e. if the session is already started, it sets up the session variables and if doesn't, it starts a new session by creating a new session ID.

Note: You must call the session_start() function at the beginning of the page i.e. before any output generated by your script in the browser, much like you do while setting the cookies with setcookie() function.


Storing and Accessing Session Data

You can store all your session data as key-value pairs in the $_SESSION[] superglobal array. The stored data can be accessed during lifetime of a session. Consider the following script, which creates a new session and registers two session variables.

To access the session data we set on our previous example from any other page on the same web domain — simply recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative array.

The PHP code in the example above produce the following output.

Hi, Peter Parker

Note: To access the session data in the same page there is no need to recreate the session since it has been already started on the top of the page.


Destroying a Session

If you want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array, as shown in the following example:

However, to destroy a session completely, simply call the session_destroy() function. This function does not need any argument and a single call destroys all the session data.

Note: Before destroying a session with the session_destroy() function, you need to first recreate the session environment if it is not already there using the session_start() function, so that there is something to destroy.

Every PHP session has a timeout value — a duration, measured in seconds — which determines how long a session should remain alive in the absence of any user activity. You can adjust this timeout duration by changing the value of session.gc_maxlifetime variable in the PHP configuration file (php.ini).

(PHP 4, PHP 5, PHP 7, PHP 8)

session_destroyDestroys all data registered to a session

Description

session_destroy(): bool

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.

In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that.

When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites.

Warning

Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links.

Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly.

To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Destroying a session with $_SESSION

// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();// Unset all of the session variables.
$_SESSION = array();// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    
$params session_get_cookie_params();
    
setcookie(session_name(), ''time() - 42000,
        
$params["path"], $params["domain"],
        
$params["secure"], $params["httponly"]
    );
}
// Finally, destroy the session.
session_destroy();
?>

See Also

  • session.use_strict_mode
  • session_reset() - Re-initialize session array with original values
  • session_regenerate_id() - Update the current session id with a newly generated one
  • unset() - Unset a given variable
  • setcookie() - Send a cookie

Praveen V

10 years ago

If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.

session_start();
session_regenerate_id(true);
?>

[Edited by moderator (googleguy at php dot net)]

Jack Luo

8 years ago

It took me a while to figure out how to destroy a particular session in php. Note I'm not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it's quite useful for functionality of force an user offline.

1. If you're using db or memcached to manage session, you can always delete that session entry directly from db or memcached.

2. Using generic php session methods to delete a particular session(by session id).

$session_id_to_destroy = 'nill2if998vhplq9f3pj08vjb1';
// 1. commit session if it's started.
if (session_id()) {
   
session_commit();
}
// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();// 3. hijack then destroy session specified.
session_id($session_id_to_destroy);
session_start();
session_destroy();
session_commit();// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();?>

JBH

5 years ago

I'm using PHP 7.1 and received the following warning when implementing Example #1, above:

    PHP message: PHP Warning:  session_destroy(): Trying to destroy uninitialized session in...

What I discovered is that clearing $_SESSION and removing the cookie destroys the session, hence the warning.  To avoid the warning while still keeping the value of using session_destroy(), do this after everything else:

    if (session_status() == PHP_SESSION_ACTIVE) { session_destroy(); }

greald at gmail dot com

1 year ago

All of a sudden neither session_destroy() nor $_SESSION=[] were sufficient to log out. I found the next to work:
setcookie(session_name(), session_id(), 1); // to expire the session
$_SESSION = [];
?>

How do you create a session and delete it?

To unset a single session variable, we can use the 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.

What is destroy session in PHP?

Description ¶ session_destroy(): bool. session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie.

How do you delete a session?

You can use the following procedure in Chrome:.
Hit F12 or open the contextual menu (right click), then "Inspect element".
Go to the Application tab..
On the right sidebar menu, go to Application > Clear storage..
Uncheck everything but Local and session storage..
Scroll to the very down and click Clear site data..

Which function is used to delete session?

1 Answer. The best explanation: The function session_unset() frees all session variables that is currently registered. This will not completely remove the session from the storage mechanism. If you want to completely destroy the session, you need to use the function session_destroy().