Submit a Form Using PHP

Hi,

I’m needing some guidance here.

I’ve created and styled it a contact form and have added Javascript-Form-Validation to it using -> http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

Now, where I’m not sure is the actual PHP code which will send the email when the form is submitted.

Here’s what I have gathered so far, but I’ve been told it’s not very safe nor effective.

<?php
$to = "EMAIL@DOMAIN.com";
$subject = "Message from: $name";
$body = "From: $name \
\
 Email: $email \
\
 Phone: $phone \
\
 Message: $message";

$sent = mail($to, $subject, $body) ;
if($sent)
	{echo 'MESSAGE SENT SUCCESSFULLY - Thank you for your Email.';}
		else
	{echo 'ERROR! Problem in sending your request.';}
?>

Is this effective? Do you have a more effective and secure script to send mail?

Thanks!!!

It seems to work fine, but I’m not sure with PHP, if it’s effective enough or not, from what I’ve been told.

That code doesn’t look complete to me. For example, the $name variable has no value. You first need to associate it with one of the $_POST values … e.g.

$name = $_POST[“name”]

(sorry, that’s not the full code, but I’m not at my main computer right now).

Also, you really need to have checks in place to make sure people haven’t inserted malicious code (you can’t rely on JS to do that for you). If no one else has responded when I get home, I’ll post some links that might be of use.

Thanks, for the heads up.

I have added.

$name = $_POST['name'] ;
$email = $_POST['email'] ;
$phone = $_POST['phone'] ;
$message = $_POST['message'] ;

I’m guessing, all I need now is the checks ?

Here is an example of how the whole PHP bit could be done, including checking that each field has something in it and that what’s in it is allowed:


<?php
if ($_POST["submit"]) {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

$errors=array(); 

if (empty($name) || !preg_match("~^[a-z\\-'\\s]{1,60}$~i", $name)) { 
$errors[]="The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}

if (empty($email) || !preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $email) && !preg_match("/^N\\/A$/i", $email)) { 
$errors[]="Your email must have a valid format";
}

if (empty($message) || !preg_match("/^[0-9A-Za-z\\/-\\s'\\(\\)!\\?\\.,]+$/", $message)) { 
$errors[]="The Comments field is required, must contain only letters, digits, spaces and basic punctuation";
}

if (empty($phone) || !preg_match("/^[A-z\\/0-9\\s\\(\\)]{1,60}$/", $phone)) { 
$errors[]="The phone field must contain only digits, spaces and parentheses";
}

if ($errors) {
echo '<ul>';
foreach ($errors as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>';
exit();
}

$to = "EMAIL@DOMAIN.com";
$subject = "Message from: $name";
$body = 'From: '.$name.'
Email: '.$email.'
Phone: '.$phone.'
Message: '.$message;
 
$header = "From: \\"$name\\" <$email>" . "\\r\
" . "Reply-To: \\"$name\\" <$email>";
if  (!$errors) {
mail($to, $subject, $body, $header) ;
header ('Location: thankyou.html');

exit();
}  
} 
?>

It also assumes that the submit button on the form looks like this:


<input type="submit" name="[COLOR="#FF0000"]submit[/COLOR]" value="Send">

And it also assumes that you have a page in the same folder called thankyou.html.

There are more sophisticated ways to do all this (the error message display is a bit basic … you could instead echo it on the page with the form and everything else still there) but at least this is a start.

I’d suggest using filter_var($email, FILTER_VALIDATE_EMAIL); rather than those fancy regexs.

Thank you very much, ralph.m, I’ll get that a test out…

Any second opinion on this?

Seems fair enough to use that filter for the email. You still need to check the other fields, and you might also want to make sure the email field has been filled in.

So… Do I take out this…

if (empty($email) || !preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $email) && !preg_match("/^N\\/A$/i", $email)) { 
$errors[]="Your email must have a valid format";
}

And replace it with this…



if(!filter_var($email, FILTER_VALIDATE_EMAIL))
  {
  echo "E-mail is not valid";
  }
else
  {
  echo "E-mail is valid";
  }


Is that correct?

Right, I’m really confused here.

See -> Here

Firstly, I’ve tested out the code you gave me ralph and it’s not working, no errors, no email, nothing.

Secondly, within the Link in the OP that I provided to the JavaScript Form Validation script and code that I’m using, it gives a pop up error within failure to meet the field requirements.

So, what I don’t understand is why have I got arrays of errors in PHP when the JavaScript form validation is working and validating each form field.

I thought, I just needed a PHP script to actually send the mail.

Hm, I fully tested that code before posting here and it worked for me. I changed the email back to the test one you gave, though, so that needs to be changed.

I don’t know how JS plays with all this, but JS isn’t reliable for validation, because if it’s off, you have no validation. Anyhow, even if I turn off JS the form is still not working, so it may be how you’ve set things up. I should have clarified that this form code works nicely if you place it on the same page as the form itself. Below is the full code I used (all on one page)–except with email address changed.


<?php
if ($_POST["submit"]) {
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];

$errors=array(); 

if (empty($name) || !preg_match("~^[a-z\\-'\\s]{1,60}$~i", $name)) { 
$errors[]="The name field must contain only letters, spaces, dashes ( - ) and single quotes ( ' )";
}

if (empty($email) || !preg_match("/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/", $email) && !preg_match("/^N\\/A$/i", $email)) { 
$errors[]="Your email must have a valid format";
}

if ($errors) {
echo '<ul>';
foreach ($errors as $err) {
echo '<li>'.$err.'</li>';
}
echo '</ul>';
exit();
}

$to = "test@test.com";
$subject = "Message from: $name";
$body = 'From: '.$name.'
Email: '.$email.'
Message: '.$message;
$header = "From: \\"$name\\" <$email>" . "\\r\
" . "Reply-To: \\"$name\\" <$email>";
if  (!$errors) {
mail($to, $subject, $body, $header) ;
header ('Location: thankyou.html');
exit();
}  
} 
?>
<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="utf-8">

<title>Experiment</title>
	
<style media="all">

</style>
	
</head>

<body>


<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
	<fieldset> 
		<legend>Contact Us</legend>
			<div>
			<label for="name">Name</label>
			<input name="name" type="text" size="40" maxlength="60" id="name" value="">
			</div>
			<div>
			<label for="email">Email Address</label>
			<input name="email" type="text" size="40" maxlength="60" id="email" value="">
			</div>
			
			<div>
			<label for="comm">Comments</label>
			<textarea name="message" rows="10" cols="50" id="comm"></textarea>
			</div>
			
			<div>
			<input type="submit" name="submit" value="Send">
			</div>
	</fieldset>
</form>


</body>

</html>

So just save this file as contact.php or whatever and it should work (once the email address is changed).

Hi,

Generally for a debatable better user experience one can use both JS and PHP validation. The PHP validation is needed if JS is turned off, but JS validation allows for nice things like to provide ajax realtime instructions, errors and feedback without the page having to be posted first.

Steve

I agree 100%
From the perspective of site maintenance, I’d hate to have problems caused from bogus input.
From the perspective of a user, I’d get annoyed if I made legit mistakes and had to keep reloading the page for every one - especially for a long form.

If I had javascript disabled, I guess I’d expect the behavior, but with it enabled I’d like my good input fields to retain my valid input values and a chance to amend my errors as easily as possible.

Thanks ralph, I will try that.