PHP and MySQL Programming/Form Handling
In order to get user input without using the command line, then you will use HTML forms. PHP has various functions and techniques for handling the input from HTML forms. In specific, we will use the special array variables $_GET[] and $_POST[].
HTML Forms
[edit | edit source]Before we start using these special variables, lets have a look at how to set up the HTML forms to interact with PHP. Here is a simple example form:
<html>
<head><title>HTML Form Example</title></head>
<body>
<form method="POST" action="form_handler.php">
username: <input type="text" name="username"> <br>
password: <input type="password" name="password"> <br>
<input type="submit" value="GO">
</form>
</body>
</html>
The above example sets up a form with a method
and an action
attribute. The `method` defines how the data from the form is to be transferred to the page defined by `action`. The `method` can either be GET or POST. If GET is used, then all the form elements will be appended to the url of the target page (specified by the action
attribute), in url encoded format (target?attrib1=val1&attrib2=val2&attrib3=val3
etc...) These attributes are easily accessed in PHP by using the $_GET[]
array.
If the POST method is specified, then the data will be put into a special server variable, and accessed in PHP by using the built-in $_POST[]
array.
Note that in the HTML code, the name
attribute of the INPUT tags are used as the reference strings in the $_GET
and $_POST
arrays, thus it is very important to always use unique values for the name
attribute.
GET
[edit | edit source]To retrieve GET
variables in the address url, we use the following method:
$username = $_GET['username'];
$password = $_GET['password'];
echo "Username: $username \n Password: $password \n";
Please note that GET
is not good to use for this example, because you will generally not want username and password details being displayed in the URL. Rather use POST for login details and authentication.
POST
[edit | edit source]To retrieve POST
variables, we use the following method:
$username = $_POST['username'];
$password = $_POST['password'];
print "Username: $username \n Password: $password \n";
Note that when POST
is used, the posted data is completely invisible to the user.
Further Reading
[edit | edit source]