Home >Backend Development >PHP Tutorial >How Can I Redirect a PHP Page After Function Execution Using `header()`?
PHP Page Redirection: Achieving Redirection After Function Execution
In PHP, the header() function provides a convenient way to redirect a page after executing functions. This functionality allows you to control the flow of your application and direct users to specific pages based on certain conditions.
Consider the following code snippet:
if (...) { // I am using echo here. } else if ($_SESSION['qnum'] > 10) { session_destroy(); echo "Some error occured."; // Redirect to "user.php". }
In this example, you want to redirect the page to "user.php" if a specific condition is met. To achieve this, you can use the header() function as follows:
if (...) { // I am using echo here. } else if ($_SESSION['qnum'] > 10) { session_destroy(); echo "Some error occured."; header("Location: http://www.yourwebsite.com/user.php"); exit(); }
The header() function takes the URL of the destination page as its argument. After calling header(), you should invoke the exit() function to prevent any further code execution that could interfere with the redirect.
Note that the header() function must be called before any output is sent to the browser, including empty lines, HTML tags, or echoes. This is because any output sent before header() will disrupt its proper execution.
By utilizing the header() function, you can efficiently redirect your PHP pages based on specific conditions, providing a seamless user experience and better control over your application's flow.
The above is the detailed content of How Can I Redirect a PHP Page After Function Execution Using `header()`?. For more information, please follow other related articles on the PHP Chinese website!