Home >Backend Development >PHP Tutorial >How to Redirect a User to Another Page After PHP Form Submission?

How to Redirect a User to Another Page After PHP Form Submission?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 18:28:03569browse

How to Redirect a User to Another Page After PHP Form Submission?

Redirecting a User to Another Page After PHP Form Submission

Challenge

Many users have encountered difficulties redirecting users to another page after submitting a form in PHP. This issue arises when developers attempt to replace the current page's content with custom "success" HTML without considering the proper timing.

The Solution

To resolve the issue, the redirect header should be added immediately after the @mail($email_to, $email_subject, $email_message, $headers); line.

<code class="php"><?php
    // ...
    @mail($email_to, $email_subject, $email_message, $headers);
    // Redirect to another PHP page
    header('Location: nextpage.php');
    // ...
?></code>

Explanation

  1. The @mail function sends the email.
  2. The header function sets the HTTP response header, which instructs the browser to redirect to a new URL.
  3. It's crucial to avoid output after setting the header. Any subsequent output (including a blank space or line break) will cause errors and prevent redirection.

Note

This method of redirection will prevent the "Thanks for subscribing to our mailing list" message from displaying on the current page. Instead, this message should be displayed on the redirected page.

The above is the detailed content of How to Redirect a User to Another Page After PHP Form Submission?. 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