How to write code to redirect in PHP?

In PHP, you can use the header() function to redirect a page. Here are some common examples of page redirection code:

  1. Redirect to a specific URL:
header("Location: http://www.example.com");
exit;
  1. Navigate to another page in the current directory.
header("Location: another_page.php");
exit;
  1. Delay redirecting to a specified URL, and wait for a certain amount of time before redirecting.
header("Refresh: 5; URL=http://www.example.com");
exit;

The number 5 in the code above indicates a delay of 5 seconds before proceeding.

Note:

  1. Before using the header() function, there should not be any content outputted to the browser, including spaces and line breaks. Otherwise, it will result in an “headers already sent” error.
  2. After calling the header() function, it is usually necessary to use the exit or die functions to terminate the script’s execution in order to ensure that the page redirects immediately.
  3. The header() function must be called before sending any content, including spaces and line breaks.
bannerAds