PHP Form Submission and Superglobal Variable

12/9/2008

 

The following HTML

 

<form action="handle_form.php" method="post">

<p>Your name: <input type="text" name="myname" size="20" maxlength="40" /></p>

<p>Your password: <input type="password" name="mypassword" size="40" maxlength="60" /></p>

<input type="submit" name="submit" value="Log in" /></div>

</form>

 

establishes a text box, a password box, and a submit button.

Your name:

Your password:

 

The caption of the text box is “Your name”;

The name of this text box is “myname”.

 

The caption of the password box is “Your password”;

The name of this text box is “mypassword”.

 The submit button does not have a caption;

The name of this submit button is “submit”; 

The text shown on this button is “Log in”, as its value.

 

After the “Log in” button is clicked, the content typed in the text box “myname” (“John Smith” in this case) is assigned in a superglobal array variable $_POST[‘myname’] (Please note that in the HTML form code, “post” is used for method = ) .  It is very important to remember that this array is an associative array and tts key is ‘myname’, - the name of that text box.

 

Similarly, after the “Log in” button is clicked, the content typed in the password box “mypassword” (“******” in this case) is assigned in the superglobal array variable $_POST[‘mypassword’].  It is very important to remember that this array is an associative array and its key is ‘myname’, - the name of that text box.

 

That is,

 

$_POST [ ‘ myname’ ]   ¬   “John Smith”    ,  and

$_POST [ ‘ mypassowrd ’ ]  ¬  “******”     .

 

 

These contents can be also accessed by another superglobal array variable $_REQUEST.  That is,

 

$_REQUEST [ ‘ myname’ ]     ¬     “John Smith”    ,  and

$_REQUEST [ ‘ mypassowrd ’ ]  ¬  “******”     .

 

Then, contents in the array can be assigned to regular variables, for example,

 

<?php

 

if (!empty($_POST [ ‘myname’ ] ) )

{

      $name = $_POST [ ‘ myname’ ];                                      // $name ¬ “John Smith”

}

else

{

      echo '<p class="error">You forgot to enter your name.</p>;

}

 

if (!empty($_POST [ ‘mypassword’ ] ) )

{

      $password = $_POST [ ‘mypassword’ ];                          // $password ¬ “******”

}

else

{

      echo '<p class="error">You forgot to enter your name.</p>;

}

 

?>

 

 Alternatively,   $_REQUEST [  ] can be used in the place of $_POST [  ].