11 Oct
Simple PHP Contact Us Form
I’ve noticed a simple contact us form is something that a lot of people frequently look for online, however many of the current solutions/examples out there are quite complex, ‘bloated’, and can also be, in some cases, complete overkill.
So here’s a simple PHP-based contact us form which makes use of one single PHP file to handle both the output of the form, the output of the thank you message, and the email processing.
You are more than welcome to copy and use this code both in a commercial and non-commercial sense.
-
<?php
-
if($_POST['contactus']) { // if user submitted the form, then
-
extract($_POST); // extract form contents and assign them to variables
-
$name = htmlentities($name);
-
$subject = htmlentities($subject);
-
$msg = htmlentities($msg);
-
$msg .= “Name: {$name}”;
-
mail(‘recipient-email@domain.com’,$subject,$msg);
-
}
-
?>
-
<html>
-
<head>
-
</head>
-
<body>
-
<form name=”contactus” action=”<?php $_SERVER['PHP_SELF']; ?>” method=”POST”>
-
Name: <input type=”text” name=”name” /><br />
-
Subject: <inpout type=”text” name=”subject” /><br />
-
Message: <input type=”textarea” name=”msg” /><br />
-
<input type=”submit” name=”contact” value=”Contact us” /></form>
-
</body>
-
</html>
It is crucial to consider that the automatically created variables, which were extracted from the $_POST array, are the same as the name of each input element.
For example:
<input type="text" name="xyz" id="xyz_input" />
Would result in a variable $xyz being created, which would be assigned the value of xyz_input.value
The htmlentities() functions are used to convert any HTML tags within the input boxes to the HTML character code equivalents, to help prevent unsanitized data from being processed. Note: Typically, using htmlentities alone is not enough – it’s strongly suggested that you use Javascript or PHP to validate the input fields prior to processing. In Web Development, always consider that someone out there may enter incorrect and/or potentially malicious data into your forms (google SQL injection, etc and you’ll see what I mean).
Obviously, if your web host doesn’t support the mail() function, you might have to consider sending your mail via an SMTP provider, using an SMTP class. There are plenty of these on the internet, however this SMTP class seems quite promising. (I haven’t used this, however – so any feedback would be greatly appreciated.)




