{"id":123222,"date":"2021-10-14T04:22:37","date_gmt":"2021-10-14T04:22:37","guid":{"rendered":"https:\/\/phppot.com\/?p=15694"},"modified":"2021-10-14T04:22:37","modified_gmt":"2021-10-14T04:22:37","slug":"php-session-time-set-unset-and-check-existence","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2021\/10\/14\/php-session-time-set-unset-and-check-existence\/","title":{"rendered":"PHP session time set unset and check existence"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1489361702128\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on November 21st, 2021.<\/div>\n<p>PHP session is one of the methods for keeping data persistency on the server side.<\/p>\n<p>PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification.<\/p>\n<p>We can also create custom code to change the default PHP session deadline.<\/p>\n<p>This article contains sections that describe the PHP sessions, their time-limit configurations. It provides examples for setting session limits and tracking existence.<\/p>\n<p>The below example gives <span>a quick solution to set PHP session time<\/span>. It contains only two steps to set and track the session expiration status.<\/p>\n<div class=\"post-section-highlight\" readability=\"44\">\n<h2>Quick example<\/h2>\n<p>1. Create a file set-session.php and set value and lifetime.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\nsession_start();\n\/\/Set PHP session with value, time\n$currentTime = time();\n$_SESSION['color'] = array( \"value\" =&gt; \"blue\", \"time\" =&gt; $currentTime, \"life_time\" =&gt; 5\n);\n?&gt;\n<\/code><\/pre>\n<p>2. Create a file check-session.php to compute if the session existence.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\nsession_start();\nif (isset($_SESSION['color'])) { $sessionSetTime = $_SESSION['color']['time']; $sessionLifeTime = $_SESSION['color']['life_time']; if ((time() - $sessionSetTime) &gt; $sessionLifeTime) { unset($_SESSION['color']); print 'Session expired'; }\n}\n?&gt;\n<\/code><\/pre>\n<\/div>\n<h2>About PHP session<\/h2>\n<p>We have already seen <a href=\"https:\/\/phppot.com\/php\/session-vs-cookies\/\">PHP sessions and cookies<\/a> in a previous article. PHP sessions are for managing application data, state persistent during the working flow.<\/p>\n<p>There are a lot of uses of sessions in an application. The below list shows some of the states or data managed by the use of sessions.<\/p>\n<p>We have seen how to create a <a href=\"https:\/\/phppot.com\/php\/php-login-script-with-session\/\">login script using the PHP session<\/a>. In that, the session lifetime tracking can be used to log out after few minutes of inactivity.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-15721\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-550x277.jpg\" alt=\"php session\" width=\"550\" height=\"277\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-550x277.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-300x151.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-768x387.jpg 768w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session.jpg 930w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>PHP session lifetime settings<\/h2>\n<p>This section describes the configuration directives used to set PHP session time. The below table shows two <a href=\"https:\/\/phppot.com\/php\/php-ini-file\/\">PHP.ini settings<\/a> related to the session.<\/p>\n<table class=\"tutorial-table\">\n<tbody readability=\"3\">\n<tr>\n<th>PHP directive<\/th>\n<th>Description<\/th>\n<\/tr>\n<tr readability=\"2\">\n<td>session.gc_maxlifetime<\/td>\n<td>It sets the max lifetime after which the session will be elapsed and collected as garbage.<\/td>\n<\/tr>\n<tr readability=\"4\">\n<td>session.cookie_lifetime<\/td>\n<td>It sets the time limit for the session cookie in seconds. Default is 0 which means to be persistent until the client quits. Note: PHP session_set_cookie_params() sets all the session cookie parameters in runtime.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The below PHP info highlights the session configuration settings. Refer to more <a href=\"https:\/\/www.php.net\/manual\/en\/session.configuration.php\" target=\"_blank\" rel=\"noopener\">runtime session configuration directives<\/a> in the linked official site.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-large wp-image-15732\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-settings-550x244.jpg\" alt=\"php session settings\" width=\"550\" height=\"244\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-settings-550x244.jpg 550w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-settings-300x133.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-settings.jpg 600w\" sizes=\"auto, (max-width: 550px) 100vw, 550px\"><\/p>\n<h2>Example: Working with PHP session time \u2013 Set expiration and limit lifetime<\/h2>\n<p>This PHP session time handling example is the enhanced version of the above quick example.<\/p>\n<p>It creates three session variables to set color, shape and size. It sets the lifetime for each PHP session variable while setting values.<\/p>\n<p>The PHP code checks if the session exists. Once the time is reached, it <a href=\"https:\/\/phppot.com\/php\/php-unlink-vs-unset\/\">unset<\/a> that particular session variable and destroys it.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-15742\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/10\/php-session-time-files.jpg\" alt=\"php session time files\" width=\"180\" height=\"142\"><\/p>\n<h3>Landing page to set session<\/h3>\n<p>The landing page of this example shows a control to set the PHP session time. Once started, the session expiration status is checked at a periodic interval. This page includes the AJAX script to raise the call to PHP to check the session.<\/p>\n<p>If the PHP session time is over, then this page will display a notice to the user. After all the sessions are expired, then the page will clear the notification and ask to reset the session.<\/p>\n<p class=\"code-heading\">index.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;html&gt;\n&lt;head&gt;\n&lt;link href=\".\/assets\/css\/style.css\" rel=\"stylesheet\" type=\"text\/css\" \/&gt;\n&lt;\/head&gt;\n&lt;body&gt; &lt;div class=\"session\" data-status='&lt;?php if(!empty($_GET[\"status\"])) { echo $_GET[\"status\"]; } ?&gt;'&gt; &lt;div id=\"box\"&gt; &lt;h1 align=\"center\"&gt;Set PHP session time&lt;\/h1&gt; &lt;div class=\"text\"&gt; &lt;a href=\"set-session.php\" class=\"btn\"&gt;Reset Session&lt;\/a&gt; &lt;\/div&gt; &lt;div id=\"status\"&gt;&lt;\/div&gt; &lt;\/div&gt; &lt;div id=\"message\"&gt;&lt;\/div&gt; &lt;\/div&gt; &lt;script src=\"https:\/\/code.jquery.com\/jquery-3.6.0.min.js\"&gt;&lt;\/script&gt; &lt;script src=\".\/assets\/js\/session.js\"&gt;&lt;\/script&gt;\n&lt;\/body&gt;\n&lt;\/html&gt; <\/code><\/pre>\n<h3>Check PHP session time via JavaScript AJAX<\/h3>\n<p>This script sets an interval to <a href=\"https:\/\/phppot.com\/php\/ajax-programming-with-php\/\">call the AJAX script<\/a> to check the PHP session time. After getting the response, this AJAX <em>success<\/em> block shows the expired PHP sessions.<\/p>\n<p>It checks the PHP session time every 5 seconds via AJAX. This script uses JavaScript&nbsp;<em>setInterval()<\/em> to invoke the <em>checkSession()<\/em> method.<\/p>\n<p class=\"code-heading\">session.js<\/p>\n<pre class=\"prettyprint\"><code class=\"language-javascript\">\nif($('.session').data('status') != \"\") { var interval; interval=setInterval(checkSession, 5000); $(\"#status\").text(\"Checking session expiration status...\");\n}\nfunction checkSession(){ $.ajax({ url:\"check-session.php\", method:\"POST\", success:function(response){ if(response!=\"\"){ if(response == -1){ $(\"#status\").hide(); clearInterval(interval); window.location.href='index.php'; } else{ $(\"#message\").append(response); } } } });\n};\n<\/code><\/pre>\n<h2>Set unset PHP session time<\/h2>\n<p>In this section, it shows two PHP files to set and unset the PHP session time.<\/p>\n<p>The <em>set-session.php<\/em> is called on clicking the UI control on the landing page. It sets the color, shape and size in the PHP session.<\/p>\n<p>Each session array is a multi-dimensional associative array. It has the details of PHP session set time, lifetime and value.<\/p>\n<p>The session set-time and lifetime are used to calculate the session expiry.<\/p>\n<p class=\"code-heading\">set-session.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\nif (! isset($_SESSION)) { session_start();\n}\n$currentTime = time();\n$_SESSION['color'] = array( \"value\" =&gt; \"blue\", \"time\" =&gt; $currentTime, \"lifetime\" =&gt; 3\n);\n$_SESSION['shape'] = array( \"value\" =&gt; \"circle\", \"time\" =&gt; $currentTime, \"lifetime\" =&gt; 5\n);\n$_SESSION['size'] = array( \"value\" =&gt; \"big\", \"time\" =&gt; $currentTime, \"lifetime\" =&gt; 10\n);\nheader(\"Location: index.php?status=starts\");\nexit();\n?&gt; <\/code><\/pre>\n<p>This code returns the response text once the session is expired.<\/p>\n<p>It validates the session expiry by comparing the remaining time and the PHP session lifetime.<\/p>\n<p>Once all three sessions are expired, then this code returns -1. On receiving -1, the AJAX callback stops tracking by clearing the interval.<\/p>\n<p class=\"code-heading\">check-session.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-html\">\n&lt;?php\nif (! isset($_SESSION)) { session_start();\n} if (! isset($_SESSION['color']) &amp;&amp; (! isset($_SESSION['shape'])) &amp;&amp; (! isset($_SESSION['size']))) { print - 1;\n}\nif (isset($_SESSION['color'])) { $sessionTimeColor = $_SESSION['color']['time']; $sessionLifeTimeColor = $_SESSION['color']['lifetime']; if ((time() - $sessionTimeColor) &gt; $sessionLifeTimeColor) { unset($_SESSION['color']); print '&lt;div class=\"response-text\"&gt;&lt;span&gt;Color Session Expired&lt;\/span&gt;&lt;\/div&gt;'; } } if (isset($_SESSION['shape'])) { $sessionTimeShape = $_SESSION['shape']['time']; $sessionLifeTimeShape = $_SESSION['shape']['lifetime']; if ((time() - $sessionTimeShape) &gt; $sessionLifeTimeShape) { unset($_SESSION['shape']); print '&lt;div class=\"response-text\"&gt;&lt;span&gt;Shape Session Expired&lt;\/span&gt;&lt;\/div&gt;'; } } if (isset($_SESSION['size'])) { $sessionTimeSize = $_SESSION['size']['time']; $sessionLifeTimeSize = $_SESSION['size']['lifetime']; if ((time() - $sessionTimeSize) &gt; $sessionLifeTimeSize) { unset($_SESSION['size']); print '&lt;div class=\"response-text\"&gt;&lt;span&gt;Size Session Expired&lt;\/span&gt;&lt;\/div&gt;'; }\n}\nexit();\n?&gt; <\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>Thus we have learned how to set PHP session time via programming. This article described the PHP configurations to set max session lifetime.<\/p>\n<p>I hope this example helped to create your own code to manage PHP sessions and time.<br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php-session-time.zip\">Download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-session-time-set-unset\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on November 21st, 2021. PHP session is one of the methods for keeping data persistency on the server side. PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification. We can also create custom code to change the default PHP session [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":123223,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-123222","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123222","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123222"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123222\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/123223"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123222"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123222"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123222"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}