w3resource

PHP script: Display last session access time


15. Display Last Session Access Time

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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to store the last access time in a session variable and display it on each page load.
  • Write a PHP function to update the last accessed timestamp in the session and output a formatted time string.
  • Write a PHP program to retrieve and display the last session access time using custom date formatting.
  • Write a PHP script to compare the last access time with the current time and display a message indicating activity duration.

Go to:


PREV : Regenerate Session ID to Prevent Fixation.
NEXT : Set Cookie and Session Variable with Same Name.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.