


Detailed explanation of how PHP sessions are destroyed after 30 minutes (with code examples)
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~
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(), '', time() - 42000, $cookieParam["path"], $cookieParam["domain"], $cookieParam["secure"], $cookieParam["httponly"]); } // as a last step, destroy the session. session_destroy();
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='stylesheet' href='style.css' type='text/css' /> <link rel='stylesheet' href='form.css' type='text/css' /> </head> <body> <div class="phppot-container"> <h1 id="Login">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['submit'])) { $usernameRef = "admin"; $passwordRef = "test"; $username = $_POST['username']; $password = $_POST['password']; // 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['login-user'] = $username; // login time is stored as reference $_SESSION['ref-time'] = 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 'last active time'. // 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['expiry-time'] = time() + ($expirtyMinutes * 60); // redirect to home // do not include home page, it should be a redirect header('Location: home.php'); } else { echo "Wrong username or password. Try again!"; } } ?> </div> </body> </html>
Dashboard authenticates PHP login session and displays login and logout links
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='stylesheet' href='style.css' type='text/css' /> <link rel='stylesheet' href='form.css' type='text/css' /> </head> <body> <div class="phppot-container"> <?php if (! isset($_SESSION['login-user'])) { echo "Login again!<br><br>"; echo "<a href='login.php'>Login</a>"; } else { $currentTime = time(); if ($currentTime > $_SESSION['expiry-time']) { require_once __DIR__ . '/destroy-session.php'; echo "Session expired!<br><br><a href='login.php'>Login</a>"; } else { ?> <h1 id="Welcome-nbsp-php-nbsp-echo-nbsp-SESSION-login-user">Welcome <?php echo $_SESSION['login-user'];?>!</h1> <a href='logout.php'>Log out</a> <?php } } ?> </div> </body> </html>
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__ . '/destroy-session.php'; header('Location: login.php'); ?>
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!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
