Skip Navigation Links
EZWEB
PHPExpand PHP

PHP Forms

A very powerful feature of PHP is the way it handles HTML forms!

PHP Form Handling

Any form element in an HTML page will automatically be available to your PHP scripts.

In Class Lab:
  •   Create the following HTML page, name it form1.html
1

<HTML><HEAD><TITLE>Form Example</TITLE>

2

</HEAD><BODY>

3

<form action="welcome.php" method="POST"> 

4

   Enter your name:<input type="text" name="name" /> 

5

   Enter your age:<input type="text" name="age" /> 

6

   <input type="submit" />

7

</form> 

8

</BODY></HTML>

  • When the user fills in this form and hits the submit button, the "welcome.php" file is called.

‚  Create the following PHP page, name it welcome.php

1

<HTML><HEAD><TITLE>Form Example Part 2</TITLE>

2

</HEAD><BODY>

3

Welcome <? echo $_POST["name"]; ?>.<br />

4

You are <? echo $_POST["age"]; ?> years old!

5

</BODY></HTML>

A sample output of the above script may be:

Welcome Steve.
You are 21 years old!

Here is how it works:

  • The $_POST["name"] and $_POST["age"] variables are automatically set for you by PHP. The $_POST contains all POST data.
  • Note: If the method attribute of the form is GET, then the form information will be set in $_GET instead of $_POST.

HTML forms

  • When creating your HTML forms, three things you will need to pay particular attention to are:
  • field names
  • method
  • action


field names

  • Every form field, whether it’s a text box, radio button, select, even submit, must have a name.
  • These names do not contain spaces. Nor do they contain anything other than letters, numbers, or underscores.
  • Name them something meaningful, because the names you use in the forms are going to become variables of the same name.


method

  • Use GET or POST
    • GET sends the submitted data as a series of name=value pairs appended to the url.
      • A benefit of GET is that it can be bookmarked by the browser.
      • Drawbacks are GET is limited to how much data can be sent, and it is less secure because data is visible in the url
    • POST is more secure, the amount of data than can be sent is much greater, but it cannot be bookmarked by a browser


action

  • action indicates the page to which data will be sent


PHP Form Handling

accessing variables

Look at the following form:

<form method=”get” action=”test.php”>
  First Name:<input type=”text” name=”first_name”><br />
  Last Name:<input type=”text” name=”last_name”><br />
  <input type=”submit” name=”submit”>
</form>

  • We can access each of the form fields as a PHP variable, by using the name we have given that field. There are 3 ways to access the form data through variables:
  • $first_name   and  $last_name – variable names are the same as the names in the form fields
  • For this way to work, however, register_globals must be set to ON in the php.ini file.
  • This is very convenient, but it opens your script up to errors and security risks.
  • By allowing form variables to become global variables, there is no separation between variables you have created, and untrusted variables created by a user.
  • superglobals:    $_GET   or   $_POST     – which one you use depends on which method you use in your form.
  • Beginning with PHP version 4.1, PHP gave us access to superglobals, meaning they are available in any part of the script.
  • To access the form value, use the field name with the superglobal as follows:

    $_GET[‘first_name’];
  • They can also easily be set to regular variables:

    $first_name = $_GET[‘first_name’];
  • Using superglobals insures that the only outside variables allowed in your script are ones submitted through the form.
  • Besides $_GET or $_POST, you can also use $REQUEST, which contains all of the variables and values transmitted through the GET and POST methods, and cookies.
  • Superglobals are associative arrays. We will be looking at arrays soon.
  • $HTTP_GET_VARS     or     $HTTP_POST_VARS
  • Before superglobals were introduced in version 4, earlier versions of PHP used these arrays to access the form data.
  • These arrays can still be used with the current version of PHP, but they have been deprecated, meaning they may not be available in future version.

    $HTTP_GET_VARS[‘first_name’];


self-submission

  • Rather than creating a separate document to handle form input, which you can do if you want, you can write your PHP document to contain both the HTML that displays the form, and the PHP that handles the form input.

 

  • If you were going to create a separate document, you would reference that document in the action of the HTML form.

<form method=”post” action=”newScript.php”>

  • Instead, we can set the action of the form to submit to itself, simply by referencing itself in the action. If we have a document named test.php, we can use that name in the action:

<form method=”get” action=”test.php”>
First Name: <input type=”test” name=”first_name”><br />
Last Name: <input type=”test” name=”last_name”> <br />
<input type=”submit” name=”submit”>
</form>

  • Using any of the three ways detailed above, we can access the values of the two fields.
  • The function isset( ), when passed a variable, will return TRUE if the variable is set to some value, FALSE if the variable is NULL.
  • We will set up our document into two parts.
    • We will print one or the other of those parts depending upon whether or not the form has been submitted.
    • We named the Submit button, and the other two form fields.
    • Before the user clicks the Submit button, those fields have a value of NULL.
    • Once submitted, they have values:
      • information entered by user
      • empty string
      • TRUE
  • When the form has been submitted, $_GET[‘submit’] is set to TRUE. We test to see if it has been set using the isset( ) function: 

1

<?

2

   if( isset(  $_GET[‘submit’] ) ){

3

      $first_name = $_GET[‘first_name’];

4

      $last_name = $_GET[‘last_name’];

5

      echo “Your name is $first_name $last_name”;

6

   }

7

   else{

8

?>

9

<form method=”get” action=”test.php”>

10

First Name: <input type=”text” name=”first_name”><br />

11

Last Name: <input type=”text” name=”last_name”> <br />

12

<input type=”submit” name=”submit”>

13

</form>

14

<?

15

   }

16

?>

 

  • This script will handle the form input when it has been submitted, but display the form every time the page is initially loaded.
  • In this example, when you set the action in your form, you want it to call itself, so you use the name of the current script.
  • A more efficient way of doing so is to use the $PHP_SELF variable, accessed through the superglobal $_SERVER. This variable will always contain the value of the current script’s name.

Change line 9 to:

<form method=”get” action=
”<?php echo $_SERVER[‘PHP_SELF’]; ?>”>

  
  • Notice that to use this variable in the form, we have to place it between the <?   ?> tagset.
  • If you happen to change the name of this php document, you will not have to go through and manually change the action. It changes automatically.

Validating form data

  • In terms of error management and security, you should always validate data entered by a user.
    • Some users can make simple mistakes and end up skewing the results they expect, while other users may maliciously try to corrupt your script.
  • We may want to check that certain fields in the form have been filled out.
  • We can continue using isset( ) to test whether or not a variable holds a value.

<?

if( isset($_GET[‘first_name’]) ) {

   $first_name=$GET[‘first_name’];

   echo “Hello, $first_name.”;

}

else{

   echo “You forgot to enter your first name.”;

}

?>


strlen

  • On problem with isset( ) is that empty strings test as TRUE. So to test for empty strings, we can use another function called strlen( ).
  • This function returns the length of a string.
    • EG, if a user types in “Steve” in the first_name field of the form, strlen( ) would return 7.

<?

$first_name=$_POST[‘first_name’];

if( strlen( $first_name ) > 0 ){

echo “Hello, $first_name.”;

}

else{

echo “You forgot to enter your first name.”;

}

?>


Trim

  • One other useful function for validating form input is trim( ).
  • This function removes any white spaces from both ends of a value.

$first_name = trim( $_GET[‘first_name’] );

  • trim( ) will not allow the user to enter a name containing nothing but spaces, as well as remove extra spaces from the beginning and end of the data.
    • It is a good idea to trim all form input.
  • Later on we will look at Regular Expressions, which allow us to validate forms to more specific standards.
    • EG, we can restrict the user to entering a particular format for a SS#, telephone number, or email address.


Summary: The purpose of validation is to

  • make sure the script has all the information it needs to do what it was designed to do
  • ensure the data is of the right type

We can do this by:

  • using the isset( ) function to make sure the variable has been set
  • using the strlen( ) function to make sure the length of a string is greater than 0
  • using trim( ) to remove white space


Validate Radio Buttons

  • We can access and validate radio buttons using the same techniques:

<form method=”post” action="<?php echo     
       $_SERVER['PHP_SELF'];?>">

Male:<input type=”radio” name=”gender”  value=”male” />

Female:<input type=”radio” name=”gender”  value=”female” />

<input type = submit>

</form>

if( isset( $_POST[‘gender’] ) ){

   if( $_POST[‘gender’] == “male” || $_POST[‘gender’] == “female” ){

echo “You claim to be a $_POST[‘gender’];  }

else { echo “Please enter a correct value.”;  }

else { echo “Please enter a correct value.”;  }

}

  • We will come back to checkboxes later on, after we look at arrays.

Sending values to a script manually

  • So far, all of the data received by these scripts have been entered by the user through a form.
  • There are two other ways to pass variables and values to a PHP script.


The first way is to use the HTML form’s hidden input type.

     <input type=”hidden” name=”author” value=”Steve” />
  <input type=”hidden” name=”subject” value=”PHP” />
  <input type=”hidden” name=”toAddress” value=”smorosko@StarkState.edu” />
    

  • These will send the variables defined by ‘name’ with their corresponding values to the script.
    • Access them as you would any other form field, through $_GET, $_POST, or $_REQUEST.
    • Hidden form elements do not display in the browser, but they are visible if you view the source code.
    • So don’t put anything in a hidden field that needs to be kept secure.


The second way is to append a value to the url.

<form method=”post” action=”test.php?author=Steve&subject=PHP">

  • You can also append name=value pairs to anchor tags, which create a link to another (or the same) page, while sending along the variables.

 

<a href=”test.php?author=Steve”>Click Here for author</a>
<a href=”test.php?subject=PHP”>Click Here for Subject</a>

    • To access these variables use the $_GET or  $_REQUEST superglobal.

    End PHP Forms





Free Tutorials and Training