Jump to content

header();


talkingAnimals

Recommended Posts

I am very very new to PHP and I need to create a simple contact form that requires only one field to be filled in. I found a tutorial to build it and it works great, I just want to make one modification. Instead of going to a blank page that outputs my thank you message, I want to redirect to a thank you page (an html file that is styled and looks like it's part of my site).

 

I thought I would simply replace echo ("bla blah"); with header("location:url"); but it doesn't seem to work.

 

<?php


$email = '[email protected]';
$subject = 'Frolick - Email Sign Up';
$message = $HTTP_POST_VARS['message'];

if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $message)) {
  echo "<h4>Invalid email address</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
  echo "<h4>No subject</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
}

elseif (mail($email,$subject,$message)) {
  echo "<h4>Thank you for sending email</h4>";
} else {
  echo "<h4>Can't send email to $email</h4>";
}
?>

 

 

I want to replace this portion:

 

elseif (mail($email,$subject,$message)) {
  echo "<h4>Thank you for sending email</h4>";
} else {
  echo "<h4>Can't send email to $email</h4>";
}

 

 

With something like this:

 

else if (mail($email,$subject,$message)) {
  header( "Location: thanks.html" );
} else {
  header( "Location: sorry.html" );
}

 

 

But it's a no go... any ideas?

 

Link to comment
https://forums.phpfreaks.com/topic/179251-header/
Share on other sites

You cannot have any output before a header() redirect.

 

So you should buffer your output, this way it will not be displayed unless needed. If your validation checks fail, flush your buffer.  On success, clear your buffer and redirect.

 

Untested below:

 

<?php
ob_start(); //Buffer your Output

$email = '[email protected]';
$subject = 'Frolick - Email Sign Up';
$message = $HTTP_POST_VARS['message'];

if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $message)) {
  echo "<h4>Invalid email address</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
  echo "<h4>No subject</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
}

elseif (mail($email,$subject,$message)) {
ob_clean(); //clear buffer [or perhaps ob_end_clean()]  
header("location:thankyou.html");
exit();
} else {
  echo "<h4>Can't send email to $email</h4>";
}

//made it to the end so output your buffer
ob_flush(); //or was it ob_end_flush()
?>

 

Link to comment
https://forums.phpfreaks.com/topic/179251-header/#findComment-945752
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.