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:
- Redirect to a specific URL:
header("Location: http://www.example.com");
exit;
- Navigate to another page in the current directory.
header("Location: another_page.php");
exit;
- 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:
- 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.
- 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.
- The header() function must be called before sending any content, including spaces and line breaks.