SandyBr
SandyBr

Reputation: 11969

php session lock

I want the code snippet

 echo "This is a test";

to be printed once every hour. So when the user loades index.php the first time it should be printed. When the user immediately after that reloads the page it should dissapear. After one hour it should be printed again... How can I do this? Thanks.

Upvotes: 0

Views: 677

Answers (3)

Pekka
Pekka

Reputation: 449485

This should work:

session_start();

if (!isset($_SESSION["last_shown"]))             // If the session variable 
                                                 // was never set
or ($_SESSION["last_shown"] < (time() - 3600))   // or was set more than
                                                 // 1 hour (3600 secs) ago
 {
  echo "This is a test";                         // Make output
  $_SESSION["last_shown"] = time();              // Update session variable 
                                                 // with current time
 }

Upvotes: 4

Michael Berkowski
Michael Berkowski

Reputation: 270637

Rather than sessions, set a cookie to expire in 1 hour. on page load, if the cookie is there don't display the message. The advantage over sessions is that the user can close the browser and return later (if you want that)

if (!isset($_COOKIE['sesslock']))
{
  // No cookie - show message & set cookie (expires in 1 hour, 3600sec)
  setcookie('sesslock','ok', time()+3600);
  echo "this is a test";
}
else
{
  // The cookie is there, don't display your message
}

Upvotes: 3

Naftali
Naftali

Reputation: 146310

you can set the current time to a $_SESSION variable and if the user changes the page check the session time variable. and if that time is greater than one hour, than display the message

Upvotes: 0

Related Questions