Table of Contents
Quick example
About this login session_destory() example
Login page with login form
Dashboard authenticates PHP login session and displays login and logout links
This PHP code is for users who wish to log out before their session expires.
Home Backend Development PHP Tutorial Detailed explanation of how PHP sessions are destroyed after 30 minutes (with code examples)

Detailed explanation of how PHP sessions are destroyed after 30 minutes (with code examples)

Nov 14, 2022 pm 04:34 PM
php session

This article will introduce you to the issue of how to specify the time to destroy the PHP session. Here is a detailed introduction to how to destroy the session through the session_destroy() function. I hope it will be helpful to friends in need~

Detailed explanation of how PHP sessions are destroyed after 30 minutes (with code examples)

PHP has a core function session_destroy() to clear all session values. It is a simple function with no parameters that returns a boolean value of true or false.

PHP's session ID is stored in a cookie by default. Generally, the name of the session cookie file is PHPSESSID. The session_destroy function will not cancel the sessionid in the cookie.

In order to "completely" destroy the session, the session ID must also be unset.

This quick example uses session_destroy() to destroy the session. It uses the set_cookie() method to kill the entire session with an expired PHP session ID.

Quick example

destroy-session.php

<?php
// Always remember to initialize the session,
// even before attempting to destroy it.

// Destroy all the session variables.
$_SESSION = array();

// delete the session cookie also to destroy the session
if (ini_get("session.use_cookies")) {
    $cookieParam = session_get_cookie_params();
    setcookie(session_name(), &#39;&#39;, time() - 42000, $cookieParam["path"], $cookieParam["domain"], $cookieParam["secure"], $cookieParam["httponly"]);
}

// as a last step, destroy the session.
session_destroy();
Copy after login

Note: Use session_start() to restart a PHP session after it is destroyed. Use PHP$_SESSION to unset specific session variables. For older PHP versions, use session_unset(). PHP session destruction output [Recommended learning: PHP video tutorial]

About this login session_destory() example

Let us create a login sample code to use PHP session, session_destroy etc. It allows users to log in and out from the current session. If you are looking for complete user registration and login in PHP script then use this code. This sample provides automatic login session expiration functionality.

Login page with login form

This form posts the username and password entered by the user. It verifies login credentials in PHP. After a successful login, it stores the login status into the PHP session. It sets the expiration time to 30 minutes from the last login time. It stores the last login time and expiration time into the PHP session. These two session variables are used to automatically expire the session.

login.php

<?php
session_start();
$expirtyMinutes = 1;
?>
<html>
<head>
<title>PHP Session Destroy after 30 Minutes</title>
<link rel=&#39;stylesheet&#39; href=&#39;style.css&#39; type=&#39;text/css&#39; />
<link rel=&#39;stylesheet&#39; href=&#39;form.css&#39; type=&#39;text/css&#39; />
</head>
<body>
    <div class="phppot-container">
        <h1>Login</h1>
        <form name="login-form" method="post">
            <table>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="username"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Sign in"
                        name="submit"></td>
                </tr>
            </table>
        </form>
<?php
if (isset($_POST[&#39;submit&#39;])) {
    $usernameRef = "admin";
    $passwordRef = "test";
    $username = $_POST[&#39;username&#39;];
    $password = $_POST[&#39;password&#39;];

    // here in this example code focus is session destroy / expiry only
    // refer for registration and login code https://phppot.com/php/user-registration-in-php-with-login-form-with-mysql-and-code-download/
    if ($usernameRef == $username && $passwordRef == $password) {
        $_SESSION[&#39;login-user&#39;] = $username;
        // login time is stored as reference
        $_SESSION[&#39;ref-time&#39;] = time();
        // Storing the logged in time.
        // Expiring session in 30 minutes from the login time.
        // See this is 30 minutes from login time. It is not &#39;last active time&#39;.
        // If you want to expire after last active time, then this time needs
        // to be updated after every use of the system.
        // you can adjust $expirtyMinutes as per your need
        // for testing this code, change it to 1, so that the session
        // will expire in one minute
        // set the expiry time and
        $_SESSION[&#39;expiry-time&#39;] = time() + ($expirtyMinutes * 60);
        // redirect to home
        // do not include home page, it should be a redirect
        header(&#39;Location: home.php&#39;);
    } else {
        echo "Wrong username or password. Try again!";
    }
}
?>
</div>
</body>
</html>
Copy after login

This is the target page for redirection after login. If a login session exists, it will display a logout link. Once it times out it will call destroy session. php code to destroy all sessions. If the 30 minute expiration time is reached or the session is empty, it will ask the user to log in.

home.php

<?php
session_start();
?>
<html>
<head>
<title>PHP Session Destroy after 30 Minutes</title>
<link rel=&#39;stylesheet&#39; href=&#39;style.css&#39; type=&#39;text/css&#39; />
<link rel=&#39;stylesheet&#39; href=&#39;form.css&#39; type=&#39;text/css&#39; />
</head>
<body>
    <div class="phppot-container">
<?php
if (! isset($_SESSION[&#39;login-user&#39;])) {
    echo "Login again!<br><br>";
    echo "<a href=&#39;login.php&#39;>Login</a>";
} else {
    $currentTime = time();
    if ($currentTime > $_SESSION[&#39;expiry-time&#39;]) {
        require_once __DIR__ . &#39;/destroy-session.php&#39;;
        echo "Session expired!<br><br><a href=&#39;login.php&#39;>Login</a>";
    } else {
        ?>
        <h1>Welcome <?php echo $_SESSION[&#39;login-user&#39;];?>!</h1>
        <a href=&#39;logout.php&#39;>Log out</a>
<?php
    }
}
?>
</div>
</body>
</html>
Copy after login

This PHP code is for users who wish to log out before their session expires.

It destroys the session by asking it to be destroyed. php code. It then redirects the user to the login page. logout.php

<?php
session_start();
require_once __DIR__ . &#39;/destroy-session.php&#39;;
header(&#39;Location: login.php&#39;);
?>
Copy after login

I hope this example helps understand how to destroy a PHP session. And, this is a perfect scenario to explain the need to destroy sessions.

This article is reprinted, original address: https://juejin.cn/post/7164391542164520990

The above is the detailed content of Detailed explanation of how PHP sessions are destroyed after 30 minutes (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles