Jump to content

PHP Contact Form Validation


cdcn

Recommended Posts

Hello everybody. I'm new here and also new to PHP but I'm creating a contact form for my website and I was wondering how to make it so people couldn't put stuff in it that isn't necessary. I was wondering if I made a function to check the form and used if statements and else if statements to make sure it was correct would it work? Something like:

 

// Checking if the form entry is correct and valid.
function checkForm()
{
if ($name == '') 
{
	echo "Please enter your first name";
	return false;
}

else if ($lname == '')
{
	echo "Please enter your last name";
	return false;
}

else if ($email == '')
{
	echo "Please enter your e-mail address";
	return false;
}

else if ($subject == '')
{
	echo "Please enter the subject of your message"
	return false;
}

else if ($message == '')
        {
                echo "Please enter your message";
                return false;
        }
}
?>

 

I know this wouldn't make sure that people couldn't enter things that they shouldn't of course, but so far would this work to make sure that someone cannot leave any empty spaces? Or would this whole idea be a bad way to validate it? Should I use something different? If so what?

Link to comment
https://forums.phpfreaks.com/topic/113365-php-contact-form-validation/
Share on other sites

I actually decided to do something else. I would appreciate it if somebody would help me out. The contact form works so far, it always sends the e-mail, whether the input is valid or not because I have the mail() function in validation.php. So how would I make it so it only sends the mail ( mail() ) when it's a valid message, and not invalid, could I use an if statement to fix this? And also, I've tried it out and put an invalid e-mail in but it still sends the message, and then on validation.php it doesn't display anything.. so I'm guessing that means my else ($email != $valid) { echo "Please goback and enter your e-mail address."; } is not the correct code? Anyway here are my files:

 

contact.php

<form action="validation.php" method="post">
<style type="text/css">
td.error {color:C03; font-weight:bold; }
</style>
<table class="contacttext" width="500">
<tr>
	<td colspan="2">

	<div class="heading">Contact Us!</div>
<div class="subtext">All fields are required. Do not leave any spaces empty.</div><br />
	</td>
</tr>
<tr>
	<td width="30%">First Name: </td>
	<td> <input type="text" id="lname" name="name" /> </td>
</tr>
<tr>
	<td width="30%">Last Name: </td>
	<td> <input type="text" id="name" name="lname" /> </td>
</tr>
<tr>
	<td width="30%" <?php if(!$em) echo 'class="error"'; ?>>E-mail Address: </td>
	<td> <input type="text" id="email" name="email" value="<?= $email ?>"> </td>
</tr>
<tr>
	<td width="30%">Subject:</td>
	<td> <input type="text" id="subject" name="subject" /> </td>
</tr>
<tr>
	<td width="30%" valign="top">Message: </td>
	<td> <textarea id="message" name="message" rows="5" cols="30"></textarea> </td>
</tr>
<tr>
	<td>
		<button type="submit">Submit</button>
	</td>
</tr>
</table>




</form>

 

functions.php

<?php
function checkEmail($email) {
  $pattern = "/^[A-z0-9\._-]+"
         . "@"
         . "[A-z0-9][A-z0-9-]*"
         . "(\.[A-z0-9_-]+)*"
         . "\.([A-z]{2,6})$/";
  return preg_match ($pattern, $email);
}
?>

 

validation.php

<?php
/* The validation.php page to 
make sure the contact form 
doesn't have any invalid 
information */

require_once('functions.php');

// Get form data and assign it to variables
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// Create the email to be sent
$to = '[email protected]';
$email = "From: $email";
$subject = "Subject: $subject";;
$message = " Message: $message";

// Make sure information is valid
if(isset($_POST['submit'])) 
{
foreach($_POST as $key=>$value) {
$$key = $value;
}
$em = checkEmail($email);
$valid = $valid && $em;
if($valid)
echo "Form filled successfully!";
exit;
}
else ($email != $valid)
{
echo "Please go back and enter your e-mail address.";
}

// Send the mail to the to address using the mail() function
mail($to, $subject, $message, $email);


?>

 

 

yes you made the function but you didn't call it and yes use if statement

and btw you got syntax errors better use a debugger like Zend Studio or PHP Designer

 

for example you should write something like this

if(checkmail($_POST['email']) !== FALSE && checkForm($name,$lname,$subject,$email,message) !== FALSE)){
      mail($to, $subject, $message, $email);
}else{
      echo "Please fill in all fields correctly";
}

 

 

So this is what I'm using, but for some reason I'm entering emails like abc123.:^% and it's still allowing it? So I don't know whats wrong, but here are the changes i made to validation.php. Anything needs fixing, is it maybe allowing those emails because the function isnt being called right, or the function is coded wrong?

 

<?php
/* The validation.php page to 
make sure the contact form 
doesn't have any invalid 
information */

require_once('functions.php');



// Get form data and assign it to variables
$name = $_POST['name'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// Create the email to be sent
$to = '[email protected]';
$email = "From: $email";
$subject = "Subject: $subject";;
$message = " Message: $message";

// Make sure information is valid

if(isset($_POST['submit'])) 
{
foreach($_POST as $key=>$value) 
{
	$$key = $value;
}
$em = checkEmail($email);
$valid = $valid && $em;
if($valid)
echo "Form filled successfully!";
exit;
}


if(checkEmail($_POST['email']) !== FALSE){
      mail($to, $subject, $message, $email);
}else{
      echo "Please fill in all fields correctly<br />";
}

?>

OK I redid a lot. I got confused and lost and didn't know what I was doing, just tried different codes, then I got this:

	if ($name == '') 
{
	echo "Please go back and fill in every field.";
	return false;
}

else if ($lname == '')
{
	echo "Please go back and fill in every field.";
	return false;
}

else if ($email == '')
{
	echo "Please go back and fill in every field.";
	return false;
}

else if ($subject == '')
{
	echo "Please go back and fill in every field.";
	return false;
}

else if ($message == '')
        {
                echo "Please go back and fill in every field.";
                return false;
} else {
mail($to, $subject, $message, $email);
echo "Your message has been sent!";	
}

 

Now, this works, if they don't fill in something it makes them go back and redo it. I had it so every variable had it's own message but when I tried it, I didn't fill in the name or last name, but it would only say to go back and enter your first name, it didn't say go back and enter your last name also though, how would I do that? And can I still make it so they can only enter certain characters for e-mail addresses and names and stuff with these if statements, or is it more complex than that?

1) To make each field a separate error, do it like this:

 

if ($name = '') {

    $errors[] = "Please fill in your first name.";

}

if ($message = '') {

    $errors[] = "Please fill in your message.";

}

etc...Also, don't return false the second you find something wrong otherwise you can't check the others.

 

Then you'd loop through the errors array with a foreach.

 

For the email:

 

if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', $email)) {

  ......

}

 

=P

Don't forget, there are many other characters that are allowed before the @. ' is a common source of error, and surely frustrates all of the Irish folk out there. Likewise, there are top level domain names that contain more than 4 characters, e.g. .museum -- http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.