POST in PHP

When sending the formwe introduced above with the method attribute set to post, the data is accessible using the $_POST superglobal array. Just like $_GET, $_POST contains one array element named after each input name.

<?php
if($_POST['login']){
   if($_POST['user'] == "admin" && $_POST['pass'] == "secretpassword"){
      // Handle login
   }
}
?>

In this example, we first check that the submit button was clicked, then we validate that the user input is correct.

Also, similarly to GET input, we can again use array notation:

<form method="post">
   <p>Please choose all languages you currently know or would like to learn in the next 12 months.</p>
   <p>
      <label>
      <input type="checkbox" name="languages[]" value="PHP" />
      PHP</label>
     <label>
     <input type="checkbox" name="languages[]" value="Perl" />
     Perl</label>
     <label>
     <input type="checkbox" name="languages[]" value="Ruby" />
     Ruby</label>
     <br />
     <input type="submit" value="Send" name="poll" />
  </p>
</form>

The formabove has three checkboxes, all named languages[]; these will all be added individually to an array called languages in the $_POST superglobal array—just like when you use an empty key (e.g. $array[] = “foo”) to append a new element to an existing array in PHP. Once inside your script, you will be able to access these values as follows:

<?php
foreach($_POST['languages'] as $language){
   switch($language) {
      case 'PHP' :
      echo "PHP? Awesome! <br />";
   break;
   case 'Perl' :
      echo "Perl? Ew. Just Ew. <br />";
   break;
   case 'Ruby' :
       echo "Ruby? Can you say... 'bandwagon?' <br />";
   break;
   default:
      echo "Unknown language!";
   }
}
?>

Next Topic | Previous Topic

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *