Created
December 17, 2012 16:47
-
-
Save lavoiesl/4319721 to your computer and use it in GitHub Desktop.
Load a PHP session only when needed
http://blog.lavoie.sl/2012/12/properly-create-and-destroy-php-session.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| # global.php | |
| # In some global configuration file, | |
| # Start the session only if the cookie is present | |
| if (isset($_COOKIE[session_name()])) { | |
| session_start(); | |
| } | |
| # In the same file or elsewhere, after the previous lines: | |
| if (isset($_SESSION['userid'])) { | |
| # If the session has been loaded and the userid is detected, set it | |
| $userid = $_SESSION['userid']; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| # login.php | |
| # We start a session if it not already started | |
| session_id() == '' && session_start(); | |
| $_SESSION['userid'] = '1'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| # logout.php | |
| session_start(); | |
| # Destroy the session, this is for the current request | |
| session_destroy(); | |
| # Ensure that the cookie is destructed by setting a date in the past | |
| setcookie(session_name(), false, time() - 3600); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment