Home » Programming » PHP » Php Refresh Page

Refresh or Redirect a Page using PHP, With Examples

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:

header("Refresh:0; url=another-page.php");

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.

It Could be Better to use JavaScript

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.

It could be better to use JavaScript for this task – we’ve covered it in the below article.

How to Refresh the Page in JavaScript using location.reload(), With Examples

Refreshing is a client-side operation. JavaScript is the client-side scripting language used by web browsers, so it can be better to do it this way rather than using server-side PHP to dictate what the client should do.

PHP might be preferable if you want search spiders such as Googlebot to crawl your redirects easily.

SHARE:
Photo of author
Author
My name is Stefan, I'm the admin of LinuxScrew. I am a full-time Linux/Unix sysadmin, a hobby Python programmer, and a part-time blogger. I post useful guides, tips, and tutorials on common Linux and Programming issues. Feel free to reach out in the comment section.

Leave a Comment