You are here: Home » All Posts » PHP Form » PHP form tutorial

PHP form tutorial

in PHP Form

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.

Note: You can make web forms quickly with Simfatic Forms. Simfatic Forms helps you to make complete, feature rich forms and get it online quickly. Read more here.

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 fwritefunction 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

Be Sociable, Share!
bunmi April 5, 2011 at 10:02 am

thanks nice tut.

Ngurah September 5, 2011 at 7:03 am

Nice Tutorial….Thanks…

Eufemia Voelkel November 25, 2011 at 8:29 am

Thanks for all your efforts that you have put in this. very interesting information. “Illegitimacy is something we should talk about in terms of not having it.” by Dan Quayle.

Michele December 27, 2011 at 4:05 pm

Hi there,

I’ve a problem with my register form.
A user can register more then once with the same data.
I save the data to a text file not to a database. How can I show the message saying username is already in use?

Hope you can help?

Thanks in advance.

YoonMi December 29, 2011 at 9:04 pm

Is there a way to check to see if the data is already entered with let’s say the email so they can not enter the info again?

Thanks in advance,
YoonMi

Ben January 2, 2012 at 5:10 pm

When I use this code, the input field is already filled with text, (i.e. “”). Is there any way of preventing this text from appearing?

wong January 3, 2012 at 9:22 am

Hi
I like this simple form tutorial.
Im new to this.

I’ve copied above sample and paste to a notepad (saved as php)

Which is your favorite movie?

after saved above command i open the file on firefox.
nothing happen when i click submit..

Please help if im missing anything here.. do i need any plug in for php or software to create php file rather than using notepad?

thanks

Prasanth January 5, 2012 at 5:27 pm

Firefox doesn’t understand PHP. You need to upload it to a webserver with PHP support.

Matt Miller January 6, 2012 at 4:01 am

PHP is a server-side language so you need to be connected to your localhost to do it. You can download XAMPP here to get started:
http://www.apachefriends.org/en/xampp.html

There are some great tutorials for PHP beginners at thenewboston.org:
http://thenewboston.org/list.php?cat=11

Also, a simple notepad code editor is TextWrangler. Works like a charm.

The first four or five tutorials should give you a good start. Hope this helps!

raj January 6, 2012 at 11:39 am

PHP files cannot be viewed directly by a browser. if you want to test your PHP files on your local computer, i suggest you to download and install WAMP server software (it’s free) on your system.

hobbit January 21, 2012 at 5:24 pm

I get notice errors throughout this, e.g.

Undefined index: formSubmit in form.php on line 3

Not sure what I’m doing wrong or if this is intentional

T February 15, 2012 at 8:59 pm

My information isn’t being placed into mydata.csv on my server, help?

Beaurocks16 March 9, 2012 at 9:14 pm

Hi,
I used the code on the template, but when I use Google Chrome to open it(i have the software) it just shows the code of notes.php. Any help?

Aldrin Paraso March 13, 2012 at 5:58 am

Thank you for this valuable information. It will be helpful in the creation of my project. God Bless you, kind sir! :)

Ashvini Tiwari March 22, 2012 at 5:56 am

Thank’s nice tuitorials

joe March 23, 2012 at 6:27 pm

great tutorial! simple and effective, worked like a charm…any way to check for already existing data in the csv file? thanks again

Comments on this entry are closed.

Previous post:

Next post: