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 :

// Set the session save path

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


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: 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.

Follow us on Facebook and Twitter for latest update.