PHP Forms

If you ever need to gather information inputted from the end user, a form must be created. We can do this by using the PHP $_GET and $_POST variables.

We use the $_GET variable to gather the information, then the $_POST variable to process that same data.

First, we will create a very simple example form using HTML:

<form action=”form.php” method=”post”>
Color: <input type=”text” name=”color” />
Gallons: <input type=”text” name=”gallons” />
<input type=”submit” name=”submit” value=”Send!”>
</form>

Using the above HTML, we would have created a form with two text boxes and a submit button. In the first text box, the user would enter the color of paint they desire. In the second box, they enter the number of gallons they would like.

The last part of the form we have a submit button, which when clicked, will send the data to the file “form.php” to be processed.

Our form.php file can look like this:

The color paint you want is: <?php echo $_POST["color"]; ?>.<br />
You wish to order <?php echo $_POST["gallons"]; ?> gallons.

Once the user submits the form, the end result could look like this:

The color paint you want is: Black.
You wish to order 8 gallons.

Sending Form Results By Email

You can take this one step further by having the data submitted in the form sent to you by email. We will be using a bare bones example of how this can be done.

Again, we start with our HTML form:

<form action=”form.php” method=”post”>
<table><tr>
<td>Name:</td>
<td><input type=”text” name=”name”></td></tr>
<tr>
<td>Subject:</td>
<td><input type=”text” name=”subject”></td></tr>
<tr>
<td>Message:</td>
<td><textarea name=”message”></textarea></td></tr>
<tr>
<td> </td>
<td><input type=”submit” name=”submit” value=”Send!”></td></tr>
</table></form>

With this simple form, we have two text boxes: One for the user to enter their name, and another to enter the subject.

We then have a text area for the user to enter the actual contents of the message, followed by a submit button which will send the data to “form.php” using the POST method.

Our form.php file can look like this:

$sendto = ‘yourname@example.com’;

$subject = $_POST['subject'];
$from = stripslashes($_POST['name']);
$body = “Message from: $fromnn”.stripslashes($_POST['message']);
mail($sendto, $subject, $body);

As you can see, we defined the string $sendto with your email address (the email address which the data will be sent to).

We then took the name to define who the message was from and the message which was entered in the text area to define the body of the email.

Finally, we took the data and sent it to the specified email address.