This tutorial takes you step by step through web form processing using PHP. You will learn how to collect input from a web form, validate and save it. This tutorial assumes that you are familiar with at least very basic PHP and HTML.
Creating the HTML code for the form
In HTML, a form is begins and ends with a <form>
tag. The form tag surrounds all the inputs as well as gives instructions about how and where to submit the form. As an example, let’s start creating a form in a file named myform.php.
<form action="myform.php" method="post">
<!-- form fields go here -->
</form>
The “action” specifies what page to submit the form to. Many times, the action will be the same page as the form. The “method” indicates how the form is submitted. There are two methods: “get” and “post”. Most of the time, forms will use the “post” method.( more on get and post )
Now let’s add some inputs to the form. Let’s add a text field that asks for your favorite movie and a submit button to submit the form.
<form action="myform.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50">
<input type="submit" name="formSubmit" value="Submit">
</form>
Getting the form data
The input of type “text” is just a single line field to type in some text. We give it a name of “formMovie” which we will use later during processing. Maxlength just indicates that the browser shouldn’t let the user type more than 50 characters into the text box.
Congratulations! You now have a form that will submit. It doesn’t do much yet, and whatever you type in “goes away” when you submit.
Let’s add some PHP to process this form:
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formMovie'];
}
?>
<form action="myform.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50">
<input type="submit" name="formSubmit" value="Submit">
</form>
First, remember that this form “submits to itself”, meaning that the form variables will be sent to this page, and the page will load again from the top.
So, the first thing we should do is to check and see if a form was submitted or not. To do that, let’s look at the value of the “formSubmit” button. If its value is “Submit”, then we know a form has been submitted. If not, then the user is probably visiting this page for the first time. To access this value, use the $_POST['inputname']
array, where “inputname” is the name in the HTML element. We use $_POST
since that is the form’s method. If it was “get” instead, we’d use $_GET[]
.
Second, after we’ve determined that the form was submitted, let’s get the text that the user typed. Again, we use the $_POST
array to get the value and put it into the $varMovie variable.
Finally, we’ve added a “value” field to the formMovie input box, and put some PHP code in there to set the value equal to whatever the user entered. This means that if you submit the form, the text you typed in will still appear in that text box. This is very important when there are multiple inputs, as we will see later with validation.
So now we have a form that still doesn’t do much. Let’s add another input before going into validation.
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formMovie'];
$varName = $_POST['formName'];
}
?>
<form action="myform.php" method="post">
Which is your favorite movie?
<input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>">
What is your name?
<input type="text" name="formName" maxlength="50" value="<?=$varName;?>">
<input type="submit" name="formSubmit" value="Submit">
</form>
Validating the input
Suppose we have a user who forgot to enter one of the fields? We need to validate the form to make sure it’s complete and filled out with valid information. Note that you can use JavaScript for this, but that JavaScript can be easily turned off: always validate in the server-side script, no matter what! ( The JavaScript form validation script can help you add JavaScript validations quickly. )
Validations can be done with simple PHP if statements. Once you need to add more types of validations quickly, checkout the PHP form validation script.
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formMovie']))
{
$errorMessage .= "<li>You forgot to enter a movie!</li>";
}
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter a name!</li>";
}
$varMovie = $_POST['formMovie'];
$varName = $_POST['formName'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
In this example, the code makes some very basic checks to see that the user typed in something –anything– into both of the input fields. If the user didn’t, each check will add another bullet point to the error message. Finally, when it’s done making validations, it will check to see if there is an error message. If there is, it displays it. If there are no errors, it displays a success message.
Note that if there are errors or not, any information that was entered into the form inputs is preserved. This way a user doesn’t have to fill out the entire form again if they forgot just one thing.
Saving the data to a file
Finally, let’s take this data and write it into a text file.
<?php
if($errorMessage != "")
{
echo("<p>There was an error:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varName . ", " . $varMovie . "\n");
fclose($fs);
header("Location: thankyou.html");
exit;
}
?>
The fopen function opens up a CSV file in “a” (append) mode. This means that if mydata.csv already exists, it will point to the end of the file. If not, it will create the file and point at the start. Next, the _fwrite_
function takes the file pointer created by _fopen_
and writes the name and movie separated by a comma and ending with a carriage return. Finally, the pointer to the file is closed. Now, every time a valid form is submitted, a name and movie will be written to mydata.csv.
Because of the way form data is “posted” to web server, hitting the refresh button on the browser will cause the same thing to happen every time it is clicked after the form is submitted. Because of this, generally you should redirect to another page to avoid refresh button problems. Create a “thankyou.html” HTML page that says “thank you for submitting your movie” or whatever.
Download Sample Code
Download the sample code for this PHP form tutorial: php-form-tutorial.zip.
For more advanced topics, see Advanced PHP form processing
See Also
- PHP Form Validation Tutorial
- How to make a form
- Dreamweaver Email Form Tutorial
- Creating a registration form using PHP
- Making a login form using PHP
- Handling checkbox in a PHP form processor
- Handling select box (drop-down list) in a PHP form
- PHP Form Validation Script
- PHP form processing
- Using PHP_SELF in the action field of a form