Programming in PHP

4.28 (118)

Handling Form Data

Handling form data is one area which is quite unique to PHP. Many other web languages handle form input data in different ways, and real programs don't take input from web forms. By a form, I mean a HTML based form with input fields. If you send the contents of the form to a PHP script, you are able to manipulate the data that has been submitted by the form.

There are two methods available for PHP to handle form data. The first is have a HTML page with a form, which upon submitting, sends the data from the form to a PHP file. The second option is to use a PHP file to write the form out, and the same PHP file to handle the input. As this is the most common method, I will be showing you how to do this.

PHP uses special variables called superglobal variables. There are several of these variables, but the main ones we'll be looking at are $_POST, $_GET, $_REQUEST and $_SERVER. Each of these variables' data type is an array as it holds lots of separate pieces of information.

When designing a HTML form, you must enter the method in which the form is submitted. You get to choose between get and post. When PHP receives this data, it will place it into the respective superglobal variable. The $_REQUEST variable is a combination of both $_GET and $_POST. This means that it holds all of the data of the other two variables.

When you choose the get method of submitting, this means that all the data submitted will be passed through the URL making it visible in the address bar. This can look very clumsy and is generally not recommended. The post method sends all the data transparently so this is the preferred method. This means we will be dealing exclusively with the $_POST superglobal, however the other two are accessed in the same way.

Form
<html>
<body>
<form name="person" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  Name:&nbsp; <input type="text" name="name"><br>
  Age:&nbsp; <input type="text" name="age"><br>
  <input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>


You should immediately notice that the method of the form is set to post to hide our data from being passed through the URL. Also notice the action of our form is set to <?php echo $_SERVER['PHP_SELF']; ?>. The action of a form is where the data is being submitted to. We use PHP to find out the address of the script we are currently running using the $_SERVER superglobal. This superglobal is an array like the others and holds a lot of data about PHP and the server you are running on. By specifying the index of the array to be PHP_SELF it will return the address of the current script.

Our form has only two input fields. One for name and one for age. It also has a submit button, thus meaning that we will have three useful form input values to our PHP script.

Full Script
<html>
<body>

<?php
if (isset($_POST['submit'])) {
    echo 
'Your name is ' $_POST['name'] . ' and you are ' $_POST['age'] . ' years old!';
} else {
?>

<form name="person" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  Name:&nbsp; <input type="text" name="name"><br>
  Age:&nbsp; <input type="text" name="age"><br>
  <input type="submit" name="submit" value="Submit">
</form>

<?php
}
?>

</body>
</html>


This full script has the exact same form before however this time it has more PHP embedded inside of it (remember PHP is a HTML embedded scripting language?). The first section of PHP makes use of a new function – isset(). This function returns true or false depending on if the variable name you pass to it exists or not. We are passing the variable $_POST['submit'] which means we are checking if the submit button was pressed, which would indicate there is form data.

Our script checks if the form has been submitted and if so executes some PHP code, otherwise it will output the HTML form. Notice that if we end the PHP code using <?php then anything that follows will output as HTML. If we start more PHP code, then PHP continues from where it left off. This explains the final bit of PHP which contains only a curly brace, as PHP was expecting a curly brace before the end of the file from the if statement.

If the form has been submitted, our script wants to output a line of text using the inputs from the form. As before, we simply use the $_POST superglobal and reference the index name being the name of the input field, to get our data.

Select Lists, Radio Buttons and Multiple Text Fields


Often you will want to give the user an option of selecting either one of many values, or many values of the same type. HTML radio buttons give the user the option to choose one out of a list, as do select lists. Select lists and multiple text fields also give the user the option to enter many values for the same input. This should sound very similar to arrays, as they hold many pieces of data of the same type.

If we create a HTML form, where the input fields are specified to be arrays, then we can take many values in. Below is a simple script using all three input types:

Final Example
<html>
<body>

<?php
if (isset($_POST['submit'])) {
    
$numbers $_POST['number'];
    
$total $numbers[0] / $numbers[1];
    
$friends $_POST['friends'];

    
    echo 
'Total: ' $total '<br>';
    
    if (
$_POST['rich'] == true) {
        echo 
'You are rich.<br>';
    }
    echo 
'You have ' count($friends) . ' friends:<br>';
    
    foreach (
$friends as $value) {
        echo 
$value '<br>';
    }
    
} else {
?>

<form name="person" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  Number 1: <input name="number[]" type="text" id="number[]"><br>
  Number 2: <input name="number[]" type="text" id="number[]"><br><br>
  Rich: <input name="rich" type="radio" value="1">Yes 
    <input name="rich" type="radio" value="0">No<br><br>
  Friends: 
    <select name="friends[]" size="3" multiple id="friends[]">
      <option value="John">John</option>
      <option value="James">James</option>
      <option value="Bill">Bill</option>
      <option value="Jane">Jane</option>
  </select><br>
    <input type="submit" name="submit" value="Submit"></p>
</form>

<?php
}
?>

</body>
</html>


In our HTML forms, where we want to be able to accept multiple values, we define the name of the input type to be the name followed by [] to indicate it will be an array value. In this script, the select list and the text boxes allow multiple values. Therefore they are arrays in the superglobal $_POST. We have then defined separate arrays to hold this data to make the code more readable. We can then manipulate these new array variables to produce an output.

One last thing to note about forms was mentioned slightly before, and that is that we can output text / HTML anywhere on the page using PHP. Because of this, we can output HTML within the value attribute of form input elements. This allows us to produce dynamic forms:

Dynamic Form
<html>
<body>
<?php
if (isset($_POST['submit'])) {
    echo 
'Your name is ' $_POST['name'] . ' and you comment was:<br>' $_POST['comment'];    
} else {
?>

<form name="person" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  Name: <input name="name" type="text" id="name"><br>
  Comment: <br>
  <textarea name="comment" cols="50" rows="5" id="comment"><?php echo 'Please enter your comment here!'?></textarea>
  <br><br><input type="submit" name="submit" value="Submit"></p>
</form>

<?php
}
?>
</body>
</html>


That's all there is to this article about programming in PHP. We have only touched the basics, however, it should have provided you a clear basis for furthering your PHP knowledge. It should also enable you to be able to switch over to almost any other scripting / programming language as the underlying concepts in most programming languages are the same.

Congratulations and many happy hours coding PHP!
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 10 of 10

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter