Friday, 3 January 2014

PHP Form Validation

PHP Form Validation  This and the next chapters show how to use PHP to validate form data.

                                                 "These pages will show how to process PHP forms with security in mind. Proper validation of form data is important to protect your form from hackers and spammers!"


The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:


The validation rules for the form above are as follows:
FieldValidation Rules
NameRequired. + Must only contain letters and whitespace
E-mailRequired. + Must contain a valid email address (with @ and .)
WebsiteOptional. If present, it must contain a valid URL
CommentOptional. Multi-line input field (textarea)
GenderRequired. Must select one
First we will look at the plain HTML code for the form:

Text Fields

The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
Name: <input type="text" name="name">
E-mail: <input type="text" name="email">
Website: <input type="text" name="website">
Comment: <textarea name="comment" rows="5" cols="40"></textarea>


Radio Buttons

The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male


The Form Element

The HTML code of the form looks like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
When the form is submitted, the form data is sent with method="post".


NoteWhat is the $_SERVER["PHP_SELF"] variable?

The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form.
NoteWhat is the htmlspecialchars() function?

The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

Big Note on PHP Form Security

The $_SERVER["PHP_SELF"] variable can be used by hackers!
If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.

No comments:

Post a Comment