This article will show you how to refresh a web page in the browser using the PHP programming language.
It’s sometimes necessary to set a page to reload automatically, usually at some interval, to keep the page updated with changing information.
For example, you may have a scoreboard application that is displayed in a web browser on a projector and wish to have it periodically refresh to keep the displayed scores up to date with those stored.
Periodic refreshing is also used to redirect to a different page at a given interval, which could be used to emulate slideshow functionality for digital signage.
Refreshing the Page Using PHP
The PHP header function is used to set HTTP request headers – bits of information invisible to the end-user which tell the web browser about the data it is receiving.
The Refresh header tells the browser to refresh the page after a given number of seconds:
<?php header("Refresh:0"); ?>
Above, the page is refreshed immediately, as 0 seconds is specified. To refresh after 3 seconds, you would use:
<?php header("Refresh:3"); ?>
The Refresh header is not an official specification – most if not all browsers do heed it, but it is worth testing with your intended audience.
Redirecting to a Different Address Using PHP
The Refresh header also accepts an optional url if you wish to redirect to another page:
Above, when the PHP is executed during page load, it will immediately redirect to the another-page.php. Any kind of URL can be supplied – it doesn’t have to be a local file on your server.
Refreshing the page using PHP can be less than ideal. The user will have no interaction or ability to interrupt the refresh request, and you cannot perform any client-side operations as they may take longer than you expect – meaning your page is refreshed before tasks are complete and unexpected behavior may result.
PHP might be preferable if you want search spiders such as Googlebot to crawl your redirects easily.