32

I have read all your posts about inserting headers into a php form file in order to redirect the user to another URL AFTER the form is submitted - but I can't figure out how to do it. Below is my code. Can you show me where to put the header/redirect so that the information gets e-mailed and then the user goes to another html page?

    <?php
    if(isset($_POST['email'])) {

    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "pecraig@moneymovers.com";
    $email_subject = "Mailing List Form";

    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you
       submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }

   // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['company']) ||
        !isset($_POST['street']) ||
        !isset($_POST['city']) ||
        !isset($_POST['state']) ||
        !isset($_POST['zip'])) {
        died('We are sorry, but there appears to be a problem with the form you 
    submitted.');      
    }

    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // required
    $company = $_POST['company']; // required
    $street = $_POST['street']; // required
    $city = $_POST['city']; // required
    $state = $_POST['state']; // required
    $zip = $_POST['zip']; // required

    $error_message = "";
    $string_exp = "/^[A-Za-z0-9 .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'The First Name you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
  }  
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$company)) {
    $error_message .= 'The Company you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$street)) {
    $error_message .= 'The Street you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$city)) {
    $error_message .= 'The City you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$state)) {
    $error_message .= 'The State you entered does not appear to be valid.<br />';
  }
  if(!preg_match($string_exp,$zip)) {
    $error_message .= 'The Zip Code you entered does not appear to be valid.<br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Response from Mailing List Page.  Please enter in database.\n\n";

    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }

    $email_message .= "First Name: ".clean_string($first_name)."\n";
    $email_message .= "Last Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_from)."\n";
    $email_message .= "Telephone: ".clean_string($telephone)."\n";
    $email_message .= "Company: ".clean_string($company)."\n";
    $email_message .= "Street: ".clean_string($street)."\n";
    $email_message .= "City: ".clean_string($city)."\n";
    $email_message .= "State: ".clean_string($state)."\n";
    $email_message .= "Zip: ".clean_string($zip)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);

?>

<!-- include your own success html here -->

Thanks for subscribing to our mailing list



<?php
}
?>
user2494737
  • 339
  • 1
  • 3
  • 7
  • 1
    Not an answer, but please choose another way [to validate emailaddresses](http://stackoverflow.com/questions/12026842/how-to-validate-an-email-address-in-php/12026863#12026863). – PeeHaa Jun 17 '13 at 22:18
  • 1
    Put `header("Location: thank_you_page.php");` after `@mail($email_to, $email_subject, $email_message, $headers);` and create `thank_you_page.php` with message of your choice. – Funk Forty Niner Jun 17 '13 at 22:26

6 Answers6

67

Right after @mail($email_to, $email_subject, $email_message, $headers);

header('Location: nextpage.php');

Note that you will never see 'Thanks for subscribing to our mailing list'

That should be on the next page, if you echo any text you will get an error because the headers would have been already created, if you want to redirect never return any text, not even a space!

multimediaxp
  • 9,348
  • 13
  • 49
  • 80
13

First give your input type submit a name, like this name='submitform'.

and then put this in your php file

if (isset($_POST['submitform']))
    {   
    ?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>      
    <?php
    }

Don't forget to change the url to yours.

Ari
  • 4,643
  • 5
  • 36
  • 52
  • In some was this seems more reliable. I had a page which was showing erratic behaviour with the header method, switching to this javascript technique seems to have cured it. – Jeremy Young Jan 13 '19 at 15:01
  • thanks for this. having a header issue that seems not to go away. `Warning: Cannot modify header information - headers already sent by` – mukolweke Feb 20 '22 at 12:24
8

If your redirect is in PHP, nothing should be echoed to the user before the redirect instruction.

See header for more info.

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP

Otherwise, you can use Javascript to redirect the user.

Just use

window.location = "http://www.google.com/"
j0k
  • 22,600
  • 28
  • 79
  • 90
Giovanni
  • 108
  • 1
  • 5
3

You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.

For more information and usage: http://php.net/manual/en/function.header.php


I see in your code that you echo() out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.

Saturnix
  • 10,130
  • 17
  • 64
  • 120
  • Right! I want to replace that success message with a redirect. Can I put it where the success message is? – user2494737 Jun 17 '13 at 22:14
  • 1
    ...but what if we need to do both? Is it not possible to both redirect and display text on the page? This is so confusing. I feel like every answer I can find about this isn't clear enough. – Mark Kramer Feb 18 '17 at 01:04
  • How could you possibly show text if you're redirecting the user to another page? This is like asking "how can I both die and read a book?". You either die and can't read or can read and not be death. You could show something and **then** redirect the user (after some time elapsed), but that's not something that can be done server-side. The server serves the page, period. You could serve the page with some JavaScript which instructs to redirect. If you find all this confusing, you have to study and understand the client-server interaction and how a browser/internet works. – Saturnix Feb 18 '17 at 23:18
0

Whenever you want to redirect, send the headers:

header("Location: http://www.example.com/");

Remember you cant send data to the client before that, though.

Frildoren
  • 243
  • 3
  • 9
  • That's just it - I'm a coding klutz and need to know exactly where to put the header in my code example. Thanks – user2494737 Jun 17 '13 at 22:12
  • Instead of Thanks for subscribing to our mailing list, in tags. – Frildoren Jun 17 '13 at 22:13
  • How are we ever supposed to use header if it can't be used after data has been sent to the client? Don't we have to send data to create the form that they're using to trigger the reload in the first place? – Mark Kramer Feb 18 '17 at 01:02
  • It's too different HTTP calls (the example is confusing, would be cleaner in two different files or another better organized structure). When the user sends the form the browser makes a new call to the webserver and in that call you can process your data and send the headers. – Frildoren Feb 21 '17 at 15:22
0

Once had this issue, thought it reasonable to share how I resolved it;

I think the way to do that in php is to use the header function as:

header ("Location: exampleFile.php");

You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:

if (isset($_POST['submit'])){   header("Location: exampleFile.php")   }

Hope that helps.

SmithVyne
  • 1
  • 2