Processing Forms in php

It’s easy to process forms with PHP, as the form parameters are available in the $_GET and $_POST arrays. There are many tricks and techniques for working with forms

Methods

GET and POST. The method that a particular form uses is specified with the method attribute to the form tag. In theory, methods are case-insensitive in the HTML, but in practice some broken browsers require the method name to be in all uppercase

A GET request encodes the form parameters in the URL in what is called a query string; the text that follows the ? is the query string:

/path/to/chunkify.php?word=despicable&length=3

A POST request passes the form parameters in the body of the HTTP request, leaving the URL untouched

The most visible difference between GET and POST is the URL line. Because all of a form’s parameters are encoded in the URL with a GET request, users can bookmark GET queries. They cannot do this with POST requests

The type of method that was used to request a PHP page is available through $_SERVER[‘REQUEST_METHOD’]

if ($_SERVER[‘REQUEST_METHOD’] == ‘GET’) {
// handle a GET request
}
else {
die(“You may only GET this page.”);
}

Parameters

Use the $_POST, $_GET, and $_FILES arrays to access form parameters from your PHP code. The keys are the parameter names, and the values are the values of those parameters. Because periods are legal in HTML field names but not in PHP variable names, periods in field names are converted to underscores (_) in the array

Example

shows an HTML form that chunkifies a string supplied by the user. The form contains two fields: one for the string (parameter name word) and one for the size of chunks to produce (parameter name number)

<html>
 <head><title>Chunkify Form</title></head>
 <body>
 <form action="chunkify.php" method="POST">
 Enter a word: <input type="text" name="word" /><br />
 How long should the chunks be?
<input type="text" name="number" /><br />
 <input type="submit" value="Chunkify!">
 </form>
</body>
</html>

Leave a Comment