Sick Gaming
[Tut] PHP session time set unset and check existence - Printable Version

+- Sick Gaming (https://www.sickgaming.net)
+-- Forum: Programming (https://www.sickgaming.net/forum-76.html)
+--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html)
+--- Thread: [Tut] PHP session time set unset and check existence (/thread-99082.html)



[Tut] PHP session time set unset and check existence - xSicKxBot - 03-28-2022

PHP session time set unset and check existence

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/03/php-session-time-set-unset-and-check-existence.jpg" width="550" height="277" title="" alt="" /></div><div><div class="modified-on" readability="7.1489361702128"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on November 21st, 2021.</div>
<p>PHP session is one of the methods for keeping data persistency on the server side.</p>
<p>PHP sessions have a deadline time limit for keeping data persistent. PHP configuration file includes directives to have this specification.</p>
<p>We can also create custom code to change the default PHP session deadline.</p>
<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>
<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>
<div class="post-section-highlight" readability="44">
<h2>Quick example</h2>
<p>1. Create a file set-session.php and set value and lifetime.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
session_start();
//Set PHP session with value, time
$currentTime = time();
$_SESSION['color'] = array( "value" =&gt; "blue", "time" =&gt; $currentTime, "life_time" =&gt; 5
);
?&gt;
</code></pre>
<p>2. Create a file check-session.php to compute if the session existence.</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
session_start();
if (isset($_SESSION['color'])) { $sessionSetTime = $_SESSION['color']['time']; $sessionLifeTime = $_SESSION['color']['life_time']; if ((time() - $sessionSetTime) &gt; $sessionLifeTime) { unset($_SESSION['color']); print 'Session expired'; }
}
?&gt;
</code></pre>
</div>
<h2>About PHP session</h2>
<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>
<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>
<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>
<p><img 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="(max-width: 550px) 100vw, 550px"></p>
<h2>PHP session lifetime settings</h2>
<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>
<table class="tutorial-table">
<tbody readability="3">
<tr>
<th>PHP directive</th>
<th>Description</th>
</tr>
<tr readability="2">
<td>session.gc_maxlifetime</td>
<td>It sets the max lifetime after which the session will be elapsed and collected as garbage.</td>
</tr>
<tr readability="4">
<td>session.cookie_lifetime</td>
<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>
</tr>
</tbody>
</table>
<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>
<p><img 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="(max-width: 550px) 100vw, 550px"></p>
<h2>Example: Working with PHP session time – Set expiration and limit lifetime</h2>
<p>This PHP session time handling example is the enhanced version of the above quick example.</p>
<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>
<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>
<p><img 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>
<h3>Landing page to set session</h3>
<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>
<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>
<p class="code-heading">index.php</p>
<pre class="prettyprint"><code class="language-html">
&lt;html&gt;
&lt;head&gt;
&lt;link href="./assets/css/style.css" rel="stylesheet" type="text/css" /&gt;
&lt;/head&gt;
&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;
&lt;/body&gt;
&lt;/html&gt; </code></pre>
<h3>Check PHP session time via JavaScript AJAX</h3>
<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>
<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>
<p class="code-heading">session.js</p>
<pre class="prettyprint"><code class="language-javascript">
if($('.session').data('status') != "") { var interval; interval=setInterval(checkSession, 5000); $("#status").text("Checking session expiration status...");
}
function 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); } } } });
};
</code></pre>
<h2>Set unset PHP session time</h2>
<p>In this section, it shows two PHP files to set and unset the PHP session time.</p>
<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>
<p>Each session array is a multi-dimensional associative array. It has the details of PHP session set time, lifetime and value.</p>
<p>The session set-time and lifetime are used to calculate the session expiry.</p>
<p class="code-heading">set-session.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
if (! isset($_SESSION)) { session_start();
}
$currentTime = time();
$_SESSION['color'] = array( "value" =&gt; "blue", "time" =&gt; $currentTime, "lifetime" =&gt; 3
);
$_SESSION['shape'] = array( "value" =&gt; "circle", "time" =&gt; $currentTime, "lifetime" =&gt; 5
);
$_SESSION['size'] = array( "value" =&gt; "big", "time" =&gt; $currentTime, "lifetime" =&gt; 10
);
header("Location: index.php?status=starts");
exit();
?&gt; </code></pre>
<p>This code returns the response text once the session is expired.</p>
<p>It validates the session expiry by comparing the remaining time and the PHP session lifetime.</p>
<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>
<p class="code-heading">check-session.php</p>
<pre class="prettyprint"><code class="language-html">
&lt;?php
if (! isset($_SESSION)) { session_start();
} if (! isset($_SESSION['color']) &amp;&amp; (! isset($_SESSION['shape'])) &amp;&amp; (! isset($_SESSION['size']))) { print - 1;
}
if (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;'; }
}
exit();
?&gt; </code></pre>
<h2>Conclusion</h2>
<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>
<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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-session-time-set-unset/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2021/10/14/php-session-time-set-unset-and-check-existence/