Refresh the current page using PHP.

This is a short guide on how to refresh the current page using PHP. Because PHP is a server-side language, we will need to send a HTTP header to the browser instructing it to refresh after a certain period of time.

Using PHP to refresh the page after five seconds.

Take a look at the following snippet:

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. Obviously, you can change the $refreshAfter variable to suit your own needs.

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

HTTP Refresh Header

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

Note that this header can also be used to redirect to another URL after a certain period of time. For more on that, you can check out this guide that I wrote.

Refresh the page once.

To refresh the page once, you can make use of PHP sessions like so:

In the example above, we used session variables to prevent any further page refreshes. If you run the code above, you will find that the page only refreshes once and that the Refresh header is not present in the page second load.

See also: Reloading pages with JavaScript.

Facebook Comments