I wrote a php contact form but I can't figure out how to redirect a user to a different page...

Here is my code:

<?php
if($_POST){  
$name = $_POST['name']; //gets the entered name  
$email = $_POST['email']; //gets the entered email address  
$subject = $_POST['subject']; //gets the subject  
$message = $_POST['message']; //gets the entered message  
$headers = "From: $email \n"; //Set from email address  
$to = "email@gmail.com"; //Set email address  
//validating the fields if any empty  
if($name != "" && $email != "" && $subject != "" && $message != ""){  
mail($to,$subject,$message,$headers); //calling php mail function  
} else  
{  
echo "Please fill in all fields and submit again!";  
}  
}  
?>
<?php
 $email_from = 'email@gmail.com.com';
    $email_subject = "New Form submission - $subject";  //  Change the message subject here
    $email_body = "You have received a new message from $name ($phone) .\n Here is the message:\n $message. His/Her full contact information is: \n $name \n $email \n 1$phone.";
// Send The Email
  $to = "email@gmail.com";  // Set valid email address to send the form to
  $headers = "From: $email_from \r\n";
  $headers .= "Reply-To: $visitor_email \r\n";
  mail($to,$email_subject,$email_body,$headers);
  ?>

Recommended Answers

All 18 Replies

try

if ( mail($to,$subject,$message,$headers) ) {
    header("Location: page.php");
} else{
    // do something else
}
Member Avatar for LastMitch

@<MICHAEL>

I wrote a php contact form but I can't figure out how to redirect a user to a different page...

What do you mean redirect a user to a different page? If a person submit the form it will post a message that the form has submitted.

I mean let me get this straight after when the user submit the form you want it to be redirected to a different page?

Is that correct?

If so then you need a header function to redirect the user after the form is submited:

<?php
header('Location: http://path/newpage.php'');
?>

You can write your redirection code right after

mail($to,$subject,$message,$headers); //calling php mail function 
header("Location: page.php");

that will redirecy after sending the mail

Wow thanks you guys, the information helped a lot!
Here is what I ended up using:

$url= "http://somewebpage.com";
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';

But I began to think again, it doesn't look great when you get redirected to a new page. So my new thinking is how do you keep the user on the same page after they submit the form because normally if you submit, it'd take you to a blank page with a message on it... so maybe display a message on the form saying, "Thank you for submitting"? Can someone assist me with this next part?

So far, thanks for helping me out guys, now lets see if you guys can help me with phase 2!

theres nothing wrong with redirecting the user to a success page. It's probably your best option. Man that code is jacked up though, no cleaning or validating? if($_POST){}, I remember those days. seriously though its a bad idea to present the form after a successful submission. you could have the form body as an include page and the success body as an include page and show the succces page, well, on success. redirecting to a blank page is very bad, on success or fail. direct the users to a page that has full navigation and maybe a link in the message body that will take them to the homepage, you dont want them using the browser back button.

I came up with the thought of not redirecting users to a new page because the contact form is going to be on every page (on the menu) and I don't want them to leave the pages they currently were on... So maybe I should put a message saying "Thank You For Submitting" after they submit the form (so they don't leave the page).

Anyways of doing that, I kind of need help with that because I can't find anything great off of google searches...

well thats a bit tough without seeing all your code but I'd start with getting some type of error handling. And posting the form in a generic way, unless you already have this handled maybe try:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

as far as the error handling again tough but you must first do all your validating. I'm gong to try to make this really simple.

    <?php
    $errors = NULL;
    if($_POST){        
        $name = $_POST['name'];
        $email = $_POST['email'];
        $subject = $_POST['subject'];
        $message = $_POST['message'];
        if($name == "" || $email == "" || $subject == "" || $message == ""){
            $errors = 'Please fill in all fields and submit again!';
        } 
        elseif(!isset($errors)) {
            $headers = "From: $email \n";
            $to = "email@gmail.com";
            if(mail($to,$subject,$message,$headers)) {
                $errors = 'You submitted a form, good for you!';
            }
        }
    }    
    ?>

then above the form print out the results, in this case the $errors variable cantains the success message as well, just for simplicity

<?php print (isset($errors) ? $errors : ''); ?>

clean your post variables or perish, depending on how you have this set up you may need to set you form fields to null on success, if they save the values on a failed post

I should add that the code for this should be included on all pages, like your form. That way when the form submits post to itself there will be no redirecting. Hope that helps.

Well so far, it doesn't redirect you to a new page (which is what I want), but I don't get a message... why is that?

Shall I send you the link to the page so you can observe as well?

not sure that would help but I'll take a look. did the code execute? try setting $errors = NULL; to $errors = 'test message'; and see if that prints to the screen. if the code executes on success and you get an email then this should be an easy fix. you could try die('die'); in key parts of the code like after elseif(!isset($errors)) {die('die')} to break down the code.

I sent you the link to my page, I am not sure if the code executed properly

put the die() code right under the $errors = NULL; the code needs to be included on every page the form is on. reload the page and it should die, if not then the code is not included in the right place. put your code in a seperate file then include at the top of your pages somehwere.
But for this I think you will need ajax. JS to handle the form verification and PHP for the sending of the message and all that. PHP will not handle this in a managable way because every time the form is submitted the page will reload and the form will close. Personally I would say create a seperate contect page although it does look cool, user experience is key. It will work if you want it to, search for jquery form validation or jquery email form validation with ajax. jquery has a lot of info out there and they have a great forum dedicated to using it correctly.

Sorry, I updated the page, i now get the messages but it doesn't display properly, may you look again?

it looks like its printng outside of the body or the form tags? it should be structured like this.

<form>
 <?php print (isset($errors) ? $errors : ''); ?><br />
 <input></input>
</form>

unless you used a table then put in a row above the form. I'm not sure but I don't think you can make re-captca any smaller then that. the message should be shorter as well if you want it to print above the form. I noticed your trying to do the validation in JS. thats a good idea but you should set a div or something, not an alert box so the user doesn't have to nav away from the form body.

OK your echoing this message from the captcha validation I noticed your other posts and then viewed your source. you appear to be validating the captcha seperately, you got a form nested inside a form, narrow this shit down, focus. you got JS val, php val. it also looks like youre missing a closing tag for a form which is probably why your text in form elements is small as shit. put css in a css file move it off you html files, put your js in a seperate file, clean it up so your not bogged down in sloppy html files

<link rel="stylesheet" type="text/css" href="style/style.css" />
<script type="text/javascript" src="js/javascript.js"></script> 

I am sorry, but i think i am just misreading this but where specifically would you put this:

<form>
 <?php print (isset($errors) ? $errors : ''); ?><br />
 <input></input>
</form>

And i will be sure to make some time to organize my files, I've got a lot of things on my plate in the moment but I will make sure that organizing my files is a completed task :).

the form and form elements are irrelevent the errors variable needs to be positioned within the form that is sending the email data that way it will print right above the form elements, make since? you may have already done this. hows about you add the code for the form that processes the email request. echo nothing that has to do with this request. add any errors to the errors variable so it prints correctly to the page. sorry about that it's much easier to deal with pags that are clean.

I will update you on progress ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.