It’s important to note that you must call the function before outputting anything to the screen, otherwise you’ll get an error.
Here’s the full example of your mail.php page with the page redirection code added. I’ve also added some basic filtering of your form data, which is always a good idea when you’re dealing with input from users. Although I’ve not shown it here, you might also want to check that the email address supplied is valid, and $message isn’t empty before you send the email.
<?php
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$message = filter_input(INPUT_POST, 'message', FILTER_SANITIZE_SPECIAL_CHARS);
$formcontent = "From: $name \
Message: $message";
$recipient = "enquiries@la-matha.com";
$subject = "Contact Form";
$mailheader = "From: $email \\r\
";
if ( mail($recipient, $subject, $formcontent, $mailheader) ){
header('Location: http://www.la-matha.com/contact2.php');
exit;
} else {
// Would be better to present some kind of friendly error for your users!
die("Error!");
}
Thanks for the help - it works exactly as I want it to. I’m not going to bother with validation - to be honest, I don’t expect much traffic, but I wanted something that looked professional.
Can you explain what you mean? I’ve never had a problem using the header function to do a redirect… the location header is part of the HTTP spec and should work across all browsers.
I’d avoid using JS to do a redirection if possible because obviously it’s going to break if the user has JS disabled.
I am not sure about that, while i used header function it shows error “Cannot modify header information - headers already sent by (output started at… )” . What is reason its shows this error?