logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

Destroy a Session in PHP!


Destroy a Session in PHP

To destroy a session in PHP, you can use the session_destroy() function. This function will unset all session variables, effectively ending the session. Here's an example:

 

<?php
// Start the session
session_start();

// Unset all session variables
$_SESSION = array();

// Destroy the session
session_destroy();

// Redirect or display a message as needed
header("Location: login.php"); // Redirect to login page after destroying the session
exit();
?>

In this example:

  1. session_start() initializes or resumes the session.
  2. $_SESSION = array(); unsets all session variables by assigning an empty array to $_SESSION.
  3. session_destroy() destroys the session. Note that this function only destroys the session data on the server; it doesn't unset the session variables or remove the session cookie from the client.
  4. Optionally, you can perform additional actions, such as redirecting the user to a login page or displaying a logout message.

Remember to call session_start() on every page where you want to work with session variables. The example above assumes that the user is redirected to a login page after logging out; adjust the redirection URL according to your application's structure.

If you want to unset specific session variables without destroying the entire session, you can use the unset() function. For example:

<?php
// Start the session
session_start();

// Unset specific session variables
unset($_SESSION['user_id']);
unset($_SESSION['username']);

// Rest of your PHP code
?>

 

This removes the specified session variables without ending the entire session.

 

Thank you.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment