Summary: in this tutorial, you will learn how an HTML form works and how to capture data from HTML form in PHP.
An HTML form consists of HTML input elements that allow you to enter the data and submit it to the web server. Those input elements include text input field, password field, checkbox, radio button, file select field, submit button…etc.
An HTML form begins with an opening <form>
tag, and ends with a closing </form>
tag as follows:
1 2 | <form action="script.php" method="post"> </form> |
There are two important attributes of the <form>
tag:
action
: the action attribute accepts an absolute URL (http://localhost/phpcontactform/contact.php
) or relative URL (/contact.php
) where the data is submitted to when user submits the form.method
: the method attribute specifies how the web browser sends the form data. You can usePOST
orGET
. ThePOST
method allows you to send large amounts of data, while theGET
method is useful for sending small amounts of data via URL.
In order to read the data from the HTML form, you need to use one of the following superglobal variables:
$_GET
array contains a list of field names and their values of the form that uses theGET
method.$_POST
array contains a list of field names and their values of the form that uses thePOST
method.$_REQUEST
array contains field names and their values of both$_GET
and$_POST
, as well as values in the$_COOKIE
superglobal array.
The following picture is an HTML contact form that we are going to create:
We will use the POST
method in the contact form so we need to read the form data from the $_POST
array. For example, we can read the name
field value from the $_POST
array as follows:
1 | $_POST['name'] |
However, we should always verify the data that users submit to the server in order to prevent malicious users who are trying to hack the site. PHP provides a very handy function named filter_var()
that not only removes any illegal characters from the data but also checks if the data is in valid form.
The following example demonstrates how to remove any illegal characters from the name
field in the form:
1 2 3 4 | <?php if($_POST['name'] != ''){ $name = filter_var($_POST['name'],FILTER_SANITIZE_STRING); } |
To check whether an email is in the proper format, we use the following code snippet:
1 2 3 4 5 | $email = filter_var($_POST['email'],FILTER_SANITIZE_STRING); if(!filter_var($email,FILTER_VALIDATE_EMAIL)){ // invalid email } |
We used the filter_var()
function twice:
- First, we removed all illegal characters from the email form field value.
- Second, we checked if the email is in proper format.
To make the form nicer, we will use Twitter Bootstrap framework.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | <?php define('MAIL_TO','webmaster@example.com'); $errors = array(); $name = ''; $email = ''; $subject = ''; $message = ''; /** * validate form data * @return boolean return true if no error found, otherwise return false */ function validate_form(){ global $errors, $name, $email, $subject, $message; // validate name if($_POST['name'] != ''){ $name = filter_var($_POST['name'],FILTER_SANITIZE_STRING); if($name == ''){ $errors[] = 'Name is not valid'; } }else{ $errors[] = 'Name is required'; } // validate email if($_POST['email'] != ''){ $email = filter_var($_POST['email'],FILTER_SANITIZE_STRING); if(!filter_var($email,FILTER_VALIDATE_EMAIL)){ $errors[] = 'Email is not valid'; } }else{ $errors[] = 'Email is required'; } // validate subject if($_POST['subject'] != ''){ $subject = filter_var($_POST['subject'],FILTER_SANITIZE_STRING); if($subject == ''){ $errors[] = 'Subject is not valid'; } }else{ $errors[] = 'Subject is required'; } // validate message if($_POST['message'] != ''){ $message = filter_var($_POST['message'],FILTER_SANITIZE_STRING); if($message == ''){ $errors[] = 'Message is not valid'; } }else{ $errors[] = 'Message is required'; } if(count($errors)){ return false; }else{ return true; } } /** * display field value * @param string $fieldName */ function display_value($fieldName){ echo isset($_POST[$fieldName]) ? $_POST[$fieldName] : ''; } /** * display message to users * @param array $errors array of errors */ function display_message($errors){ if(!isset($_POST['submit'])){ return; } // if(count($errors) === 0){ ?> <div class="alert alert-success"> <p>Thank you! your message has been sent.</p> </div> <?php }else{ ?> <div class="alert alert-block alert-error fade in"> <p>The following error(s) occurred:</p> <ul> <?php foreach ($errors as $error) { echo "<li>$error</li>"; } ?> </ul> </div> <?php } } /** * start form processing */ function start_form(){ global $errors, $name, $email, $subject, $message; $mail_msg = ''; // if user submitted the form if(isset($_POST['submit'])) { // validate form if(validate_form()) { $mail_msg .= 'From: ' . $name . "\n"; $mail_msg .= 'Email: ' . $email . "\n";; $mail_msg .= 'Message: ' . $message . "\n"; // send email to the MAIL_TO email address if(!@mail(MAIL_TO, $subject, $mail_msg)){ $errors[] = 'Error sending email'; } } } } // start form processing start_form(); ?> <!DOCTYPE html> <html> <head> <title>Contact Form</title> <link rel="stylesheet" href="css/bootstrap.min.css"> </head> <body> <div class="container"> <form action="contact.php" method="POST" class="form-horizontal"> <fieldset> <legend>PHP Contact Form Demo</legend> <?php display_message($errors); ?> <div class="control-group"> <label for="name" class="control-label">Name:</label> <div class="controls"> <input type="text" name="name" id="name" value="<?php display_value('name')?>" class="input-xlarge" placeholder="Name"/> </div> </div> <div class="control-group"> <label for="email" class="control-label">Email:</label> <div class="controls"> <input type="email" name="email" id="email" value="<?php display_value('email')?>" class="input-xlarge" placeholder="Email"/> </div> </div> <div class="control-group"> <label for="subject" class="control-label">Subject:</label> <div class="controls"> <input type="text" name="subject" id="subject" value="<?php display_value('subject')?>" class="input-xlarge" placeholder="Subject" /> </div> </div> <div class="control-group"> <label for="message" class="control-label">Message:</label> <div class="controls"> <textarea rows="7" cols="25" name="message" id="message" class="input-xlarge"><?php display_value('message')?></textarea> </div> </div> <div class="control-group"> <div class="controls"> <input type="submit" name="submit" value="Send" class="btn"> <input type="reset" name="reset" value="Reset" class="btn"> </div> </div> </fieldset> </form> </div> </body> </html> |
How the contact form works.
First, we define a list of global variables that we can use throughout the functions:
1 2 3 4 5 6 7 8 9 | <?php define('MAIL_TO','webmaster@example.com'); $errors = array(); $name = ''; $email = ''; $subject = ''; $message = ''; |
Second, in the validate_form()
function, we check all the form fields. If there is any error occurred, we log the error in the $errors
global array.
Third, the display_value()
function displays field value if it exists in the $_POST
array. We use the display_value()
function to retain the field values between subsequent requests in case there is an error occurred. This helps user save time fill out the form fields again.
Fourth, the display_message()
function displays error or success message based on the $errors
global array.
Fifth, the start_form()
function checks if a user submitted the form. If yes, it will validate the form by calling the validate_form()
function. If everything is fine, it will send out an email using the mail()
function.
You can download the script files in the download link below and play with the form in your system.
PHP Contact Form (1718 downloads)In this tutorial, we’ve shown you how to work with HTML form and how to process HTML form in PHP.