Verification: a143cc29221c9be0

Php arrays in html forms

Introduction to the form

POST data is submitted by a form and “posted” to the web server as form data. POST data is encoded the same way as GET data, but isn't typically visible to the user in standard browsers.

Most forms use the post method because it “hides” the form data away from the user and doesn't clutter up the URL in the address bar. Note that GET and POST methods are equally (in)secure.

As easily as a user can monkey with GET data in a URL, the same thing can be done with POST data. You should always assume that the user can submit whatever form and form data that they want to, and process the data accordingly. Don't trust user input, whether it's from GET or from POST!

Post data is accessed with the $_POST array in PHP.

echo("First name: " . $_POST['firstname'] . "
\\n"); echo("Last name: " . $_POST['lastname'] . "
\\n"); ?>
form action="myform5.php" method="post">
   p>First name: input type="text" name="firstname" />p>
   p>Last name: input type="text" name="firstname" />p>
   input type="submit" name="submit" value="Submit" />
form>

Using “isset”

You can use the “isset” function on any variable to determine if it has been set or not. You can use this function on the $_POST array to determine if the variable was posted or not. This is often applied to the submit button value, but can be applied to any variable.

For example:

if(isset($_POST['submit']) 
   {
      echo("First name: " . $_POST['firstname'] . "
\\n"); echo("Last name: " . $_POST['lastname'] . "
\\n"); } ?>
form action="myform5.php" method="post">
   p>First name: input type="text" name="firstname" />p>
   p>Last name: input type="text" name="firstname" />p>
   input type="submit" name="submit" value="Submit" />
form>

The above code will only display the submitted values if the submit button was clicked.

Can I use both GET and POST in the same page?

GET and POST occupy different spaces in the server's memory, so both can be accessed on the same page if you want. One use might be to display different messages on a form depending on what's in the query string.

http://mysite/myform5.php?lang=english

if(isset($_POST['submit']) {
      if($_GET['lang'] == "english") {
         echo("First name: " . $_POST['firstname'] . "
\\n"); echo("Last name: " . $_POST['lastname'] . "
\\n"); } else if($_GET['lang'] == "spanish") { echo("Nombre: " . $_POST['firstname'] . "
\\n"); echo("Apellido: " . $_POST['lastname'] . "
\\n"); } ?>
form method="post">
   p>First name: input type="text" name="firstname" />p>
   p>Last name: input type="text" name="firstname" />p>
   input type="submit" name="submit" value="Submit" />
form>

Instead of using GET and POST arrays, you can also use the $_REQUEST array, which will contain the combined contents of the data. If GET and POST variables have the same name, POST will take priority. It's recommended not to do this unless you really have to, because it can be confusing, and it's best to be clear about where an input is coming from.

One more thing to notice: the “action” on the form is now missing. Technically, this is not valid HTML. However, by not putting in an action, browsers will assume that the form is submitting to itself. This is important because it will also preserve the querystring when the form is submitted (the ?lang=english part). You can use server variables like $_SERVER['PHP_SELF'] and $_SERVER['QUERY_STRING'] to build an action value.

For more information, see Using PHP_SELF in the action field of a form

Register globals off?

If you are using a version of PHP earlier than 4.2.0, you should strongly consider setting register_globals to “off” in your .htaccess file (if you are using Apache server) for the exact same reasons as were mentioned in the previous tutorial on GET. If you have PHP 4.2.0 or later, don't worry about it.

Select box

Let's look at a new input: a “select” box, also known as a “drop-down” or “pull-down” box. A select box contains one or more “options”. Each option has a “value”, just like other inputs, and also a string of text between the option tags. This means when a user selects “Male”, the “formGender” value when accessed by PHP will be “M”.


p>
What is your Gender?
select name="formGender">
  option value="">Select...option>
  option value="M">Maleoption>
  option value="F">Femaleoption>
select>
p>


The selected value from this input was can be read with the standard $_POST array just like a text input and validated to make sure the user selected Male or Female.


if(isset($_POST['formSubmit']) )
{
  $varMovie = $_POST['formMovie'];
  $varName = $_POST['formName'];
  $varGender = $_POST['formGender'];
  $errorMessage = "";

  // - - - snip - - - 
}

?>


It's always a good idea to have a “blank” option as the first option in your select box. It forces the user to make a conscious selection from the box and avoids a situation where the user might skip over the box without meaning to. Of course, this requires validation.


if(!isset($_POST['formGender'])) 
{
  $errorMessage .= "
  • You forgot to select your Gender!
  • "
    ; } ?>

    ( For a generic, easy to use form validation script, see PHP Form Validation Script )

    Multi-select

    Suppose you want to present a select box that allows the user to select multiple options.

    Here is how to create such an input in HTML:

    
    label for='formCountries[]'>Select the countries that you have visited:label>br>
    select multiple="multiple" name="formCountries[]">
        option value="US">United Statesoption>
        option value="UK">United Kingdomoption>
        option value="France">Franceoption>
        option value="Mexico">Mexicooption>
        option value="Russia">Russiaoption>
        option value="Japan">Japanoption>
    select>
    
    
    

    Please note the similarity to a checkbox group. First, set multiple="multiple” as a property of the select box. Second, put [ ] at the end of the name. Finally, we don't really need a “blank” option in this select box, because we can simply check to make sure the user selected something or not. To select multiple values, use the shift or ctrl buttons when clicking.

    The PHP code to process this field is very similar to the checkbox code. $_POST['formCountries'] returns an array of the selected values.

    
    if(isset($_POST['formSubmit'])) 
    {
      $aCountries = $_POST['formCountries'];
      
      if(!isset($aCountries)) 
      {
        echo("

    You didn't select any countries!

    \n"); } else { $nCountries = count($aCountries); echo("

    You selected

    $nCountries countries: "); for($i=0; $i $nCountries; $i++) { echo($aCountries[$i] . " "); } echo(""); } } ?>

    As before, use “isset” is to make sure some values were selected.

    Using switch

    Now, let's change the multi-select box back to a standard single select box. We want to now perform different actions based on what selection the user makes. You could write a bunch of “if” statements, but that could get messy. Let's look at two ways: dynamic commands and the switch statement.

    
    if(isset($_POST['formSubmit'])) 
    {
      $varCountry = $_POST['formCountry'];
      $errorMessage = "";
      
      if(empty($varCountry)) 
      {
        $errorMessage = "
  • You forgot to select a country!
  • "
    ; } if($errorMessage != "") { echo("

    There was an error with your form:

    \n"); echo("
      "
    . $errorMessage . "\n"); } else { // note that both methods can't be demonstrated at the same time // comment out the method you don't want to demonstrate // method 1: switch $redir = "US.html"; switch($varCountry) { case "US": $redir = "US.html"; break; case "UK": $redir = "UK.html"; break; case "France": $redir = "France.html"; break; case "Mexico": $redir = "Mexico.html"; break; case "Russia": $redir = "Russia.html"; break; case "Japan": $redir = "Japan.html"; break; default: echo("Error!"); exit(); break; } echo " redirecting to: $redir "; // header("Location: $redir"); // end method 1 // method 2: dynamic redirect //header("Location: " . $varCountry . ".html"); // end method 2 exit(); } } ?>

    These two approaches have their pro's and con's. The switch method is basically a concise method of writing a bunch of “if” statements. Each case matches the variable passed the switch and performs all actions after that case up until a break statement. In this case, each case is redirecting to the corresponding page to the selected country. If the selected country is not found in one of the cases, the “default” case is assumed, and “Error!” is displayed.

    The second method is just passing the selected value to the header function to redirect to the correct page.

    The first method requires writing more code, but is more secure because it ensures the form only redirects to 6 pre-programmed cases, or else displays an error message and ends execution.

    The second method is much more concise, but less secure because a malicious user could monkey around with the form and submit whatever value he wants. If using method 2, it's a good idea to validate the selected country first, to make sure it won't result in a redirect to a malicious page.