Friday, May 18, 2012

Creating HTML Forms and Receiving HTTP POST Data

In my previous post, I showed you how to use HTTP GET to transfer/receive data through a page's URL (as well as how to intermingle PHP code with HTML code). What if you want the user to submit data through an HTML form to your website? That's where HTTP POST comes in.

There are two parts to making standard HTML forms: the HTML form code itself (including graphics, placement, text, and logic/data) and the PHP script that will retrieve the form data. We'll start with a brief overview of how you might want to make the form.

Here is a demonstration that I made with everything I'm going to cover in this tutorial - experiment with it a little (including pressing the submit button at the bottom):

http://thecodingwebsite.com/tutorials/demos/forms/index.php

Here is the code for the first page, "index.php":

<html>

<head>

</head>

<body>

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

<table cols="2">
<tr><td align="right">Textbox:</td><td align="left"><input name="textbox" type="text" value="Default Text"/></td></tr>
<tr><td align="right">Textarea:</td><td align="left"><textarea name="textarea" rows="10" cols="40">Default Text</textarea></td></tr>
<tr><td align="right">Dropdown (select):</td><td align="left"><select name="dropdown">
<option value="1">1</option>
<option value="A">A</option>
<option value="cookie">cookie</option>
</select></td></tr>

<tr><td align="right">Submit button:</td><td align="left"><input type="submit" value="Button Title"/></td></tr>
</table>

</form>

</body>

</html>

All this page is made of is an HTML form with an HTML table used to align it. The left column is composed of text explaining what the right column is - there's a text box, a text area (a multi-lined text box), a drop down (aka a select element), and a submit button.

Notice that there are 2 important properties you need to set in the form itself: the method is "POST" and the action is "receive.php" (the name of the page that will receive the form data). I used a table in this case purely for simplicity; there are other ways of aligning form content to your liking, but a table was the simplest way to align things without requiring an hour of explanation. Personally, I would vouch for using the simplest method of creating a form unless you need some other functionality or the table messes up your CSS styling or something. Also, take note that you can place a table and its rows and columns within a form.

A lot of the table alignment is pretty self explanatory (if you need more information, try going here and here), so I'll move on to explaining the form's content briefly. Basically, you should use an "input" element whenever you want a single-line text box or a button. Inputs can also be used for other types of data entry (as depicted in the "type" attribute found here) as well, including:
  • button
  • checkbox
  • file
  • hidden (used for passing hidden data to the receiving page that the user can only see by looking at the source code of the form's page)
  • image
  • password
  • radio
  • reset
  • submit
  • text
I also used a "textarea" element for the multi-lined text box and a "select" element (with multiple child "option" elements) for the drop down box.

The only other important thing (and possibly the most important thing) to note about these elements is that each of them use the "name" property. This sets the string you will use in the receiving page to retrieve the POST data. The select element used the name property once, but its child option elements did not use it because they all have the same purpose/use: the drop down box.



Just so you don't get lost, we're passing 3 pieces of data to the receiving page: "textbox", "textarea", and "dropdown" (as depicted by the "name" property in the input, textarea, and select elements). Let's take a look at the code for "receive.php" now:

<html>

<head>

</head>

<body>

<?php

function receivePOST($variableName)
{
 return htmlspecialchars($_POST[$variableName]);
}

$textBox = receivePOST("textbox");
$textArea = receivePOST("textarea");
$dropDown = receivePOST("dropdown");

if (!strlen($textBox) || !strlen($textArea) || !strlen($dropDown))
{
 echo "ERROR: Not all expected values have been entered/submitted!";
}
else
{
 echo "Received submitted data!<br/><br/>";
 echo "Text box contents: $textBox<br/><br/>";
 echo "Text area contents: $textArea<br/><br/>";
 echo "Drop down contents: $dropDown<br/><br/>";
}

?>

</body>

</html>

Assuming you've already read and understood the code in the previous tutorial regarding HTTP GET, this code should be relatively simple to grasp with only a little explanation. Basically, the only thing that really changed in the process of retrieving data is that I used "$_POST[]" instead of "$_GET[]".

I did create a new function here called "receivePOST". If you're not familiar with functions, a function is basically a section of code that you intend to call multiple times (perhaps with minor changes in between each call). It expects a variable to be passed in every time it's called - we know this because of the code in the very first line of the function:

function receivePOST($variableName)

In between the parentheses is a variable called "$variableName". I named it this because that's what it will represent: the name of the variable being received. "receivePOST" has one purpose: to retrieve the variable with a name of whatever value is passed in via HTTP POST, call the "htmlspecialchars" function on it (to replace special characters), and return the value. This function is then called 3 times:

$textBox = receivePOST("textbox");
$textArea = receivePOST("textarea");
$dropDown = receivePOST("dropdown");

Remember those 3 values for "name" that we used in the HTML form ("textbox", "textarea", and "dropdown")? That's the string we pass in to this function. Just so you understand fully, if we didn't use a function and decided to do everything manually, the code would look like this:

$textBox = htmlspecialchars($_POST["textbox"]);
$textArea = htmlspecialchars($_POST["textarea"]);
$dropDown = htmlspecialchars($_POST["dropdown"]);

Hopefully that makes sense now. The last thing I do before using these 3 values is check to make sure none of them are empty with this code:

if (!strlen($textBox) || !strlen($textArea) || !strlen($dropDown))

You should know what a conditional statement is from my last tutorial. In this case, there are actually 3 conditions combined into one. If this were to be put into words, it would read: "if either of the '$textBox', '$textArea', or '$dropDown' variables (or any combination of them) do not have a string length greater than 0". In PHP, you can frequently use variables of different types interchangeably without worrying about any consequences. For instance, even if the value of "$textBox" is 3, it could still be used as if its value were "3", and vice versa. Hence, we can simply check the string length, and if its length is not greater than 0 then it is empty. Just for better understanding, "!" means "not/negate/false/opposite", and "X || Y" (this character is found above the "Enter" key, usually) means "X, Y, or both".


Finally, after ensuring that all 3 values have been passed in, it echoes the contents of each variable for the viewer to see. I hope this tutorial helped you to understand how to create your own HTML forms and the backend PHP code to receive and process data from them. Now you just have to learn how to do other things with that data besides just echoing it out. :)

6 comments: