PHP Form Tutorial with Example
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts.
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:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Contact Form</title>
</head>
<body>
<h2>Contact Us</h2>
<p>Please fill in this form and send us.</p>
<form action=”process-form.php” method=”post”>
<p>Your Name: <input type=”text” name=”yourname” /><br />
E-mail: <input type=”text” name=”email” /></p>
<p>Do you like this website?
<input type=”radio” name=”likeit” value=”Yes” checked=”checked” /> Yes
<input type=”radio” name=”likeit” value=”No” /> No
<input type=”radio” name=”likeit” value=”Not sure” /> Not sure</p>
<p>Your comments:<br />
<textarea name=”comments” rows=”10″ cols=”40″></textarea></p>
<p><input type=”submit” value=”Send it!”></p>
</form>
</body>
</html>
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 “process-form.php”. The form data is sent with the HTTP POST method.
To access the value of a particular form field, you can use the superglobal variables $_POST, $_GET.
To display the submitted data you could simply echo all the variables.
The “process-form.php” looks like this:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Contact Form</title>
</head>
<body>
Your name is: <?php echo $_POST[‘yourname’]; ?><br />
Your e-mail: <?php echo $_POST[’email’]; ?><br />
<br />
Do you like this website? <?php echo $_POST[‘likeit’]; ?><br />
<br />
Comments:<br />
<?php echo $_POST[‘comments’]; ?>
</body>
</html>
The output could be something like this:
Your name is: Web Master
Your email: webmaster@cmscomputer.com
Do you like this website? Yes
Comments:
This is my comment…
The PHP code above is quite simple. Since the form data is sent through the post method, you can retrieve the value of a particular form field by passing its name to the $_POST superglobal array, and displays each field value using echo() statement.
In real world you cannot trust the user inputs; you must implement some sort of validation to filter the user inputs before using them.
In real world you cannot trust the user inputs; you must implement some sort of validation to filter the user inputs before using them. You will learn ‘Form Handling and Validations’ in our next post.