Home >Backend Development >PHP Tutorial >How to Redirect a PHP Page After Function Execution Using header()?

How to Redirect a PHP Page After Function Execution Using header()?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 09:34:11295browse

How to Redirect a PHP Page After Function Execution Using header()?

Redirecting PHP Page After Function Execution

In PHP, it is possible to execute a function and then redirect the user to a different page within the same root folder. This can be achieved using the header() function.

Code Example:

Consider the following PHP code snippet:

if (...) {
    // I am using echo here.
} else if ($_SESSION['qnum'] > 10) { 
    session_destroy();
    echo "Some error occured.";
    // Redirect to "user.php".
    header("Location: user.php"); 
    exit();
}

Explanation:

  1. header("Location: user.php");: This line sends a special HTTP header to the browser, instructing it to redirect the user to the specified URL ("user.php").
  2. exit();: It is recommended to call exit() after the header() function to prevent any subsequent code from executing and potentially interfering with the redirect process.

Considerations:

  • header() must be called before any output is sent to the browser, including HTML tags or blank lines. Failing to do so will result in an error.
  • Verify that the redirect code runs before any other output is generated.
  • Avoid using echo or other output commands before header(), as it can interfere with the redirect process.

The above is the detailed content of How to Redirect a PHP Page After Function Execution Using header()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn