Skip to main content

PHP Forms

PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. PHP - A Simple HTML Form The example below displays a simple HTML form with two input fields and a submit button: Example
Name:
E-mail:
When the user fills out the form above and clicks the submit button, the form data is sent for processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST method. To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this: Welcome
Your email address is: The output could be something like this: Welcome John Your email address is john.doe@example.com The same result could also be achieved using the HTTP GET method: Example
Name:
E-mail:
and "welcome_get.php" looks like this: Welcome
Your email address is: The code above is quite simple. However, the most important thing is missing. You need to validate form data to protect your script from malicious code. Think SECURITY when processing PHP forms! This page does not contain any form validation, it just shows how you can send and retrieve form data. However, the next 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! GET vs. POST Both GET and POST create an array (e.g. array( key1 => value1, key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user. Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. $_GET is an array of variables passed to the current script via the URL parameters. $_POST is an array of variables passed to the current script via the HTTP POST method. When to use GET? Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases. GET may be used for sending non-sensitive data. Note: GET should NEVER be used for sending passwords or other sensitive information! When to use POST? Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send. Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. However, because the variables are not displayed in the URL, it is not possible to bookmark the page. Developers prefer POST for sending form data. PHP Form Validation This and the next chapters show how to use PHP to validate form data. PHP Form Validation Think SECURITY when processing PHP forms! 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: Field Validation Rules Name Required. + Must only contain letters and whitespace E-mail Required. + Must contain a valid email address (with @ and .) Website Optional. If present, it must contain a valid URL Comment Optional. Multi-line input field (textarea) Gender Required. 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: E-mail: Website: Comment: Radio Buttons The gender fields are radio buttons and the HTML code looks like this: Gender: Female Male Other The Form Element The HTML code of the form looks like this:
"> When the form is submitted, the form data is sent with method="post". What 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. What is the htmlspecialchars() function? The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with < and >. 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. Cross-site scripting (XSS) is a type of computer security vulnerability typically found in Web applications. XSS enables attackers to inject client-side script into Web pages viewed by other users. Assume we have the following form in a page named "test_form.php": "> Now, if a user enters the normal URL in the address bar like "http://www.example.com/test_form.php", the above code will be translated to: So far, so good. However, consider that a user enters the following URL in the address bar: http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E In this case, the above code will be translated to: This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited. Be aware of that any JavaScript code can be added inside the - this would not be executed, because it would be saved as HTML escaped code, like this: <script>location.href('http://www.hacked.com')</script> The code is now safe to be displayed on a page or inside an e-mail. We will also do two more things when the user submits the form: Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function) Remove backslashes (\) from the user input data (with the PHP stripslashes() function) The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again). We will name the function test_input(). Now, we can check each $_POST variable with the test_input() function, and the script looks like this: Example Notice that at the start of the script, we check whether the form has been submitted using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted - and it should be validated. If it has not been submitted, skip the validation and display a blank form. However, in the example above, all input fields are optional. The script works fine even if the user does not enter any data. PHP Forms - Required Fields This chapter shows how to make input fields required and create error messages if needed. PHP - Required Fields From the validation rules table on the previous page, we see that the "Name", "E-mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form. Field Validation Rules Name Required. + Must only contain letters and whitespace E-mail Required. + Must contain a valid email address (with @ and .) Website Optional. If present, it must contain a valid URL Comment Optional. Multi-line input field (textarea) Gender Required. Must select one In the previous chapter, all input fields were optional. In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function: PHP - Display The Error Messages Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields): Example "> Name: *

E-mail: *

Website:

Comment:

Gender: Female Male Other *

The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?". PHP Forms - Validate E-mail and URL This chapter shows how to validate names, e-mails, and URLs. PHP - Validate Name The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message: $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise. PHP - Validate E-mail The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function. In the code below, if the e-mail address is not well-formed, then store an error message: $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } PHP - Validate URL The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message: $website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } PHP - Validate Name, E-mail, and URL Now, the script looks like this: Example PHP Complete Form Example This chapter shows how to keep the values in the input fields when the user hits the submit button. PHP - Keep The Values in The Form To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the tags. The little script outputs the value of the $name, $email, $website, and $comment variables. Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons): Name: E-mail: Website: Comment: Gender: value="female">Female value="male">Male value="other">Other PHP - Complete Form Example Here is the complete code for the PHP Form Validation Example: Example

Comments

Popular posts from this blog

MySQL Databases PDO

PHP MySQL Use The ORDER BY Clause Select and Order Data From a MySQL Database The ORDER BY clause is used to sort the result-set in ascending or descending order. The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC To learn more about SQL, please visit our SQL tutorial. Select and Order Data With MySQLi The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"].

PHP OOP

PHP - What is OOP? From PHP5, you can also write PHP code in an object-oriented style. Object-Oriented programming is faster and easier to execute. PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions. Object-oriented programming has several advantages over procedural programming: OOP is faster and easier to execute OOP provides a clear structure for the programs OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug OOP makes it possible to create full reusable applications with less code and shorter development time Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the applicatio

PHP - AJAX

PHP - AJAX Introduction AJAX is about updating parts of a web page, without reloading the whole page. What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX AJAX is Based on Internet Standards AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) AJAX applications are browse