How do I redirect contact form after submission?

Hello,
Currently once my contact form is submitted the page goes to the form.submit.php page that is defined in the action of the form (action=“form.submit.php”). What I want it to do is to stay on the contact page and display the page as well as a thank you message. How do I do that if I have my form.submit.php set as the action in my form?

Here is my code for the form:


<form method="post" id="contact_form2" action="_php/form.submit.php">
   <!-- Name -->
   <div class="field">
      <label for="name">*Name:</label>
      <input name="name" type="text">
   </div>

   <div class="clear"></div>

   <!-- Email -->
   <div class="field">
      <label for="email">*Email:</label>
      <input name="email"type="text">
   </div>

   <div class="clear"></div>

   <!-- Phone -->
   <div class="field">
      <label for="phone1">*Phone Number:</label>
      <input name="phone1" type="text">
   </div>

   <div class="clear"></div>

   <!-- Remarks -->
   <div class="remarks">
      <label for="remarks">Please Describe Your Needs:</label>
      <textarea name="remarks" cols="81" rows="7"></textarea>
   </div>

   <!-- Submit Button -->
   <div class="controls2">
      <input type="submit" name="submit_btn" id="submit_btn" value="Submit">			
   </div>
</form>

Here is my code for form.submit.php:


<?php
require 'form.libs.php';

function get_errors($form_data,$rules) {
	// returns an array of errors
	$errors=array();
	
	// validate each existing input
	foreach($form_data as $name=>$value) {
		if(!isset($rules[$name])) continue;
		$hname=htmlspecialchars($name);
		$rule=$rules[$name];
		
		// make sure that 'required' values are set
		if(isset($rule['required']) && $rule['required'] && !$value)
			$errors[]='Field ' .$hname. ' is required.';
		
		// 'minlength' inputs need a minimum length
		if(isset($rule['minlength']) && strlen($value)<$rule['minlength'])
			$errors[] =$hname. ' should be at least ' .$rule['minlength'] . ' characters in length.';
		
		// verify that 'email' inputs are valid email addresses
		if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL))
			$errors[]=$hname. ' must be an email address.';
		$rules[$name] ['found']=true;
	}
	
	// check for missing inputs
	foreach($rules as $name=>$values) {
		if(!isset($values['found']) && isset($values['required']) && $values['required'])
			$errors[]='Field ' . htmlspecialchars($name) . ' is required.';
	}
	
	// return array of errors (or empty array if all is OK)
	return $errors;
}

$errors=get_errors($_POST,$form_rules);
if(!count($errors)) {
	// save the data, or post it, or whatever
	
	// send the email
	if (isset($_POST['submit_btn'])){
		$to = "melinda@melindamccawmedia.com";
		$subject = "Email from JDR Website";
		$message = "Name: {$_POST['name']}
Phone: {$_POST['phone1']}
Email: {$_POST['email']}
	
	";
	if ($_POST['remarks'] != ""){
		$message .= "{$_POST['name']} had the following remarks: {$_POST['remarks']}
	
	";
		}
		$headers = "From: " . $_POST['name'] . " <" . $_POST['email'] . ">\
";
		$headers .= "Reply-To: " . $_POST['name'] . " <" . $_POST['email'] . ">\
";
		$headers .= "X-Mailer: PHP4\
" ; // mailer
		$headers .= "X-Priority: 3\
" ;  // priority
		$headers .= "Return-Path:  $to\
";
		$headers .= "Origin: ".$_SERVER['REMOTE_ADDR']."\
";
		$headers .= "Content-Type: text/plain; charset=us-ascii\
";
		
		$autoTo = $_POST['email'];
		$autoreply = "Thank you for your inquiry, we will be in contact with you shortly!"; //change this to your message
	
		//if (
			(mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You from JDR Excavating", $autoreply, 'From: doug@jdr-excavating.com'));// {
//			echo "&reply=success";
//		} else {
//			echo "&reply=error";
//		}
//	echo 'success';
}
else{
	// errors found
	echo '<strong>Errors found in form:</strong><ul><li>';
	echo join('</li><li>',$errors);
	echo '</li></ul><p>Please go back and correct your errors.</p>';
}
}

Thanks for any help!

PHP comes with a function
Header(“Location: url”);

I have tried using that, but was getting an error. I tried putting it in the php code where the “echo “&reply=success”;” is commented out. So what I had looked like this:


if ((mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You from JDR Excavating", $autoreply, 'From: doug@jdr-excavating.com')) {
	Header("Location: contact4.php");
}

The error I am getting is:
Parse error: syntax error, unexpected ‘{’ in /home/user/public_html/folder/_php/form.submit.php on line 67

Line 67 is:


if ((mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You from JDR Excavating", $autoreply, 'From: doug@jdr-excavating.com')) {

What am I doing wrong? Am I putting the Header(“Location: contact4.php”);
in the correct location?

Below is a functional (very basic) mail processor with redirect, the code is commented for you to see what is taking place.


<?php



$goto_after_mail = "http://www.domain.com"; // This is the URL that is shown after the mail is submitted.
$from_mail = $_REQUEST['email']; // Be sure your EMAIL form field is identified as "email".
$from_name = $_REQUEST['name']; // Be sure your NAME form field is identified as "name".
$header = "From: \\"$from_name\\" <$from_mail>\\r\
";
$header .= "MIME-Version: 1.0\\r\
";
$header .= "Content-Type: text/plain; charset=\\"utf-8\\"\\r\
";
$header .= "Content-Transfer-Encoding: 7bit\\r\
";
$subject = "Your Message Subject"; // Insert your message subject.
foreach ($_REQUEST as $key => $val) {
    if ($key != "" && $key != "") {
        $body .= $key . " : " . $val . "\\r\
";
    }
}
if (mail("mail@domain.com", $subject, $body, $header)) { // Insert your e-mail address to be used to view your submissions.
    header("Location: ".$goto_after_mail);
}
?>

Thanks! That works great! I was actually doing it right before, I just had a missing ‘)’ at the end of my if (mail(… statement. Those little things get me every time. But I am slowly getting better at trouble shooting. Thanks again for the help!

I am also trying to print out a success message if the mail is sent. I thought that in the same if statement I could define a variable called $success and make it equal to the string I want to print. Then I thought that I could echo that variable on the contact page.

This is how I tried to make it work:


if ((mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You from JDR Excavating", $autoreply, 'From: name@domain.com'))) {
   header("Location: ".$goto_after_mail);
   $success = "Your message has been sent. A JDR Excavating representative will be in contact with you shortly!";
}

And on the contact page I have this:


<div id="message">
   <?php echo $success; ?>
   <?php echo $invalid; ?>
</div>

Unfortunately this is not working. How do I get this to work?

Thanks!

Why it doesn’t work is you are sending the browser to a new page that has no idea the old page even existed. Instead, pass a flag in the url
header(‘Location: page.php?success=1’);

Then check it and act appropriately
if($_GET[‘success’]) { $message = ‘congratz!’; }

That worked great! Thank you for the help!

One other question. I have a success message showing up when the email is sent. I want to have an error message that prints the actual errors if a field is empty or incorrect. I have tried making $message = $errors and echoing $message. I have also tried this:


if($_GET['errors']) {
   $message = '<strong>Errors found in form:</strong><ul><li>' . join('</li><li>',$errors) . '</li></ul><p>Please go back and correct your errors.</p>';
}

But that gives me a warning:

Warning: join() [function.join]: Invalid arguments passed in /home/user/public_html/folder/contact4.php on line 145

How do I get it to print out a list of the errors?

Currently this is what I have:


<div id="message">
   <?php
      if($_GET['success']) {
         $message = 'Your message has been sent. A JDR Excavating representative will be in contact with you shortly!';
      }
      if($_GET['errors']) {
         $message = 'There are errors in your form. Please correct them to continue';
      }
      echo $message;
   ?>
</div>


if ((mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You", $autoreply, 'From: name@domain.com'))) {
   header('Location: http://www.mccawphotographics.com/jdr/contact4.php?success=1');
}
//errors found
   header('Location: http://www.mccawphotographics.com/jdr/contact4.php?errors=1');

I would like it to print out something like this:

Errors found in form:
• error 1
• error 2
• error 3
Please go back and correct your errors.

Thanks!

The second argument to join must be an array, have a look at $errors, what is in it?

In looking at the code it looks like $errors is an array. But I am still working on learning php so I could be wrong. This is the code to check for errors:


require 'form.libs.php';

function get_errors($form_data,$rules) {
   // returns an array of errors
   $errors=array();
	
   // validate each existing input
   foreach($form_data as $name=>$value) {
      if(!isset($rules[$name])) continue;
      $hname=htmlspecialchars($name);
      $rule=$rules[$name];
		
   // make sure that 'required' values are set
   if(isset($rule['required']) && $rule['required'] && !$value)
      $errors[]='Field ' .$hname. ' is required.';
		
   // 'minlength' inputs need a minimum length
   if(isset($rule['minlength']) && strlen($value)<$rule['minlength'])
      $errors[] =$hname. ' should be at least ' .$rule['minlength'] . ' characters in length.';
		
   // verify that 'email' inputs are valid email addresses
   if(isset($rule['email']) && $rule['email'] && !filter_var($value,FILTER_VALIDATE_EMAIL))
      $errors[]=$hname. ' must be an email address.';
      $rules[$name] ['found']=true;
   }
	
   // check for missing inputs
   foreach($rules as $name=>$values) {
      if(!isset($values['found']) && isset($values['required']) && $values['required'])
         $errors[]='Field ' . htmlspecialchars($name) . ' is required.';
   }
	
   // return array of errors (or empty array if all is OK)
   return $errors;
}

$errors=get_errors($_POST,$form_rules);
if(!count($errors)) {
   // save the data, or post it, or whatever
   // send the email
   if (isset($_POST['submit_btn'])){
      $to = "name@domain.com";
      $subject = "Email from Website";
      $message = "Name: {$_POST['name']}
      Phone: {$_POST['phone1']}
      Email: {$_POST['email']}
	
	";
   if ($_POST['remarks'] != ""){
      $message .= "{$_POST['name']} had the following remarks: {$_POST['remarks']}
	
	";
   }

      $headers = "From: " . $_POST['name'] . " <" . $_POST['email'] . ">\
";
      $headers .= "Reply-To: " . $_POST['name'] . " <" . $_POST['email'] . ">\
";
      $headers .= "X-Mailer: PHP4\
" ; // mailer
      $headers .= "X-Priority: 3\
" ;  // priority
      $headers .= "Return-Path:  $to\
";
      $headers .= "Origin: ".$_SERVER['REMOTE_ADDR']."\
";
      $headers .= "Content-Type: text/plain; charset=us-ascii\
";
		
      $autoTo = $_POST['email'];
      $autoreply = "Thank you for your inquiry, we will be in contact with you shortly!";
	
      if ((mail($to,$subject,$message,$headers))&&(mail($autoTo, "Thank You", $autoreply, 'From: name@domain.com'))) {
         header('Location: http://www.domain.com/folder/contact4.php?success=1');
	}
      }

}
      header('Location: http://www.domain.com/folder/contact4.php?errors=1');

Here is the required form.libs.php code:


$form_rules=array(
	'name'=>array(
		'required'=>true
	),
	'email'=>array(
		'required'=>true,
		'email'=>true
	),
	'phone1'=>array(
		'required'=>true
	),
	'remarks'=>array(
		'required'=>true,
		'minlength'=>10
	)
);

Any help understanding this would be appreciated. Thanks!

By have a look at it I meant this:


// what is in errors immediately before it is used
var_dump($_GET['errors']);
if($_GET['errors']) {

   $message = '<strong>Errors found in form:</strong><ul><li>' . join('</li><li>',$errors) . '</li></ul><p>Please go back and correct your errors.</p>';

} 

When you know what it is set too you can set about finding why it is not set to what you want.
It comes from the last line of that first block of code. You can’t set a variable in one script and have it show up on another page. For that you have to use sessions or cookies, e.g.


//processing script
session_start();
$errors = 'bunch of errors messages';
$_SESSION['errors'] = $errors;

// form script
session_start();
echo $errors; // warning: var does not exist
echo $_SESSION['errors']; // bunch of error messages

Thanks again for your help! I was able to get it working with your help with SESSIONS.

I decided I wanted to make my form fields sticky so if there is an error they only have to fill in the field they missed or messed up on. So I added this code to my fields to make them sticky.


<input name="name" type="text" value="<?php if (isset($_POST['name'])) { print htmlspecialchars($_POST['name']); } ?>">

I have used this before and it works great. But now it suddenly isn’t working.
Here is my form code:


<form method="post" id="contact_form2" action="_php/form.submit.php">
   <!-- Name -->
   <div class="field">
      <label for="name">*Name:</label>
      <input name="name" type="text" value="<?php if (isset($_POST['name'])) { print htmlspecialchars($_POST['name']); } ?>">
   </div>

   <div class="clear"></div>

   <!-- Email -->
   <div class="field">
      <label for="email">*Email:</label>
      <input name="email" type="text" value="<?php if (isset($_POST['email'])) { print htmlspecialchars($_POST['email']); } ?>">
   </div>

   <div class="clear"></div>

   <!-- Phone -->
   <div class="field">
      <label for="phone1">*Phone Number:</label>
      <input name="phone1" type="text" value="<?php if (isset($_POST['phone1'])) { print htmlspecialchars($_POST['phone1']); } ?>">
   </div>

   <div class="clear"></div>

   <!-- Remarks -->
   <div class="remarks">
      <label for="remarks">Please Describe Your Needs:</label>
      <textarea name="remarks" cols="81" rows="7"></textarea>
   </div>

   <!-- Submit Button -->
   <div class="controls2">
      <input type="submit" name="submit_btn" id="submit_btn" value="Submit">			
   </div>
</form>

Any ideas why this won’t work for this form?

Thanks for any help!

There appears to be no issue with that code.

I was able to get it to work using SESSIONS. I ended up using this:

<input name="name" type="text" value="<?php if (isset($_SESSION['name'])) { print htmlspecialchars($_SESSION['name']); } ?>">

and defining the variables in my processing script like this:

session_start();
//$errors = 'bunch of errors messages';
$_SESSION['errors'] = $errors;
$_SESSION['name'] = $_POST['name'];
$_SESSION['email'] = $_POST['email'];
$_SESSION['phone1'] = $_POST['phone1'];
$_SESSION['remarks'] = $_POST['remarks'];

So the problem was that after going around a circuit of a couple of different pages, the form data was being lost.

Apart from using sessions, there are other appropriate ways to deal with that.

One way is to transmute the POST data to GET data for the error part of the process.

Another way is to use a 302 redirect from the error page back to the referring page.

Thanks! That is good to know. I appreciate everyone helping me as I continue to work on learning php. I think I will play with that option as well to see the differences.

Thanks again!