html form guide
  about

PHP form tutorial

This PHP form tutorial will give you an introduction to creating and processing user input via a web form. This tutorial assumes that you are familiar with at least very basic PHP and HTML.

Creating the HTML code for the form

A form is a set of defined inputs that a user will fill out and then submit for processing. 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">
  <p>
    What is your favorite movie?
    <input type="text" name="formMovie" maxlength="50" />
  </p>
  <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">
  <p>
    What is your favorite movie?
    <input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>" />
  </p>
  <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">
  <p>
    What is your favorite movie?
    <input type="text" name="formMovie" maxlength="50" value="<?=$varMovie;?>" />
  </p>
  <p>
    What is your name?
    <input type="text" name="formName" maxlength="50" value="<?=$varName;?>" />
  </p>        
  <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!

Validations can be done with simple PHP if statements.

  <?php
    if($_POST['formSubmit'] == "Submit") {
      $varMovie = $_POST['formMovie'];
      $varName = $_POST['formName'];
      $errorMessage = "";
     
      if($varMovie == "") {
        $errorMessage .= "<li>You forgot to enter a movie!</li>";
      }
      if($varName == "") {
        $errorMessage .= "<li>You forgot to enter a name!</li>";
      }

      if($errorMessage != "") {
        echo("<p>There was an error with your form:</p>\n");
        echo("<ul>" . $errorMessage . "</ul>\n");
      } else {
        echo("<p>Your form was valid.</p>\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 with your form:</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 functions 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.

That's all for this PHP form tutorial. Download the sample code for this PHP form tutorial.



  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb


Related pages

 
  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb
Email forms
  How to get email from html form submission

Email form using 'mailto'

Form to email using PHP

Email form with file attachment in PHP

Form mail scripts
  Form mail script selection guide

Perl based form mail

Contact Forms
  PHP based email contact form

Secure your HTML contact form using captcha
PHP Form
  PHP form validation script

PHP form tutorial: first steps

PHP form processing

PHP form 'GET'

PHP form 'POST'

Handling checkbox in PHP form processor

Handling select box in a PHP form

Using PHP_SELF in the action field of a form

How to submit a form using PHP

Creating a registration form using PHP

Making a login form using PHP

Creating a multi-page order form using PHP

Passing PHP form variables from one page to other

  Copyright © 2008 html-form-guide.com . All rights reserved.