SimpleForm: Easy PHP multi-form email handler
— It’s been a while, but today I am releasing a new version of my contact form script, this time under the name SimpleForm. It’s a nicer version of the previous one, re-written from the ground up and with a couple of new features. SimpleForm is basically meant to be an easy solution to handle one or many forms with little effort. It’s mainly focused on ease of use and rapid deployment.

These are a couple of it’s main features ( ver. 1.1.4 ):
* Multiform handler.
* Support for required fields.
* PHP email validation.
* Unobtrusive JavaScript function to pre-check form data ( 4KB file ).
* Lightweight, easy to use.
* Multilingual support.
* External configuration file that can reside outside the public folder.
HOW DOES IT WORKS?
It’s very simple, first there is a configuration file where you define all of your website forms, by this I mean form title, form fields, form required fields and the location of each form. Then there are some snippets you have to add to your form page/s and thats all. SimpleForm takes care of pre-cheking the form fields with JS and then validating them with PHP, if it’s valid then it will send the email to the configured email address and return the user to the form page with a success message or otherwise, with an error message.
INSTALLING THE SCRIPT
These are the necessary steps to have it up and running ( requires PHP 5 ):
- Download SimpleForm ( ver 1.1.4 )
- Open sf-config.php and edit the necessary info.
- Upload sf-config.php to your host ( preferably outside the public folder ).
- Open simpleform.php and edit the variable $PATH_TO_CONFIG_FILE ( on line 24 ) with the path from simpleform.php to sf-config.php ( leave empty if it resides on the same folder ).
- Upload simpleform.php, simpleform.css and checkform.mini.js inside your public folder.
- Open your form page/s and add the necessary code snippets.
EDITING THE CONFIGURATION FILE SF-CONFIG.PHP
# ------------------------------------------------------------ # // SIMPLEFORM CONFIGURATION // # ------------------------------------------------------------ # /* GENERAL CONFIGURATION /////////////////////////////*/ // The name of the website/client. Example: "My Website". $aSettings["szFrom"] = ""; // The email address that will receive the emails. Example: "me@myemail.com". $aSettings["szRecipient"] = ""; /* The email address that will be used to send the emails. To work properly this has to be a real account configured on the same server of the site. Example: "noreply@mywebsite.com". */ $aSettings["szFromEmail"] = ""; /* FORMS CONFIGURATION /////////////////////////////*/ /* The next step is to configure the Form/s. You can add as many as you want. */ $aForms = array( 1 => array( // FORM ID: 1 "szFormTitle" => "", // FORM TITLE - Example: "Contact Form" "szFormURL" => "", // FORM URL ( users will be redirected to this page ) "szFormRequired" => array( /* REQUIRED FIELDS ( array of name attributes ) */ "name", "email", ), "aFormFields" => array( /* LIST OF FORM FIELDS AND THEIR OUTPUT NAME All input fields coming from the form should go here. The first value is the name attribute used and the second value on the right the name displayed on the outputed data. Any required field that contains the word "email" will have it"s value validated as an email address. */ "name" => "First Name", "email" => "E-mail", "work_email" => "Work Email", "phone" => "Telephone", "-sep1" => "This is a separator", /* This is a separator. Any variable starting with the sign "-" will act as a content separator. */ "color" => "Color Option", "comments" => "Comments", "-sep2" => "This is Another separator", "newsletter" => "Subscribe to our Newsletter?", "interested[]" => "Im interested in", /* add more */ ) ), 2 => array( /* Form 2. Same as above */ "szFormTitle" => "", "szFormRequired" => array(), "szFormURL" => "", "aFormFields" => array( /* add more */ ) ), 3 => array( /* Form 3. Same as above */ "szFormTitle" => "", "szFormRequired" => array(), "szFormURL" => "", "aFormFields" => array( /* add more */ ) ), /* add more */ ); /* RESPONSE CONFIGURATION /////////////////////////////*/ /* Response Messages: These are the variables that hold the messages the system prints as response. You can modify them to suit your project needs. */ // Form has been sent. $aSettings["aMessages"]["szSubmitSucess"] = "Your message has been sent succesfully. Thanks!"; // Missing fields. $aSettings["aMessages"]["szMissingFields"] = "Please complete all required fields."; // Unvalid email address. $aSettings["aMessages"]["szUnvalidEmail"] = "Please insert a valid email address."; // Email not sent by system error. $aSettings["aMessages"]["szSystemError"] = "There was an error in the system. Please try again later. Thanks!"; /* ADVANCED CONFIGURATION /////////////////////////////*/ // Name of the GET variable to pass response messages define( "GET_NAME", "response"); // Debug mode ( prints email content, and system errors ) define( "DEBUG_MODE" , false ); /* Check if the domain of the submited email addresses exists. False by default as it may bring problems with some servers. ) */ define( "CHECK_EMAIL_ADDRESS_DNS" , false );
INTEGRATING SIMPLEFORM WITH YOUR FORMS
Below you’ll find the things you need to do to your form page ( must be php file ) for SimpleForm to work. I also have included a full example at bottom.
A. Add Javascript and CSS files
Add simpleform.css and checkform.js ( or checkform.mini.js ) inside the <head> element:
<link rel="stylesheet" href="simpleform.css" type="text/css" media="screen"/> <script type="text/javascript" src="checkform.mini.js"></script>
B. Define the path to the config file and Include simpleform.php in the document ( before your form/s ):
<?php define( "CONFIG_PATH", "place/here/the/path/to/sf-congif/dir/" ); require_once "simpleform.php"; $sForm = new simpleForm(); ?>
C. Add SimpleForm Responses function
Prints the systems response and can reside anywhere on the document.
<?php // Example: <p class="message-box error">Please insert a valid email address.</p> $sForm->handleMessage(); ? >
Output example:
D. Add SimpleForm Form function
This function generates the required hidden input fields for simpleForm to work. The value passed is the ID assigned to the current form in the configuration file. This function must reside in between the <form></form> elements.
<?php //Prints necessary data for the form with the ID = 1 $sForm->printData(1); ?>
E. Edit the <form> attributes:
Point the form’s action attribute to simpleform.php and then add the checkform function to enable the js data pre-checking.
<form action="simpleform.php" method="post" onsubmit="return checkform(this)">
The checkform() function supports an optional string parameter which alters the text you
want to display on the js alerts. The variable #name is provided as a wildcard for the field Name.
Examples:
“Please complete the field #name”
“The field #name is missing”
“Por Favor complete el campo #name”
onsubmit="return checkform(this,'The field #name is missing')"
Full Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>SimpleForm Example</title> <link rel="stylesheet" href="simpleform.css" type="text/css" media="screen"/> <script type="text/javascript" src="checkform.mini.js"></script> </head> <body> <?php define( "CONFIG_PATH", "../secure/" ); require_once "simpleform.php"; $sForm = new simpleForm(); $sForm->handleMessage(); ?> <form action="simpleform.php" method="post" onsubmit="return checkform(this)"> <fieldset> <?php $sForm->printData(1); ?> <legend>Personal Details:</legend> <label for="name" >Name</label> <input name="name" id="name" type="text" value="" /> <label for="email">Email <span class="required">(required)</span></label> <input name="email" id="email" type="text" value="" /> <label for="work_email">Work Email</label> <input name="work_email" id="work_email" type="text" value="" /> <label for="phone">Telephone <span class="required">(required)</span></label> <input name="phone" id="phone" type="text" value="" /> <label for="color">Color Options: <span class="required">(required)</span></label> <select name="color" id="color"> <option value="-">Choose a color</option> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> <label for="comments">Comments</label> <textarea name="comments" id="comments" rows="10" cols="50"></textarea> </fieldset> <fieldset class="radio"> <legend>Subscribe to our Newsletter? <span class="required">(required)</span></legend> <label><input type="radio" name="newsletter" value="Yes" /> Yes</label> <label><input type="radio" name="newsletter" value="No" /> No</label> </fieldset> <fieldset class="checkbox"> <legend>Im interested in: <span class="required">(required)</span></legend> <label><input type="checkbox" name="interested[]" value="Arts" /> Arts</label> <label><input type="checkbox" name="interested[]" value="Science" /> Science</label> <label><input type="checkbox" name="interested[]" value="Sports" /> Sports</label> </fieldset> <p><button type="submit">Submit this!</button></p> </form> </body> </html>
RELEASE NOTES
ver 1.1.4 – Another Email Bug fixed ( Courtesy of megabonez ).
ver 1.1.3 – Email Bug fixed ( Mayor thanks to Jim from cpscreative.com ).
ver 1.1.2 – Minor Bugs fixed.
ver 1.1.1 – Optional Email DNS checking.
ver 1.1 – Easier path deployment, Configurable response variable name, Debug function and minor bug fixes.
ver 1.0 – First Release.




Matt,
Does the email validation support the “+” character, or will it fail validation like so many other incorrect email validation scripts?
Thanks
Hi Charles, yes it does validate emails with the plus character. Thanks for the comment!
I just broke the email validation. I first entered mail@mail.no and filled out the rest of the form. Then I went back up to the email, and removed “no”, so it said “mail@mail.” and it passed trough the validation :)
Hi Ronny, Thanks for the heads up, the script has been corrected.
Is it possible to customize/change the above form with additional fields and get this script work with them?
Hi Avaz, yes absolutely, the script supports as many fields and forms as you want. Build your form from the ground up and once done modify “sf-config.php” with the name attributes of your form. For example, lets say you built this form:
<form action="simpleform.php" method="post" onsubmit="return checkform(this)">
<?php $sForm->printData(1); ?>
<label for="price" >Price</label>
<input name="price" id="price" type="text" value="" />
<label for="amount" >Amount</label>
<input name="amount" id="amount" type="text" value="" />
<p><button type="submit">Order</button></p>
</form>
Then on ‘sf-config.php‘ you would configure the form incoming fields:
1 => array(
"szFormTitle" => "My Order Form",
"szFormRequired" => array("price","amount"),
"szFormURL" => "order.php",
"aFormFields" => array(
"price" => "Product Price",
"amount" => "Amount",
)
),
You can change the fields and required fields at any time, making it really easy to update the script. Of course you have to also follow the steps mentioned in the post above to make sure it will work correctly. Let me know if you still having doubts
Can i get all mail through this form into my free gmail account or php mailer needed. ?
Hi Jitendra. I’m not sure what you mean about php mailer, but aside from that, yes you can point the form to your free gmail account.
Hi Matt,
Thanks for this script. I’m kind of a newbie-intermediate with php. I’ve tried your script (the whole sample folder) after editing the necessary field. I get the email but it doesn’t pass the values from the checkboxes. Any ideas on this?
Another quick questions. I’ve tried your script on a different server (for my work) but I keep getting this error when I submit
PHP Fatal error: Call to undefined function checkdnsrr() in D:\inetpub\wwwroot\_newsite\sample\simpleform.php on line 224
I’m really not sure how to fix this error.
Thanks for any help.
Nice but u must also update the pre checking js validation of valid email address.
Hi E11World, glad you like SimpleForm. Please download the new version, It nows comes with the DNS check off by default. As for the checkboxes values it was a little code mistake I made on the last update. So this new one should fix it. Thanks for the comment!
Hi Shahriat, Thank you. I look forward improving the js pre-validation although I really want the keep the file size relatively small. Any suggestion are welcomed.
Thanks for this new version Matt. Everything worked except for one thing which I think could be differnt (if I understood it right).
After I hit submit, the page redirects to index.php or any page I want. If I leave it blank, it shows me a blank page.
Before you had it so it gives you the Sent Message on the same page. Is that not available in this version or is it just not working right for me?
I did change the $bDisplay = false; to $bDisplay = true; but it didn’t help. I don’t know what else to try now.
You are welcome, thanks for the feedback and also for downloading the new version. As for the Sent Message, if I understood correctly what you ask, simpleForm will always show the response messages after it redirects the user to the form page specified in "szFormURL" => "formpagenamehere.php" variable ( found on the sf-config.php file). Let me know if that helps or if you are referring to something else. Thanks again!
I guess I explained it wrong then. I don’t get any response message after submitting. It just goes to the page specified in the szFormURL. I guess something did go wrong for this not to show the message before redirecting.
How about just leaving the user on the page after they get the message?
This would be a really sweet addon to the script. I will work on this
http://orkans-tmp.22web.net/star_rating/index.html
I don’t know if anyone out there done this already though.
My bad Matt. I didn’t know that I was suppose to put the same page’s url there to do that. Now it works.
Another improvement I would suggest for this is, when the user gets an error, to re-populate all the fields with there values that the user entered instead of reseting them to blank.
Great script! Thanks for sharing. You might want to mention that it requires PHP 5. I initially had it testing on one of my subdomains running PHP 4 and it wouldn’t run at all…
Hi Jeff, thanks for the comment and suggestion, post updated.
First of all, thanks for sharing the script! I’ve found something probably usefull in case someone else is having the same problem as me.
I was trying to make it work, but it didn’t sent the emails until I changed the php ’safe mode’ on the server configuration. Aparently it has to be off if you want the script to work properly.
Hey Matt – Just wondering if you can recommend a good web host to use this with? I’m using Dotster and, even when inputting a valid email address associated with our account, I’m getting the error message – but at the same time I’m receiving the email.
Thanks!
Hi Jon, I have used this script across several hostings ( mosso, dreamhost, ixwebhosting, and others ) without problems. Is your server running PHP5?
Hi Matt,
First want to thank you for posting this great form!
In comparing what I’ve got working on my site and what you have on your demo page, I have a question about the response message.
If the user does not complete a required field, your demo highlights that field in red and displays a pop up message explaining the field is required.
On my site, if the user does not complete a required field the field box will highlight in red for a split second then I am redirected back to the same page (which I’ve specified, “szFormURL” => “contact.php”,) and the message is displayed above the form. However the required field boxes are no longer highlighted in red?
Is there anyway to keep the red highlighted boxes on the redirected ?response=2 page?
http://styleatile.com/contact.php
Thanks!
Hi Brian, glad you like SimpleForm. From what I saw, I’m guessing that you haven’t updated the required fields array in sf-config.php ( szFormRequired ) to match your form required fields. This is causing the JS script to search for a color,newsletter and interested[] field which don’t exists in your form thus skiping and giving an error. Hope that helps you,
Thanks for the comment!
Very nice
Hey. I like your CSS used in this script. It is wonderful. I keep getting this error when I run the script “There was an error in the system. Please try again later. Thanks!” Please what could be the problem?
Hi Matt!
Thanks for sharing but I’m a little confused… Firstly, why are there are two parts to the validation? JS and PHP – if i remove checkform.js, the PHP still validates and the user is presented with the more friendly css styled message – rather than the not so friendly JS message box.
Personally, i prefer the php validation – am i right in thinking i can just remove the checkform.js?
Secondly, whilst using only php validation – i am trying to make the form sticky, and failing miserably… I am using the following within the HTML form: (this is for the ‘name’ field)
value=”"
So the whole input line becomes:
<input type=”text” name=”name” id=”Name” value=”" />
But for the life of me, can’t work why it’s not working…
Any suggestions would be greatly appreciated!
Many thanks!
Hi Francis, thank you for the comment. Have you checked the php version you are running? It must be php5 for SimpleForm to work correctly. Thanks!
Hi Martin, thank you for the comment and sorry for the delay. What you mean by making your form sticky? You are correct you can use it without js validation, although users will get to fill the form again if they enter wrong data as it will reload the page to check the inputed data via php. Cheers!
Hey Matt,
First off, thanks for the great scripts. I love your subscribe and unsubscribe script, it was a joke to install and edit to my specifications (added an image echo when email was submitted so the form and buttons get covered).
As for this contact form, I was wondering, how would I go about by storing the form data in a database as well as emailing it.
Thanks in advance
I found a problem in a couple routines where you are using aSettings['szFrom'] instead of this->aSettings['szFromEmail'] which results in a weird sender. The functions are in simpleform.php: declareHeaders() and sendEmail(). I modified them as follows:
Line 285:
$this->szHeaders = ‘From: ‘ . $this->aSettings['szFrom'] . “aSettings['szFromEmail'] . “>” . “\r\n”;
Line 291:
if( mail( $this->aSettings['szRecipient'], $this->aSettings['szFrom']. ‘aSettings['szFromEmail'] . ‘>: ‘.$this->aForm['szFormTitle'], $this->szContent, $this->szHeaders, ‘-f’ . $this->aSettings['szFrom']. ‘aSettings['szFromEmail'] . ‘>’ ) )
Forgot to say first off, great script! :-) Just jumped right to the issues. Sorry about that!
Seriously Brilliant, well put together stuff. Thankyou!
Dear Jim, Thanks for pointing that out, can’t believe I didn’t noticed.
Just fixed the issue and updated SimpleForm to 1.1.3 please download it again.
Thanks again!
Thanks for the nice comment Alan! you are welcome,
cheers!
Hey Matt,
Great script again. I believe I caught an error on your most recent change.
simpleform.php line 291:
if( mail( $this->aSettings['szRecipient'], $this->aSettings['szFromEmail'].’: ‘.$this->aForm['szFormTitle'], $this->szContent, $this->szHeaders, ‘-f’ . $this->aSettings['szFromEmail'] ) )
this should be:
if( mail( $this->aSettings['szRecipient'], $this->aSettings['szFrom'].’: ‘.$this->aForm['szFormTitle'], $this->szContent, $this->szHeaders, ‘-f’ . $this->aSettings['szFromEmail'] ) )
Basically, this was causing the subject line of the email to be “[from email]: [form title]” instead of “[from]:[form title]”
Also, do you know of any fairly easy ways to record the data in a database?
Thanks,
-A
Thanks for everyone who been contributing and Megabonez for the new bug heads up, the script has been patched and re uploaded.
As for storing the emails on a database, the best solution would be to create a new private method in the SimpleForm class that loops trough the fields array and then stores this information into the database. The adequate place to call it would be only once the email is sent, ( private method sendEmail() ) as probably you want to save only successful emails. I can’t promise this will be a future add on, but will consider to include it in next versions.
Thanks again
thanks for the script. i was really looking for it
thanks for providing this script. I’ve been looking for something that is this simple and pretty for a few days now… he sample code is also very helpful :)
Great Works, Hats off Matt
this form is awesome!
how will this handle multiple recipients?
It would be cool, if fields could also be checked on numbers only, or for zipcodes, a special regex should be there as well as for text-only fields.
Hello!
I am trying to implement the simpleform.php (which I have done successfully on other sites), and I am getting the following error:
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in [path name to simpleform.php]
When I did a search I found at least 2 other websites out there with the same error message coming up related to this script.
Any ideas of what setting I have wrong?
Thanks!!
Hi,very good script,congratz.
I have a question… there is a way to put client mail on szfromEmail or something like that,simply for press reply button on client mail and not to click on email.
Thank you and sry for my english(im spanish).
@Amanda:
Sounds like you’re running PHP4 on your Server!?
Hi Matt, do you have a tut for the contact form? I am really new to all this and I just can’t seem to get things in order. Thank you!
- Achalla