w3resource

PHP script: Display last session access time

PHP Cookies and Sessions: Exercise-15 with Solution

Write a PHP script to display the last time the session was accessed by the user.

Sample Solution:

PHP Code :

<?php
// Set the session save path
session_save_path('i:/custom/');
session_start();

if (isset($_SESSION['last_access_time'])) {
    $lastAccessTime = $_SESSION['last_access_time'];
    echo "Last access time: " . date('Y-m-d H:i:s', $lastAccessTime);
    $_SESSION['last_access_time'] = time(); // Update the last access time
} else {
    $_SESSION['last_access_time'] = time();
    echo "Session started. First access.";
}

?>

Sample Output:

Session started. First access.
Last access time: 2019-07-12 04:46:38
 
Last access time: 2019-07-12 04:46:59

Explanation:

In the above exercise -

We start the session using session_start() to initialize the session.

  • Check if the session variable 'last_access_time' is set. If it is set, retrieve its value and store it in $lastAccessTime.
  • Use echo to display the last access time using date() to format the timestamp into a human-readable date and time format.
  • After displaying the last access time, we update the 'last_access_time' session variable with the current time using time() to record the new access time.

If the 'last_access_time' session variable is not set, we set it to the current time. We display a message indicating that the session has started and this is the first access.

Flowchart:

Flowchart: PHP script: Display last session access time.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Regenerate session ID for security.
Next: Cookie and session variable comparison.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/cookies-sessions/php-cookies-sessions-exercise-15.php