0

I'm trying to make a form for a website I'm building. I'm very new to coding but I have done some simple websites before and have a very basic knowledge of web coding. I have two issues. 1) I'm trying to code this form so that if the two email fields do not match, a message will show up in some way notifying the viewer. 2) The send button will send the info in an email but two parts aren't working: the check box array isn't working (it only says "array" and I want it to say the values separated by commas), and I don't know how to have it redirect to a separate success page (i.e. contact_success.html). Giving me the answer alone is fine, but it would be really great if you can tell me why you use the specific codes.

Here is the HTML code for the entire form:

<form name="contact" action="contactProcess.php" method="post" onSubmit="return validateForm()">
<table  width="100%" cellspacing="6">
    <tr>
        <th width="30%" class="th_contact">*Name:</th>
        <td width="70%"><input type="text" size="50" name="name"></td>
    </tr>
    <tr>
       <th class="th_contact">*Your email  address:</th>
       <td><input type="text" size="50" name="email"></td>
   </tr>
   <tr>
       <th class="th_contact">*Confirm email  address:</th>
       <td><input type="text" size="50" name="email2"></td>
   </tr>
   <tr>
       <th class="th_contact">How did you hear about us?</th>
       <td><input type="radio" name="referral" value="friend or family">Friend or Family<br />
       <input type="radio" name="referral" value="veterinarian">Veterinarian<br />
       <input type="radio" name="referral" value="flyer or mailer">Flyer or Mailer<br />
       <input type="radio" name="referral" value="humane society or similar facility">Humane     Society or Similar Facility<br />
       <input type="radio" name="referral" value="walked or drove by">Walked or Drove By<br />
       <input type="radio" name="referral" value="other">Other<br />
       </td>
   </tr>
   <tr>
       <th valign="top"><h5>What type of pet do you have?</h5></th>
       <td><input type="checkbox" name="pet[]" value="dog">Dog<br />
       <input type="checkbox" name="pet[]" value="cat">Cat<br />
       <input type="checkbox" name="pet[]" value="bird">Bird<br />
       <input type="checkbox" name="pet[]" value="fish">Fish<br />
       <input type="checkbox" name="pet[]" value="reptile">Reptile<br />
       <input type="checkbox" name="pet[]" value="small animal">Small Animal<br />
       </td>
   </tr>
       <td  align="left"><input type="submit"  class="button" value="submit">
       *Required  Fields</td>
   </tr>
</table>
</form>

Here's the PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title>Contact PHP</title>
     <link href="A4P.css" rel="stylesheet" type="text/css" />
</head>

<body>
<?php {
//Set up message body
$message = "Form Submitted on: " . date("m/d/y") . "\n";
$message .= "\n";
$message .= "Name: " . $_POST['name'] . "\n";
$message .= "Email Address: " . $_POST['email'] . "\n\n";
$message .= "Referred by: " . stripslashes($_POST['referral']) . "\n";
$message .= "Pets: " . $_POST['pet'];


//Set up email
$to = "example@example.com, <" . $_POST['email'] . ">";
$subject = "New Email Club Entry";
$headers = "From: " . "All 4 Pets Website";

//Send email
mail($to,$subject,$message,$headers);

}
?>

</body>
</html>

Here's how the email looks in case it matters:

Form Submitted on: 11/18/13

Name: Brad Moore
Email Address: 123@yahoo.com

Referred by: walked or drove by
Pets: Array

Sebastian Höffner
  • 1,864
  • 2
  • 26
  • 37
Dark Wolf
  • 1
  • 1

4 Answers4

1
  1. if ($_POST['email'] != $_POST['email2'])
    {
        //alert user
    }
    
  2. Can't just dump an array out like a string. And the HTML for checkboxes should be name="pets" not "pets[]" I believe.

    $str = implode(" , " , $_POST['pets']);
    
        //now it's a string
    
xd6_
  • 483
  • 4
  • 9
0

What you are looking for is to validate your code. This link will provide the details needed for validating your code, whether you choose to validate on the same page or validate on a different page is up to you. Comment on this answer if you have more questions about it.

http://www.w3schools.com/php/php_form_validation.asp

Validating on the same page would mean that you need to check if the submit button is first pressed, i.e.

if(isset($_POST['button'])) {
    //your code here
}

Then you want to check if the emails in the post are the same:

if(isset($_POST['button'])) {
    if($_POST['email1'] != $_POST['email2']{
        //do yourself a favor and use an array to store the errors in
    }
    else{
        //you can choose to let the user know that it was a success or nothing at all.
    }
}

Validating your PHP code allows you to check to make sure that the user is doing what you ultimately want them to do. If you do not validate, technically that submit button is 'posting' but not really doing anything more than the function it is asked to afterwards. Put the validation code either above the tag in a new set of tags or simply below all of the code you have already written. Along with this, if you are doing validation on the same page, you want to change your tag to look like this:

<form action="" method="post">

This way it knows to validate on the same page and you aren't choosing to do so on a different one.

BuddhistBeast
  • 2,652
  • 2
  • 21
  • 29
0

For checking if two variables match, just simply use the if statement:

if($_POST['email1']==$_POST['email2']) {
    //emails match, continue with form submission
} else {
    //emails do not match, show error
}

For showing which checkboxes were selected, use this code to put the values into a single string.

$checked = implode(" , ", $_POST['pets']);
//$checked would be values of selected checkboxes, each separated by a comma

To redirect to a page upon successful submission, use this code:

header("Location: success.html");

You should do validation and sanitize your input, but here's what you asked for. :)

Caleb
  • 827
  • 2
  • 13
  • 30
  • Where would I add the if statement exactly? Remeber I only have a _basic_ knowledge of web coding. I know CSS and HTML thoroughly. JS, PHP, etc are very new to me so I really am clueless here. – Dark Wolf Nov 19 '13 at 06:31
  • The if statement would go anywhere before you send the email through PHP. If the emails match, send the email. If not, show an error – Caleb Nov 19 '13 at 06:41
0

1) Since you already have a validateForm() call in your form I assume you want to check the mail addresses with JavaScript.

First you should alter your form for this:

onsubmit="return validateForm(email.value, email2.value);"

In the JavaScript code you can then simply create a function like this:

function validateForm(email1, email2) {
    return 0 == email1.localeCompare(email2);
}

Maybe you also want to check if the the e-mail fields are empty or if your pets are chosen correctly - all those checks can be implemented in that function as well.

(See also Optimum way to compare strings in Javascript? )

2)

a)

To have a comma-seperated list of the pets try PHPs implode method:

$message .= "Pets: " . implode(", ", $_POST['pet']);

Your problem here is that you print the array directly, not its values. With implode you take all values, add the , between them and form a string out of it.

How you print all values is not so important, but the concept between what the array is and what its values are is important. Maybe you should try print($_POST['pet']); and print_r($_POST['pet']) to see the difference. And read the PHP documentation about those functions.

b)

The redirect is a little bit more tricky. You can use a html-redirect like this:

<meta http-equiv="refresh" content="0; url=http://example.com/" />

Where the 0 is the time in seconds before the reconnect to http://example.com/ happens.

(See also Redirect from an HTML page )

But probably you want to check the form first and assure that the E-Mail is sent before you redirect. This should be done by sending a new header.

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

The problem here is that header information has to be sent before any output occurs.

(See also How to fix "Headers already sent" error in PHP )

To achieve this in your example you could simply remove the HTML part around the mail creation. You would then just submit your form to the contactProcess.php and from that page to the contact_success.html .

<?php
    //Set up message body
    $message = "Form Submitted on: " . date("m/d/y") . "\n";
    $message .= "\n";
    $message .= "Name: " . $_POST['name'] . "\n";
    $message .= "Email Address: " . $_POST['email'] . "\n\n";
    $message .= "Referred by: " . stripslashes($_POST['referral']) . "\n";
    $message .= "Pets: " . implode(", ", $_POST['pet']);


    //Set up email
    $to = "\"Some person\" <example@example.com>, \"" . $_POST['name'] . "\" <" . $_POST['email'] . ">";
    $subject = "New Email Club Entry";
    $headers = "From: " . "\"All 4 Pets Website\" <all4pets@example.com>";

    //Send email
    mail($to, $subject, $message, $headers);

    // Redirect to contact_success.html
    header("Location: contact_success.html"); 
        // maybe you have to adjust the path
?>

Two additional hints at this point:

1.: You should decide on a design pattern for your file names and either use the underscore between words or distinguish them with camel case (in your case you use contact_success.html with an underscore and contactProcess.php in camel case). It doesn't matter for which you decide, but you should try to be consistent. This makes it easier for you and others to read code, organize files, etc.

2.: The "From: "-information in the E-Mail should be formatted like "All 4 Pets Website" <noreply@example.com> or something similar. If you leave it like All 4 Pets Website you (and your customers) might receive an e-mail "from" All@host.com, 4@host.com, Pets@host.com, Website@host.com. So try to use the format "Name" <mail@example.com>. I included that in the code above, you also can see how to escape the quotation marks there. Just update the addresses and names according to what you need.

3) Why these codes?

The JavaScript because you already provided the template for it. I would of course add more checks, but I prefer evaluating in the PHP script - because there exist users without JavaScript on the internet.

The implode? Because while I was writing this xd6_ already provided that answer, so I just sticked to that. I would have probably come up with something more complicated like a for-loop.

The header("Location: http://example.com/"); simply because I always use that for redirects.

4)

<?php
if(isset($_POST['submit'])) echo "<p>Form submitted!</p>";
if(isset($_POST['arr'])) {
   echo "<p>Received an array: <br /><br />";
   echo implode(", ", $_POST['arr']);
   echo "<br /><br />";
   print_r($_POST['arr']);
   echo "</p>";
}
?>
<form method="post" action="">
  <input type="checkbox" value="checkbox1" name="arr[]" />
  <input type="checkbox" value="checkbox2" name="arr[]" />
  <input type="checkbox" value="checkbox3" name="arr[]" />
  <input type="checkbox" value="checkbox4" name="arr[]" />
  <input type="submit" value="submit" name="submit" />
</form>

This simple example shows a form with a few checkboxes. Just copy the code to a PHP file and try it out.

5)

As noted in the comments I had a mistake in the JS: of course you have to use email.value, not the field itself for the simple comparison. I changed the above code. Below I extended the example from 4) to also provide some form checking. Again it should be working by just copying it into a PHP file.

<script type="text/javascript">
function validateForm(str1, str2) {
   /* this if statement is just for demonstration purposes */
   if(0 != str1.localeCompare(str2))
       document.getElementById('error').innerHTML = "Text fields are not the same!";
   return 0 == str1.localeCompare(str2);
}
</script>
<?php
if(isset($_POST['submit'])) echo "<p>Form submitted!</p>";
if(isset($_POST['arr'])) {
   echo "<p>Received an array: <br /><br />";
   echo implode(", ", $_POST['arr']);
   echo "<br /><br />";
   print_r($_POST['arr']);
   echo "</p>";
}
?>
<div id="error"></div>
<form method="post" action="" onsubmit="return validateForm(str1.value, str2.value);">
  <input type="checkbox" value="checkbox1" name="arr[]" />
  <input type="checkbox" value="checkbox2" name="arr[]" />
  <input type="checkbox" value="checkbox3" name="arr[]" />
  <input type="checkbox" value="checkbox4" name="arr[]" />
  <input type="text" name="str1" />
  <input type="text" name="str2" />
  <input type="submit" value="submit" name="submit" />
</form>

6)

Updated my 2)b)2. statement. "Name" <mail@example.com> is the way to go.

Community
  • 1
  • 1
Sebastian Höffner
  • 1,864
  • 2
  • 26
  • 37
  • Thank you! So the redirect worked. Your explanation coupled with the article you cited about "headers already sent by php" really helped explain that part to me. However not only do I not quite understand the parts about the pets array or email match, when I tried to add the code anyway (learning by trial and error), nothing worked. I tried `$message .= "Pets: " . implode(", ", $_POST['pet[]']);` and `$message .= "Pets: " . explode(", ", $_POST['pet[]']);` and `$message .= "Pets: " . implode(", ", $_POST['pet']);` and `$message .= "Pets: " . explode(", ", $_POST['pet']);`. What else to try? – Dark Wolf Nov 19 '13 at 06:19
  • The pet array thing worked fine for me. Try to leave out the `[]` squared brackets. I add an example at the end of my post. – Sebastian Höffner Nov 19 '13 at 11:48
  • I also had an error in the JS, in fact you have to somehow acces the `.value` of the form fields, I just let you pass the formfields themselves. – Sebastian Höffner Nov 19 '13 at 12:27
  • Nope. Nothing. Here is the code again. where it works, sends me the word "array" instead of the values, and does not check email match. – Dark Wolf Nov 21 '13 at 03:44
  • ` $message = "Form Submitted on: " . date("m/d/y") . "\n"; $message .= "\n"; $message .= "Name: " . $_POST['name'] . "\n"; $message .= "Email Address: " . $_POST['email'] . "\n\n"; $message .= "Referred by: " . stripslashes($_POST['referral']) . "\n"; $message .= "Pets: "; $message .= explode(", ", $_POST['pet']); $to = "s.salinas1992@yahoo.com, <" . $_POST['email'] . ">"; $subject = "New Email Club Entry"; $headers = "From: " . "All 4 Pets Website"; mail($to,$subject,$message,$headers); header("Location: contact_success.html"); } ` – Dark Wolf Nov 21 '13 at 03:45
  • and the HTML form where the array is: `
    What type of pet do you have?
    Dog
    Cat
    Bird
    Fish
    Reptile
    Small Animal
    `
    – Dark Wolf Nov 21 '13 at 03:48
  • Pet array: `$message .= explode(", ", $_POST['pet']);` As mentioned in my post and in other answers this should be `$message .= implode(", ", $_POST['pet']);`. E-Mail Check: Did you apply the fix I applied to the `onsubmit=""`? You have to add `.value` there or in the script where you check the values. (Do you have JavaScript activated?) And I see you already use `
    ` which you should adapt for your `` as well (but this has nothing to do with your problems).
    – Sebastian Höffner Nov 21 '13 at 09:19
  • After playing around again with your code I found out that what I mentioned above is true: Format your "From"-address correctly. I came up with `$to = "\"Someone\" , \"" . $_POST['name'] . "\" <" . $_POST['email'] . ">";` and `$headers = "From: " . "\"All 4 Pets Website\" ";` I will update my answer above to reflect this. Everything else works fine. – Sebastian Höffner Nov 21 '13 at 09:42