Open In App

Refresh a page using PHP

Last Updated : 27 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, you can refresh a page using the header() function. You can automatically reload the page by setting the Refresh header with a time interval. For example, the header(“Refresh: 5”); reloads the page every 5 seconds after sending the response to the browser.

Syntax:

void header( $header, $replace = TRUE, $http_response_code )
Or
header(string, replace, http_response_code)

Parameters:

  • $header: It holds the header string. There are two types of header calls. The first header starts with the string “HTTP/”, which is used to figure out the HTTP status code to send. The second case of the header is the “Location:”. It is a mandatory parameter.
  • $replace: It is optional parameter. It denotes the header should replace previous or add a second header. The default value is True (will replace). If $replace value is False then it force multiple headers of the same type.
  • $http_response_code: It is an optional parameter. It forces the HTTP response code to the specified value (PHP 4.3 and higher).

Note: This function prevents more than one header to be sent at once. This is a protection against header injection attacks after PHP 4.4 release. Below example illustrates the use of header() to refresh current page in PHP:

Example: This example we demonstrates the use of the header() function to refresh the current page every 3 seconds, displaying a message and dynamically updating the current time and date.

php
<?php

// Demonstrate the use of header() function
// to refresh the current page
 
echo "Welcome to index page</br>";
echo "Page will refresh in every 3 seconds</br></br>";
  
// The function will refresh the page 
// in every 3 second
header("refresh: 3");
  
echo date('H:i:s Y-m-d');

exit;
?>

Output:

Example 2: This example we demonstrates using the header() function to redirect the user to the GeeksForGeeks website after 3 seconds, displaying a message before redirecting.

php
<?php

// Demonstrate the use of header() function
// to refresh the current page
 
echo "Welcome to index page</br>";
echo "we will redirect to GeeksForGeeks Official website in 3 second";
  
// The function will redirect to geeksforgeeks official website
header("refresh: 3; url = https://www.geeksforgeeks.org/");
  
exit;
?>

Output:

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



Next Article

Similar Reads