Automatic refresh only once in PHP

Asked

Viewed 640 times

0

I need to do an automatic "refresh" on some pages of a customer’s site. However, this "refresh" needs to happen only A time.

I know I could put the meta tag below, for example:

<meta content="3;url=http://www.meusite.com.br/index.php" http-equiv="Refresh" />

But it would update every 3 seconds. And I wanted it to update only once. How can I do that? Using SESSION, COOKIE or something else?

1 answer

0


Hello, Gustavo.

One solution I see is to use URL parameters along with the function time() of PHP.

$show = false;

if (isset($_GET['t']) {
  $time = $_GET['t'];

  if (time() - $time > 5) {
    $show = true;
  }
} else {
  $show = true;
}

if ($show) {
  echo '<meta content="3;url=http://www.meusite.com.br/index.php?t=' . time() . '" http-equiv="Refresh" />';
}

Explaining the code:

  1. Defined the variable $show, which will indicate whether to insert the update command after 3 seconds, initially set in false (not show unless...);
  2. Checking the existence of the URL parameter t which stores the second time of the last time which called the page update command;
    1. Once existing, compare the difference from the last time it called the update function with the current time;
      1. If the difference is greater than 5 seconds (considering 3 seconds plus an error margin of 2 seconds), it is a sign that this time was an "old" request, which validates a new page update, considering a new user: $show = true.
    2. No URL parameter exists t, characterizes how a new user porting is shown the page update command $show = true.
  3. If $show == true displays the page update command, being sent with the parameter t = time(), current time in seconds.

Possible problem of this algorithm:
If the page takes more than two seconds to load, it is possible that this goes beyond the margin of error of time (of two seconds), which will always be considered as a new user, updating to any request.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.