Professional Documents
Culture Documents
by
Prasanth Janardanan
This is a Free Ebook. You have permission to share this and pass it along for free to anyone you like, as long as you make no changes or edits to its contents or digital format. The right to sell it, however, is strictly reserved. 1
Dedication: To All Simfatic Forms Users. You made this book possible.
Contents
1. Introduction ........................................................................................................... 6 1.1 1.2 How does a web form work? .......................................................................... 8 How to build a web form ................................................................................ 9
1.2.1 Hand-coding your form ............................................................................... 9 1.2.2 Using tools to build your form .................................................................... 9 1.2.3 Desktop form builders ................................................................................. 9 1.2.4 Online form builders .................................................................................. 10 1.2.5 The Downside to Online Form Builders ................................................... 11 2 The Front-End Of the Form ................................................................................. 13 2.1 Form Coding in a Nutshell ............................................................................ 14
2.1.1 FAQs ............................................................................................................. 15 2.1.2 Input Elements............................................................................................ 15 2.1.3 Structuring the form .................................................................................. 19 2.1.4 Styling the form .......................................................................................... 20 2.2 Form Validations ............................................................................................ 26
2.2.1 The Purpose of Form Validation ............................................................... 26 2.2.2 Give the User a Helping Hand ................................................................... 26 2.2.3 Be Liberal with Input Formatting .............................................................. 27 2.2.4 Make Error Messages Helpful ................................................................... 27 2.3 How to Structure a Web Form Well ............................................................. 30
2.3.2 Additional Information .............................................................................. 30 2.3.3 Pre-requisites .............................................................................................. 31 2.3.4 Images versus Text ..................................................................................... 31 2.3.5 Grouping ..................................................................................................... 32 2.3.6 The Great Scroll .......................................................................................... 32 2.4 How to Get More Form Submissions .......................................................... 34
2.4.1 Ask a Few but Relevant Questions............................................................ 34 2.4.2 Ask the most important question first ..................................................... 35 2.4.3 Explain why you are asking certain questions ........................................ 35 2.4.4 Assure security and privacy of the information submitted ................... 36 2.4.5 Provide Helpful Validation Messages ....................................................... 36 2.4.6 Avoid the Reset Button ! ............................................................................ 37 2.4.7 Avoid CAPTCHA ........................................................................................... 37 2.5 Creating Large Forms .................................................................................... 39
2.5.1 Making your web forms more usable: ..................................................... 39 2.5.2 Design strategy for very large forms ........................................................ 40 3 The Back-End of the Form .................................................................................. 43 3.1 3.2 Server-side Validations ................................................................................. 43 Emailing .......................................................................................................... 45
3.2.1 Simple Emailing .......................................................................................... 45 3.2.2 Advanced Emailing ..................................................................................... 45 3.3 3.4 Saving to database ........................................................................................ 47 Handling File Uploads ................................................................................... 49
3.5
3.5.1 Spam and CAPTCHA ................................................................................... 52 3.5.2 SQL Injection ............................................................................................... 53 3.5.3 Cross Site Scripting (XSS) ........................................................................... 55 3.5.4 Cross Site Request Forgery (CSRF) ............................................................ 57 3.5.5 Email Header Injection ............................................................................... 58 3.5.6 Other Preventative Techniques ................................................................ 60 3.5.7 Security and Usability Balancing ............................................................... 61 4 References ............................................................................................................ 63
1. Introduction
Web forms are a critical part of your website's success or failure. You may have spent a fortune on an attention-grabbing headline, compelling text, great illustrations, a pleasing layout, perhaps some fast-loading video - but if your forms fail, so does your site! Failure can mean a lot more than just code failure and error messages; it can also mean forms that don't get filled in, or are filled incorrectly. Keep an eye on your email inbox, as I'll be sending you some free bonus design tips to address such issues. Talking of free ... THIS GUIDE IS FREE OF CHARGE! Please note I created this guide to help my friends and visitors to www.Simfatic.com. It is given to the community for free. If you paid money for it then you should demand a refund! Also, feel free to pass this guide to anyone you think might need it, as long as this introduction is left intact. This guide takes you through the essentials of building professional quality web forms for websites (web forms).
Follow the examples and soon you will be able to manually build contact forms, appointment forms, surveys, lead capture forms and more. Of course you can cheat and use Simfatic Forms software instead: www.simfatic.com Sometimes though, even if you can automate things, it helps to know HOW and WHY it works! OK, let's get started...
The client side of the form handles the 'look & feel' of the form (aligned labels, fonts, colors etc.) . You can also add a bit of helpful validation in this part of the form. The server side processing script does all the back-end core functionality like sending emails, saving the submissions to a database and so on. The client side of the form runs in your visitor's browser. It can't do the heavier stuff like emailing or saving to database. So, to run a complete form, you need a web server where you can run your server side processing script.
8
10
You can design your form, choose the options and the software generates the code for you. Then you can just upload the generated code to your website and you have an online form online ready to accept submissions. This is the easiest method and how the Simfatic Forms software works. Here are some of the advantages: Your forms run on your own webserver Lots of customization options. You can build any number of forms for any number of websites No monthly subscription fee.
Online form builders both build and then host your form. That means the server side processing remains on their website and you just have to embed the client side of the form in your web pages. You can later log-in to their website to view your form submissions. Since the form is hosted on their website you don't have to worry about the server-side configuration such as creating a database and giving it permissions. That makes them very easy for short-term forms such as surveys or planning a one-time event like a wedding.
10
11
11
12
All of those downsides magically turn into benefits when you host your own form processing script on your own server.
12
13
For tutorials and introductions to these languages, see the reference section.
13
14
<form method='post' action='/handle-form.php'> <p> <label for='name'>Name:</label> <input type='text' name='name'/> </p> <p> <label for='email'>Email:</label> <input type='text' name='email'/> </p> <p> <input type='submit' name='submit' value='Submit'/> </p> </form> The form above has a name field, an email field and a submit button.
method='post' means the form submission data is not sent as part of the URL. For most forms, it should be good enough to keep the method='post'
action='/handle-form.php' means the form submission should be send to a script in the URL: /handle-form.php
<input type='text' name='name'/> Creates a single line text field. (Notice the type='text' attribute) . Every field in the form should have a name. That name is used to identify the field in the server side script.
14
15
<input type='submit' name='submit' value='Submit'/> Creates a submit button. Pressing the submit button sends the form submission to the server side processing script.
2.1.1 FAQs
Some Frequently Asked Questions on basic HTML Form: 1. How can I create sub forms? or How can Create Nested forms? There is no sub forms or nested forms. One form can't contain another form. What you need to do is a visual representation of sections in a single form (this is explained in later chapters ) 2. How can I make the form send an email to me? The only reliable way is to code the server side processing script (handleform.php in the example above) to collect the form submission and send the email.
15
16
The most common input method on an HTML form is the text box. To add one of these to your form, use the code in this way: <input name="name" size="15" type="text" />
This creates a single-line box that is 15 characters wide, and allows the user to enter as much text as he wants. When you refer to this box from a form mail script, you will use its NAME value. Multiline textbox
For a text box with multiple lines, use the following code: <textarea name='Address' rows='3' cols='30' > </textarea>.
Instead of having just a single line to input on, the user can perform carriage returns to make better formatting of the text. This is also easier if the user will be inputting a large amount of text address or comments for example. Its much easier to have it all in a large text area, and be able to scroll through it. Drop-down List
16
17
For dropdown list, the user can choose only one option from a number of available options. <select name="colors"> <option> Red </option> <option> Green </option> <option> Yellow </option> <option> Blue </option> <option> Orange </option> </select>
Create a drop-down list when the user is to select from a big set of values. When the number of options is less than 5, consider using radio buttons instead. Check box
A toggle switch that user can select or deselect.(example: subscribe, 'Agree' etc) <input type="checkbox" name="subscribe" value="yes" />Send me email notifications
When you have a number of options to select from a set, create a checkbox group.
17
18
<input name="color[]" type="checkbox" value="green"/>green <input name="color[]" type="checkbox" value="red" />red <input name="color[]" type="checkbox" value="blue" />blue
Radio buttons
Use radio buttons when the user can choose only one option from a number of options. <input checked="checked" name="answer" type="radio" value="true" />True <input name="answer" type="radio" value="false" />False
Any of the radio buttons with the same name will fall into the same group, and only allow one at a time to be checked. File Upload
When you want to let your users upload a file along with the form submission, use a file upload widget. Upload your profile photo: <input type="file" name="photo" />
18
19
Here is the code: <fieldset > <legend>Personal Information</legend> <label for='name'>Name:</label> <input type='text' name='name' id='name'/> </p> <p> <label for='email'>Email:</label> <input type='text' name='email'/> </fieldset>
19
20
In both the cases, label being close to the input element visually indicates which label is for which input element. Label being far from the input element fails to establish the relation between the label and the input element.
A nicely designed form can contain both the first two styles of labels. Right Aligned Labels Sample code for making right-aligned labels:
20
21
HTML <div class='container_2_col'> <label for='name' >Name:</label> <input type='text' name='name' id='name'/> </div> <div class='container_2_col'> <label for='email' >Email:</label> <input type='text' name='email'/> </div> CSS .container_2_col label { text-align:right; width:30%; display:inline-block; vertical-align:top; } .container_2_col { margin:25px 0px; } The container_2_col class sets a vertical margin and right aligned label having some width. Here is the sample form in this style:
21
22
You can download the sample code for this form from the link below: aligning-labels.zip Top Aligned Labels The sample code for top aligned labels: HTML <div class='container_1_col'> <label for='name' >Name:</label> <input type='text' name='name' id='name'/> </div> <div class='container_1_col'> <label for='email' >Email:</label> <input type='text' name='email'/> </div> CSS .container_1_col {
22
23
Note that the label has display:block and align left in the single column(top aligned label ) style. The form made in this style:
You can download the sample code for this form from the link below: aligning-labels.zip It is usually best to mix both the right-aligned style and the top aligned style.
23
24
When the input field is smaller, make it right-aligned. When it is large, align the label on top. Example:
Reusing the form style You can reuse the master-form-style.css in the sample code above while making your forms. Follow these steps: 1. Include/link to the master-form-style.css in your HTML form page: <link rel="stylesheet" href="master-form-style.css" type="text/css" />
24
25
2. If you want right aligned label, just wrap the input elements in a <div> with container_2_col class <div class='container_2_col'> <label for='email' >Email:</label> <input type='text' name='email'/> </div>
3. If you want top-aligned label, use the container_1_col class instead: <div class='container_1_col'> <label for='name' >Name:</label> <input type='text' name='name' id='name'/> </div>
Using labels with Checkboxes and radio buttons You can wrap the label tag around the check box element or radio box element like this: <label class='wrapper'> <input type="checkbox" name="subscribe" value="yes" /> Send me email notifications</label> <label class='wrapper'> <input type="radio" name="color" value="green" />Green </label> The advantage of using the label this way is that clicking on the label checks/unchecks the checkbox/radio button
25
26
26
27
If you want your visitors to take full responsibility for the accuracy of their entries, the offer of some how-to hints can help. Provide correct and easily visible formatting tips up front. Supply uncommon fields with a clickable link to additional information Offer dynamic tips like "this field must be numeric" when the user types invalid data. Demonstrate the formatting like "mm/dd/yyyy" or"###-##-####"
28
One common problem with error display is that the message itself may not be visible to the user. This usually happens when the errors are shown on the top of the form or bottom of the form. The best approach is to display the error message next to the corresponding input and make sure that the message is visible. (Scroll to the message box using JavaScript)
The Intelligent Error Message In addition to showing the user what is wrong with his input, a well-thought error message will explain in simple terms the best way to correct it. If its wording is too brief or overly technical, your user will just get frustrated Proper positioning is just as important. An error message should always display alongside the field in question. Showing it at the top or bottom of the screen won't help the user much. The worst type of error message is one that appears in a pop-up window or redirects to another page. Either of these will force the user to navigate back to the form, and when he does, your carefully worded explanation will disappear from view. If this happens more than once, the user might decide to disappear as well.
28
29
29
30
2.3.1 Heading
Why are we here? In general, a web form does not have a complex purpose, but it does have a purpose. Once youve lured your visitor to the form, that purpose should be made plain in the forms heading. Simplicity is best Google may not be known for the aesthetics of its offerings, but it frequently gets the user experience right, especially in its most popular products. In Gmail, for example, new users are offered the chance to Sign up for Gmail on a page that highlights three features that, in Googles eyes, set the service apart from the competition. A click on the sign-up link leads to a page that simply says Create an Account. Those three words tell you everything you need to know Subheads also work well if they adhere to the same principles. If you present users with a long form, help them to navigate by inserting short, simple and clear subheads at intervals. Otherwise, people will be lost in the midst of what feels like an endless chore.
31
Not all forms are created equal, and there are situations in which its appropriate to introduce the form by providing the user with additional information. Having brought your visitor this far, though, you want to make it as easy as possible for him or her to continue. Again, brevity is best. Users will avoid large blocks of text, skipping directly to the form. Keep introductory information to a minimum. Edit ruthlessly, breaking text into digestible paragraphs of short, declarative sentences, and youve maximized the chance that users will pay attention.
2.3.3 Pre-requisites
If a form requires certain information, advise users in advance, especially if its the kind of information that may not be instantly available to the average user. Theres no need to warn users that theyll be asked for names, addresses and phone numbers, but it is worth alerting them to the need for certain less obvious pieces of information, including: Drivers license numbers Social security numbers Insurance policy numbers Model numbers for devices
Giving that kind of notice is, for one thing, a sign of consideration for your visitors. For another, it can help to avoid the situation in which users abandon a half-completed form when theyre confronted with questions that they cant answer immediately. Instead, youve captured the momentum they generated when starting the form.
32
It bears repeating that large blocks of text are not user-friendly. At best, users may skim them. At worst, they avoid them altogether. This problem occurs in many contexts, not just in the design of forms, and the solution often involves images. Images are not purely decorative, although they can certainly add variety and visual appeal. Use images to explain, when possible.
2.3.5 Grouping
People thrive on patterns. We see them when theyre there and we impose them on the world when we can. Grouping fields into related sections, a process also called chunking, makes it easier for people to process the information thats in front of them. Presenting users with a page of 25 undifferentiated questions gives those users nothing to hang on to. Grouping those questions into related subjects and setting them apart with appropriate sub-headings helps users to understand whats happening. The entire process is easier. For the best experience, groups can be numbered, and the form can be accompanied by an indication of the users progress through the form. Instead of leaving people in limbo, tell them the stage theyve reached. Show them that questions are part of a logical progression and that theres an end in sight. Those small courtesies will make for a happier audience.
33
confusing and difficult to navigate. Horizontal flow, even if applied consistently, feels awkward and unnatural. If you scroll through a page, we assume that you are moving vertically. If your mouse has a scroll button, its default configuration is on the vertical axis. So make your form flow vertically. A consistent vertical flow is what feels natural to users, and its what they have come to expect.
33
34
34
35
36
survey if the form is for survey. You should also assure them of the confidentiality of the information they provide and reassure them that you will not share this information with any other person. Information is very sensitive in this modern age and people are not always willing to give their details easily. You therefore need to explain why you need such information in order to get more form submissions.
37
Validation messages that are conversational in nature are better than bland error messages.
37
38
CAPTCHA Validation tests are a way of confirming that the user filling in the web form is actually a human being. This involves something that may be possible for a human being to accomplish but not a robot. However, CAPTCHA tests are frustrating to most users. They are usually very confusing and the user may get it wrong several times thus giving up. Also note that CAPTCHA tests are only to avoid automated submissions of the form. CAPTCHA does not add any other security to the form! There are other, non-intrusive ways to avoid CAPTCHAs. Consider CAPTCHA only when none of the alternatives work and you start getting too many spam submissions. Getting more form submission starts with the right design and a plan. With the points highlighted above, you can be able to design a proper form the user will fill to completion and submit successfully. You will also get more honest answers and your users will have a better experience with forms.
38
39
40
Fields should be presented logically, so that it makes sense to the visitor. For example, there is no point in asking for marital status after making the visitor input the spouse's name. Correct order also makes it easier for you to validate inputs as the form is filled. It is easier and faster to tab through fields than using the mouse to click each one before entering it. Pay attention to the tab order so that the control moves logically from field to field. If you get this wrong and the control keeps jumping randomly, visitors are likely to abandon the form. Use white space properly: If you are keeping all the fields on a single page, don't try to cramp all of them together to accommodate everything without scrolling. Most visitors are fine with vertical scrolling. So use white space wisely. Hide what is not required: Long web forms often collect information that fit a wide group of people. As the form is filled, some of the fields may become irrelevant to the visitor. Hide irrelevant fields so that the visitor does not have to read them and waste time. Take care with validation so that you don't make any of the irrelevant fields mandatory. Though this may seem fundamental, this is one aspect that usually goes wrong with long forms. Example is when the use has been forced to enter a dummy zip code even though he is not living in the US.
41
form is so large that it becomes necessary to break it up into multiple pages? Here are three popular strategies: Using the Wizard Design: A wizard is nothing but a way of presenting the form in steps. You show only a small logical section in each step. We are all familiar with this approach, as the windows installer uses this approach when we install new software.
The user moves back and forth from page to page using the 'Back' and 'Next' buttons. This also allows us to hide irrelevant pages from the visitor. The inputs can be validated on each page making things easier for the visitor. We can also save the inputs after each section so that nothing is lost. Show a page count or progress bar so that the user knows how many pages are left. Show/Hide Sections Hiding/showing a section is useful when there are mutually exclusive set of input fields. For example, you can have a check box that says Billing address is same as shipping address. If enabled, that check box hides the section of Billing address fields Other Tips for Large Forms Keep unnecessary distractions like links, ads and special offers away. Don't tempt the user to leave the form and move to something else. Give helpful information for filling out the form on one side. Give explanatory text near the fields in case they are confusing. Provide default values, drop down lists and radio buttons whenever possible.
41
42
Use icons or symbols, if they make sense, to make things more clear and attractive
As you can see, a lot of planning is required for designing long web forms. Better planning will result in a better design and more form submissions. If you take the time to do the planning and put some thought into the design elements, your visitors will enjoy filling your form even if it is a little long. Whatever you do, don't make the form look like an add-on to your website, let it blend in with the design and be a part of it.
42
43
44
$length)
Using those validation functions : if(!empty($_POST['submit'])) { if(!checkMandatory('name')) { $errors[] = "Please enter your Name"; } elseif(!checkMaxLength('name',10)) { $errors[] = "The name is too long!"; } if(!checkMandatory('email')) { $errors[] = "Please enter your Email address"; } elseif(!checkEmail('email')) { $errors[] = "Enter the correct email address"; } if(empty($errors)) { /*Successful validation*/ header("Location: thankyou.html"); exit(); } } You can download the sample validation code here: form-validation.zip
44
45
3.2 Emailing
The common need for any form processing script is to send a notification email that the form was submitted by a visitor.
$myemail = 'yourname@website.com';//<----- Replace Your email address here. /* do validations here */ /*Send the form submission by email*/ $email_subject = "A new form submission"; $email_body = "You have received a new form submission \n"; foreach($_POST as $key => $value) { $email_body .= "$key : $value \n"; } $headers = "From: $myemail\n"; mail(/*to*/$myemail,$email_subject,$email_body,$headers);
You can download email sample code from the link below: email-form.zip
46
Here is some sample code that uses PHPMailer: require_once("class.phpmailer.php"); $myemail = 'yourname@yourdomain.com';//<<---Replace your email address here $mailer = new PHPMailer(); $mailer->CharSet = 'utf-8'; $mailer->AddAddress($myemail,'YourName'); $mailer->Subject = "New form submission"; $mailer->From = $myemail; $email_body = "You have received a new form submission <br/>\n"; foreach($_POST as $key => $value) { $email_body .= "$key : $value <br/>\n"; } $mailer->MsgHTML($email_body); $mailer->Send(); For more information on PHPMailer see the PHP mailer documentation
46
47
$db = mysql_connect("servername","username","password"); //<<---Enter your mysql login details here if(!$db) die("Error connecting to MySQL database."); mysql_select_db("databasename" ,$db); //<<---Enter your database name here //<<-- you should have the table (subscriptions) created first $sql = "INSERT INTO subscriptions (name, email, message,subscribe) VALUES (". PrepSQL($_POST['name']) . ", " . PrepSQL($_POST['email']) . ", " . PrepSQL($_POST['message']) .", " . PrepSQL($_POST['subscribe']) .")"; mysql_query($sql); // function: PrepSQL() // use stripslashes and mysql_real_escape_string PHP functions // to sanitize a string for use in an SQL query // // also puts single quotes around the string // function PrepSQL($value) { // Stripslashes if(get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote $value = "'" . mysql_real_escape_string($value) . "'"; return($value); }
47
48
The code above connects to the MySQL server, selects the database and inserts the form submission data. (Please note that the form validations should already be done before this part of the code) You can download the full code from the link below: database-form.zip
48
49
The file upload box is created using the input tag with type="file" <input type="file" name="uploaded_file">
Now, on the server side, we can access the uploaded file's information from the $_FILES array. $_FILES['uploaded_file']['name'] contains the file's name and $_FILES["uploaded_file"]["tmp_name"] contains the temporary file path of the uploaded file. Here is the PHP code to copy the uploaded file to a file uploads folder:
$upload_folder ='../../uploads/'; //<<-- This folder must exist and should be writeable
49
50
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']); $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; $tmp_path = $_FILES["uploaded_file"]["tmp_name"]; if(!move_uploaded_file($tmp_path,$path_of_uploaded_file)) { $errors .= '\n error while copying the uploaded file'; } You can download the full code from the link below: file-upload.zip
Plupload http://www.plupload.com/
50
51
51
52
never trust user input". Simply put, this means that a user can be just
about anyone, from a man using a computer for the first time or someone who has extensive experience as a hacker. There is no way to tell. In this section, we are going to take a serious look at the more common security vulnerabilities associated with web forms and how we can best overcome them. The following 5 are the more common forms of web form hacking: - Spam - SQL Injection - XSS - CSRF - Email header Injection
53
In this example the user inputs their information like this: Username=smith Password=smith123
53
54
The query then searches the table of users for instances where the username is "smith" and the password is "smith123". Now here is what a hacker will do. A hacker will use the following user name and password to gain unauthorized access. Username=smith Password=' OR 'x'='x
Now let us take a look at just what such a query will do. When we insert these values into a query it will look like this: SELECT * from users WHERE name='smith' AND password='' OR 'x'='x';
The form of query will search for the name "smith" in the database, just as it did in the previous example, but instead of searching that string for the password it will see the query as 'x'='x'. The server reads this query as a true statement so if the username "smith" exists in the database and is true according to the query, then the password will be bypassed as a true statement. That string x'='x is commonly referred to as the magic string. To prevent such SQL Injection, there is a built-in function in PHP called mysql_real_escape_string() , which escapes certain characters so that the SQL query is not modified. Here is the PHP function to sanitize form input before using in an SQL query:
54
55
// function: PrepSQL() // use stripslashes and mysql_real_escape_string PHP functions // to sanitize a string for use in an SQL query // // also puts single quotes around the string // function PrepSQL($value) { // Stripslashes if(get_magic_quotes_gpc()) { $value = stripslashes($value); } // Quote $value = "'" . mysql_real_escape_string($value) . "'"; return($value); }
Look at how the SQL statement look like, after this update: SELECT * from users WHERE name='smith' AND password='\' OR \'x\'=\'x'
Note that the quote characters are escaped with a slash \ making SQL query compare password with the entered value (' OR 'x'='x). The SQL query can not be modified any more.
56
browser and adds them to their own browser, so that whenever the hacker opens that site in their own browser it will him them a logged in account of the infected client. Let's assume that you have a guest book form on your website where clients are able to leave you feedback. The user feedback is displayed on the guestbook entries page like this: <h1>Feedback from: <?php echo $name ?> </h1>
A normal user will input his name and will get response like this: Feedback from Smith Johns Now let's take a look at what a malicious user will input. Let's assume the malicious user inputs their name as: <script>alert("Whoopey! I could run a script");</script>
Now the HTML code in the guestbook entries page looks like this: <h1>Feedback from: <script>alert("Whoopey! I could run a script");</script></h1>
56
57
When the guest book entries page loads. This is seemingly harmless. However, the harm occurs when the hacker steals cookies from the users computer and posts it to his own server: <script>post_to_myserver(getcookie('sessionid'));</script>
To avoid this problem, always use the PHP function htmlentities() to display any user entered data on a web page. So the corrected code is : <h1>Feedback from: <?php echo htmlentities($name) ?> </h1>
Now, if the hacker enters script code, it will be converted like this: <script>alert("Whoopey! I could run a script");</script> The browser will display it exactly as the HTML code entered.
57
58
Cross Site Request Forgery (CSRF) is a one click attack. This attack is used in websites that has signup and login. Most of those websites use cookies to remember the user and the user does not have to login every time. The malicious user embeds a hidden form that contains "ACTION" onto the target website and then sends the link to the victim. When the user clicks on the link the hidden form is submitted and the form then uses the session of the active user (in this case the victim). Since the website remembers the user, the changes are made in to his account. In this way the attacker has the ability to remotely make changes to the victim's account information. Let's look at an example of how this form of malicious attack works. The malicious user can use this technique to update an email address with his own email and then gain access to reset passwords. Once the attacker has reset the passwords of the victim's emails he can then take control of the victim's account. In order to avoid this problem, Check and make sure that the user had initiated the account update process by loading the form. Request the user to login again before making changes to his account. Send a confirmation link to the user to complete account update the process
58
59
this happens you are at risk of wasting mailing resources and in some cases you may even find your mail server being blacklisted. Let's look at an example of how this form of attack works. Let's assume you have a feedback or contact us page on your website When sending an email you have two options available for sending to multiple recipients. These are CC which means carbon copy and BCC which means Black Carbon Copy. In either CC or BCC you have the ability to add other email addresses of people you want to send the email to. Using CC will send addresses to all users and are visible to all recipients but when you use BCC the email will go to multiple recipients but the email addresses are not visible to every recipient. The PHP mail() function has 4 parameters: to, message, subject and headers. The headers parameter can contain multiple attributes like From , CC or BCC separated by new lines. (By the way, this is not specific to PHP. The mail headers can contain parameters separated with newline in any platform) Now a typical email code looks like this:
= = = =
mail($to, $subject, $message, $headers); Note that the email field is used in the emailing code without any filtering. Let's say that the spammer or attacker puts the following into the email field:
59
60
In this example \r\n indicates the end of one email header and the beginning of the next. We can also add multiple emails with this technique. Here we have the issue of "\r\n". We need to block the user from inputting this or find a way to filter the user's input in this way:
/* Sanitize() function removes any potential threat from the data submitted. Prevents email injections or any other hacker attempts. if $remove_nl is true, newline chracters are removed from the input. */ function Sanitize($str,$remove_nl=true) { if($remove_nl) { $injections = array('/(\n+)/i', '/(\r+)/i', '/(\t+)/i', '/(%0A+)/i', '/(%0D+)/i', '/(%08+)/i', '/(%09+)/i' ); $str = preg_replace($injections,'',$str); } return $str; } Any data from the form should be filtered with such a sanitize function first $headers = 'From: '.Sanitize($_POST['email']);
61
There are other techniques we can use to prevent spammer attacks. As we have already discussed it is imperative to never trust anything a user inputs. If some of the value is going to the database we must ensure that all input is properly filtered before it reaches the database server. It is the same in the case of a mail server. Security checks must be implemented on the server side coding (PHP or other). For example, in a form we must not limit ourselves to JavaScript validations. Validate on the server side as well. By putting security measures into play before spammers have the opportunity to infiltrate your website through web forms you can prevent a lot of damage from occurring. Your web form security should be a priority and not something that is addressed after an attack. Remember that you owe users of your web forms the security their private information deserves, and if you lose that trust through not implementing adequate security measures you will lose respect, credibility and your business will suffer as a result.
61
62
security to your form or website. CAPTCHA just adds frustration to your users and will cause your form submissions to drop. Misconception 2 : Very tight Form Validation Increases Security Some forms validate with very tight input patterns. For example, not allowing non alphabetic characters in names, allowing only numbers in phone number field, restricting punctuation characters in feedback/message fields etc
This usually originates from the misconception that such validations will increase security and will close vulnerabilities. The fact is, it will not . Too much of validations will just cause more trouble to your users. Peoples names can contain non-alphabetic Characters (o'connor ).Some people prefer entering phone numbers separated with space or hyphen. As explained in the Form Validation Section, being liberal on input field patterns makes it easy to complete the form. Handle it in the server-side Handling security is the server-side coders job. The server side programmer should properly filter convert the user input before saving to database, sending emails or before displaying on a web page. Do not trouble your website users in the name of security.
62
63
4 References
Books Designing with the Mind in Mind: Simple Guide to Understanding User Interface Design Rules by Jeff Johnson Don't Make Me Think: A Common Sense Approach to Web Usability by Steve Krug Web Form Design: Filling in the Blanks by Luke Wroblewski Forms that Work: Designing Web Forms for Usability Caroline Jarrett & Gerry Gaffney HTML and CSS: Design and Build Websites by Jon Duckett JavaScript & jQuery: The Missing Manual by David Sawyer McFarland JavaScript: The Good Parts by Douglas Crockford Learning PHP, MySQL, JavaScript, and CSS: A Step-by-Step Guide to Creating Dynamic Websites by Robin Nixon Programming PHP by Kevin Tatroe, Peter MacIntyre and Rasmus Lerdorf
Add more books: http://www.ebooksselection.com
63