Need help with a contact form

Hello,

I know there are hundreds upon hundreds of examples for contact forms. I guess I’m a little overwhelmed as I am new to PHP. Any help will be greatly appreciated.

First let me explain what I need then I’ll place my code. I need a simple contact form that uses PHP. Can’t use JS, will be used in an environment that completely disables JS. Since I’m new to PHP, I’ve been having some problems with validation and security. The code below works for sending the email and I really like the formatting of the email sent, although I’m having problems with validation and clearing the form after the user click submits. Is there a better solution out there or am I heading in the right direction with this script? Again your help will be greatly appreciated.

PHP


<?php

//Strip Tags and white Space from all input with this function
function white_tags_strip($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);

return $value;
}

$send = $_POST[send];

if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}
	
if($email_sent === true) {

$from = white_tags_strip($_POST['from']);
$to = white_tags_strip($_POST['to']);
$name = white_tags_strip($_POST['name']);
$title = white_tags_strip($_POST['title']);
$company = white_tags_strip($_POST['company']);
$phone = white_tags_strip($_POST['phone']);
$subject = white_tags_strip($_POST['subject']);
$message = white_tags_strip($_POST['message']);

// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {

        $nameErr = "Please enter your name.";
    }
    else {
        $name = $_POST["name"];
    }

    if (empty($_POST["email"])) {
        $emailErr = "Please enter your email.";
    }
    else {
        $email = $_POST["email"];
    }
	if (empty($_POST["phone"])) {
		$phoneErr = "Please enter a phone number.";
	}
	else {
		$phone = $_POST["phone"];
	}
    if (empty($_POST["message"]))  {
        $messageErr = "Cannot leave message box blank.";
    }
    else {
        $message = $_POST["message"];
    }

}
					
if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\
MIME-Version: 1.0 \
Content-type: text/html; charset=iso-8859-1";

$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;

if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "It went through!";}
else {$error_message = "There seems to be a problem...";}}

}
	
?>

HTML


<table style="border-collapse:collapse; border-spacing:0" >
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
  <tr>
    <td>Name:</td>
	<td><input name="name" placeholder="Name*" type="text" class="text" value="<?php echo htmlspecialchars($name);?>"/>
            <span class="error"><?php echo $nameErr;?></span></td>
  </tr>
  <tr>
    <td>Title:</td>
	<td><input type="text" placeholder="Title" name="title" size="50"/></td>
  </tr>
  <tr>
    <td>Company:</td>
	<td><input type="text" placeholder="Company" name="company" size="50" /></td>
  </tr>
  <tr>
    <td>Phone:</td>
	<td>
	    <input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/>
	    <span class="style1">Example: 1234567890</span> <span class="error" style="color:#990000"><?php echo $phoneErr;?></span></td>
  </tr>
  <tr>
    <td>Email:</td>
	<td><input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
        <span class="error"><?php echo $emailErr;?></span></td>
  </tr>
  <tr>
    <td>To:</td>
	<td><select name="to" size="1">
		<option value="Contact1@example.com">Contact 1</option>
		<option value="Contact2@example.com">Contact 2</option>
		</select></td>
  </tr>
  <tr>
    <td>Subject:</td>
	<td><input type="text" name="subject" placeholder="Subject" size="50" /></td>
  </tr>
  <tr>
  	<td valign="top">Detail:</td>
    <td colspan="2"><textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea></td>
  </tr>
  <tr>
    <td colspan="2" style="text-align:center;"><input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" /></td>
  </tr>
</form>
</table >

You can’t nest a form in a table like that. The only tags allowed between a <table> and <tr> tag are <caption> <col> <colgroup> <thead> <tfoot> <tbody>

<form> is invalid there - you need to move it outside the table or get rid of the table completely and use CSS to do the layout of the form instead.

Thanks for the reply, sorry about that I just wanted to include the form html in this post and didn’t realize I put <form> tags on the inside of my quick little table. My main concern is with the PHP and validation though. I know that I can validate and clear the form using JS/AJAX but the end users that will be using this site will not have JS support client side. The form itself will be using my css file to fit the layout of the actual page. One more thing I would like to know is can I use this in the PHP instead of putting the email address in the HTML? If it a bad idea or just not normally done.


//select the correct to address
switch ($to) {
case "1":
	$to = "contact1@example.com";
	break;
case "2":
	$to = "contact2@example.com";
	break;
default:
	$to = "contact1@example.com";
	break;}

And in the HTML of the form with the selector:


  <tr>
    <td>To:</td>
	<td><select name="to" size="1">
		<option value="1">Contact 1</option>
		<option value="2">Contact 2</option>
		</select></td>
  </tr>

Thanks again!

If the email address is always the same one then adding it from PHP is the best option. If there are a small range of emails then passing an indicator of which one and converting to the actual address in PHP is the best option.

All forms need to be validated on the server using PHP or another server side language. In the case of PHP the $_POST array will contain all the fields sent when the submit button is pressed. You then validate them before moving the values out of that array.

Any JavaScript validation is just a nice to have feature for the person filling out the form to save them having to submit the entire form before finding out what they got wrong.

The PHP validation will be different for each field because you need to validate that the information entered in each specific field is valid for that field eg

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {

for validating an email.

Thanks for the clarification regarding the email switch. There will be multiple contact emails that the form will be using. As for validation, when I submit with this form it sends an email regardless of what is or is not entered into the input fields. Example is the email field, leaving it blank still sends an email from the form and entering test@example sends one as well.

I updated the code by the way, using your advice and also finding a solution to my security concerns from a PHP book. Could you check it out and let me know what you think? Surprisingly I think I’m catching on, although something’s are still a little foggy. Thanks again!


<?php

//Sainitize function
function sanitizeString($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);

return $value;
}

$send = $_POST[send];

//Email validation - does not work by the way
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
   $email_error = true;
   $error_message[] = "Please use a valid email format: name@domain.com";
}	  

if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}
	
if($email_sent === true) {

$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);

// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {

        $nameErr = "Please enter your name.";
    }
    else {
        $name = $_POST["name"];
    }

    if (empty($_POST["email"])) {
        $emailErr = "Please enter your email."; 
    }
    else {
        $email = $_POST["email"];
    }
	if (empty($_POST["phone"])) {
		$phoneErr = "Please enter a phone number.";
	}
	else {
		$phone = $_POST["phone"];
	}
    if (empty($_POST["message"]))  {
        $messageErr = "Cannot leave message box blank."; 
    }
    else {
        $message = $_POST["message"];
    }

}

//select the correct to address
switch ($to) {
case "1":
	$to = "contact1@example.com";
	break;
case "2":
	$to = "contact2@example.com";
	break;
default:
	$to = "contact1@example.com";
	break;}

if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\
MIME-Version: 1.0 \
Content-type: text/html; charset=iso-8859-1";

$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;

if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "Thank you, your email is on the way!";}
else {$error_message = "There seems to be a problem!";}}

}
	
?>
<body>

<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table style="border-collapse:collapse; border-spacing:0" >
  <tr>
    <td>Name:</td>
	<td><input name="name" placeholder="Name*" type="text" class="text"/>
            <span class="error"><?php echo $nameErr;?></span></td>
  </tr>
  <tr>
    <td>Title:</td>
	<td><input type="text" placeholder="Title" name="title" size="50"/></td>
  </tr>
  <tr>
    <td>Company:</td>
	<td><input type="text" placeholder="Company" name="company" size="50" /></td>
  </tr>
  <tr>
    <td>Phone:</td>
	<td>
	    <input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/>
	    <span class="style1">Example: 1234567890</span> <span class="error" style="color:#990000"><?php echo $phoneErr;?></span></td>
  </tr>
  <tr>
    <td>Email:</td>
	<td><input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
        <span class="error"><?php echo $emailErr;?></span></td>
  </tr>
  <tr>
    <td>To:</td>
	<td><select name="to" size="1">
		<option value="1">Contact 1</option>
		<option value="2">Contact 2</option>
		</select></td>
  </tr>
  <tr>
    <td>Subject:</td>
	<td><input type="text" name="subject" placeholder="Subject" size="50" /></td>
  </tr>
  <tr>
  	<td valign="top">Detail:</td>
    <td colspan="2"><textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea></td>
  </tr>
  <tr>
    <td colspan="2" style="text-align:center;"><input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" /></td>
  </tr>

</table >
</form>


Continued Problems with validation and PHP