Cheesetoast » validation http://www.cheesetoast.co.uk Brain Food for Web Developers Mon, 07 Jul 2014 23:18:22 +0000 en-US hourly 1 http://wordpress.org/?v=4.2.10 PHP Contact Page with Validation http://www.cheesetoast.co.uk/php-contact-page/ http://www.cheesetoast.co.uk/php-contact-page/#comments Tue, 20 Jul 2010 11:04:50 +0000 http://www.cheesetoast.co.uk/cheesepress/?p=43 I'm going to demonstrate how to create a PHP contact page that checks that the form fields are valid before e-mailing the contact message. Form validation is something that can be done very well in JQuery (since it does not require the page to be reloaded), however if you want another option then PHP can get the job done too. Continue reading

The post PHP Contact Page with Validation appeared first on Cheesetoast.

]]>

I’m going to demonstrate how to create a PHP contact page that checks that the form fields are valid before e-mailing the contact message. Form validation is something that can be done very well in JQuery (since it does not require the page to be reloaded), however if you want another option then PHP can get the job done too.

Start with a HTML Form

We are going to start by creating the HTML form in a file called ‘contact.php’.

<form method=”post” name=”contact_form” action=”<?php echo $_SERVER[‘SCRIPT_NAME’] ?>”>
<fieldset>
<h1>Contact Form</h1>
<p>  <!– Get users name –>
<label for=”name”>Name:</label>
<input name=”name”  value=”<?php echo $_POST[‘name’]; ?>” />
</p>
<p>
<!– Get users email–>
<label for=”email”>E-mail:</label>
<input name=”email”  value=”<?php echo $_POST[’email’]; ?>” />
</p>
<p>
<!– Get users message –>
Message:<br />
<textarea name=”message” cols=”40″ rows=”4″ > value=”<?php echo $_POST[‘message’]; ?>”</textarea>
</p>
<input type=”submit” value=”Send” />
<input type=”hidden” name=”contact_form” value=”submitted” />
</fieldset>
</form>

This is pretty much a typical HTML form except for some simple PHP code. The code in the first line tells the page to post the field data to itself. We could just use the name of the file ‘contact.php’ in there, however the page would break down if the file name was changed.

Warning: A lot of people believe $_SERVER[‘PHP_SELF’] to be a good alternative to SCRIPT_NAME. While this achieves the same result as far as the form is concerned, it can be dangerous if misused. PHP_SELF contains more info that just the file name and hackers can take advantage of this by performing a XSS attack. For more information on this, see the PHP Manual about PHP_SELF.

There is also some more PHP code in amongst the value attributes. Basically if the user fills out the form incorrectly this will make sure that they don’t have to enter the info all over again.

Notice also the hidden input at the end of the form. I will talk more about this soon.

Gathering User Input

Ok so now that we have the form we need to write the code that handles the data that has been posted. We could just as easily write this code in a separate file and have the html form action attribute point to that instead, but for this example I’ll do it all in one file.This is where the order of things comes into play. Although the form is the first thing we have written, it’s actually going to be at the end of the file. We’re going to start by asking if the contact form has been submitted already. If it has been submitted it will do the validation checks before displaying the form. Here’s how we do this:

First of all we set a variable called ‘submitted’ to FALSE. This is the default (strictly speak we don’t need to do this, since a non-existant boolean is always considered FALSE, but it might help when trying to visualise the flow).

$submitted = FALSE;

Then we’re going to ask if the form has been submitted by checking to see if the form’s hidden value has been posted:

if ($_POST[‘contact_form’]) {

$submitted = TRUE;  // The form has been submitted and everything is ok so far…

$name = htmlspecialchars($_POST[‘name’], ENT_QUOTES);
$email = htmlspecialchars($_POST[’email’], ENT_QUOTES);
$message = htmlspecialchars($_POST[‘message’], ENT_QUOTES);

As you can see I’ve set up some variables that are associated with the posted form data using the php filer ‘htmlspecialchars()’. It is very important to take precautions with any input that comes from the user. Every time you’re dealing with user input you should always assume that it’s hostile. By using the htmlspecialchars filter we can convert special characters to HTML entities (the ENT_QUOTES parameter is used to convert single quotes as well). This will hopefully prevent people from trying to submit some nasty javascript in the message box. For more information on this function and more security tips have a look at what the PHP Manual has to say on the matter.

Error Checking

Next we use a few if statements to check that the contact form was filled out properly.if ($name = “”) {
// if the name is blank… give error notice.
echo “<p>Please enter your name.</p>”;
$submitted = FALSE;  // Set this to FALSE so that it the message is not sent.
}

We repeat this with the ‘e-mail’ and ‘message’ variable, changing the error notice accordingly. When it comes to the e-mail, however, we need to add a little extra to check that the address is valid. This will require us to search through the string and check that there is both a ‘@’ character and a period in there somewhere. Notice that in this case we cannot use the variables that we assigned earlier, since they have already been stripped of these special characters. Instead we will use the data directly from the $_POST. The logic here can be a little confusing so bear with me.

if ($_POST[’email’] != “” && (!strstr($_POST[’email’],”@”) || !strstr($_POST[’email’],”.”))) { …

The first part of this checks that the email is not blank. We already have a separate statement to check for that and we don’t want two error messages coming up. The second part checks if the special characters are present in the email post.

If the user has tripped an error for whatever reason then $submitted will be set back to FALSE. The contact form will display as normal but with the addition of the error message(s). If the user has managed to submit the form successfully, then $submitted will be set as TRUE and the e-mail can be sent. To prepare for sending the e-mail we need to set up some more variables.

$to = “target@email.comThis e-mail address is being protected from spambots. You need JavaScript enabled to view it“;  // Set the target email address.
$header = “From: $email”;
$attention = “Someone has sent you contact e-mail from your webpage!”;
$message = “Attention: $attention \n From: $name \n Message: $message \n”;

if ($submitted)
{
mail($to, $attention, $message, $header);
echo “<p>Thank you $name. Your message has been sent.</p>”;
}

Putting it all together

Finally, we put it all together:
<?php

$submitted = FALSE;

if ($_POST[‘contact_form’]) {

$submitted = TRUE;  // The form has been submitted and everything is ok so far…

$name = htmlspecialchars($_POST[‘name’], ENT_QUOTES);
$email = htmlspecialchars($_POST[’email’], ENT_QUOTES);
$message = htmlspecialchars($_POST[‘message’], ENT_QUOTES);

if ($name == “”) {
// if the name is blank… give error notice.
echo “<p>Please enter your name.</p>”;
$submitted = FALSE;  // Set this to FALSE so that it the message is not sent.
}

if ($email == “”) {
// if the email is blank… give error notice.
echo “<p>Please enter your e-mail address so that we can reply to you.</p>”;
$submitted = FALSE;  // Set this to FALSE so that it the message is not sent.
}

if ($message == “”) {
// if the message is blank… give error notice.
echo “<p>Please enter a message.</p>”;
$submitted = FALSE;  // Set this to FALSE so that it the message is not sent.
}

if ($_POST[’email’] != “” && (!strstr($_POST[’email’],”@”) || !strstr($_POST[’email’],”.”)))
{
// if the string does not contain “@” OR the string does not contain “.” then…
// supply a different error notice.
echo “<p>Please enter a valid e-mail address.</p>”;
$submitted = FALSE;  // Set this to FALSE so that it the message is not sent.
}

$to = “target@email.comThis e-mail address is being protected from spambots. You need JavaScript enabled to view it“;  // Set the target email address.
$header = “From: $email”;
$attention = “Someone has sent you contact e-mail from your webpage!”;
$message = “Attention: $attention \n From: $name \n Message: $message \n”;

if ($submitted == TRUE)
{
mail($to, $attention, $message, $header);
echo “<p>Thank you $name. Your message has been sent.</p>”;
}

}

?>

<form method=”post” action=”<?php echo $_SERVER[‘SCRIPT_NAME’] ?>”>
<fieldset>
<h1>Contact Form</h1>
<p>  <!– Get users name –>
<label for=”name”>Name:</label>
<input name=”name” value=”” />
</p>
<p>  <!– Get users email–>
<label for=”email”>E-mail:</label>
<input name=”email” value=”” />
</p>
<p>  <!– Get users message –>
Message:<br />
<textarea name=”message” cols=”40″ rows=”4″ ></textarea>
</p>
<input type=”submit” value=”Send” />
<input type=”hidden” name=”contact_form” value=”submitted” />
</fieldset>
</form>

And that’s it! If you have any questions or recommendations on how to improve this page then please post a comment.

 

The post PHP Contact Page with Validation appeared first on Cheesetoast.

]]>
http://www.cheesetoast.co.uk/php-contact-page/feed/ 0