How to refresh a page using PHP.

In this tutorial, we are going to show you how to refresh a page using PHP.

Because PHP is a server-side language, we will need to send an HTTP header.

This header will tell the browser to refresh after a certain period of time.

How to refresh the current page with PHP.

Take a look at the following example:

//The number of seconds to wait before refreshing the current URL.
$refreshAfter = 5;

//Send a Refresh header to the browser.
header('Refresh: ' . $refreshAfter);

In the PHP code above, we sent a Refresh header to the browser by using PHP’s header function.

This meta refresh header tells the browser that it should refresh the current page after five seconds.

If you want to change the number of seconds that it takes, then you can simply modify the $refreshAfter variable.

If you inspect the HTTP response headers using Chrome Developer Tools or something similar, you will see the following:

HTTP Refresh Header

The PHP example above is equivalent to placing the following HTML meta tag in the head of your document:

<meta http-equiv="refresh" content="5" />

You can also use this header to redirect to another URL after a certain period of time. For more information on how to do that, you can check out this guide.

Only refresh it once.

To refresh the page once, you will need to use a session variable like so:

//Start the session.
session_start();

//If the session variable does not exist,
//we will know that the page has not been refreshed yet.
if(!isset($_SESSION['already_refreshed'])){

    //Number of seconds to refresh the page after.
    $refreshAfter = 5;

    //Send a Refresh header.
    header('Refresh: ' . $refreshAfter);

    //Set the session variable so that we don't
    //refresh again.
    $_SESSION['already_refreshed'] = true;

}

In the example above, we used a session variable to prevent any further page refreshes.

If you run the code above, you will see that the header is not present on the second page load.

See also: Reloading pages with JavaScript.