User Interaction and Forms
For many applications of PHP, the ability to interact with users whoview the Web page is essential. Veterans of JavaScript tend to think in terms
of event handlers, which let you react directly to the actions of the user
— for example, the movement of the mouse over a link on the page. Server-side
scripting languages such as PHP have a more limited scope when it comes to
user interaction. As PHP code is activated when a page is requested from the
server, user interaction can occur only in a back-and-forth fashion: the user
sends requests to the server, and the server replies with dynamically generated
pages.The key to creating interactivity with PHP is to understand the techniques
we can use to send information about a user's interaction along with his or
her request for a new Web page. PHP makes this fairly easy, as we'll now see.The simplest method we can use to send information along with a page
request uses the URL query string. If you've ever seen a URL with a question mark
following the file name, you've witnessed this technique in use. Let's look
at an easy example. Create a regular HTML file called welcome1l (no .php file
extension is required, since there will be no PHP code in this file) and insert
this link:
<a href=">Hi, I'm Kevin!</a>
This is a link to a file called welcome1.php, but
as well as linking to the file, we're also passing a variable along with the
page request. The variable is passed as part of the query string, which is
the portion of the URL that follows the question mark. The variable is called name and
its value is Kevin. To restate, we have created a link
that loads welcome1.php, and informs the PHP code contained
in the file that name equals Kevin.To really understand the results of this process, we need to look at welcome1.php.
Create it as a new HTML file, but this time note the .php extension
— this tells the Web server that it can expect to interpret some PHP
code in the file. In the body of this new file, type:
<?php
$name = $_GET['name'];
echo( "Welcome to our Website, $name!" );
?>
Now, if you use the link in the first file to load this second file,
you'll see that the page says "Welcome to our Website, Kevin!"PHP automatically creates an array variable called $_GET[1] that
contains any values passed in the query string. $_GET is
an associative array, so the value of the name variable
passed in the query string can be accessed as $_GET['name'].
Our script assigns this value to an ordinary PHP variable ($name)
and then displays it as part of a text string using the echo function.
In
versions of PHP prior to 4.2, the register_globals setting
in php.ini was set to On by default.
This setting tells PHP to create automatically ordinary variables for all
the values supplied in the request. In the previous example, the $name
= $_GET['name']; line is completely unnecessary if the register_globals setting
were set to On, since PHP would do it automatically. Although
the convenience of this feature was one aspect of PHP that helped to make
it such a popular language in the first place, novice developers could easily
leave security holes in sensitive scripts with it enabled.For a full discussion of the issues surrounding register_globals,
see my article Write
Secure Scripts with PHP 4.2! at sitepoint.com.
You can pass more than one value in the query string. Let's look at
a slightly more complex version of the same example. Change the link in the
HTML file to read as follows (this is welcome2l in
the code archive):
<a href="> Hi,
I'm Kevin Yank! </a>
This time, we'll pass two variables: firstname and lastname.
The variables are separated in the query string by an ampersand (&).
You can pass even more variables by separating each name=value pair
from the next with an ampersand.As before, we can use the two variable values in our welcome.php file
(this is welcome2.php in the code archive):
<?php
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
echo( "Welcome to my Website, $firstname $lastname!" );
?>
This is all well and good, but we still have yet to achieve our goal
of true user interaction, where the user can actually enter arbitrary information
and have it processed by PHP. To continue with our example of a personalized
welcome message, we'd like to allow the user to actually type his or her name
and have it appear in the message. To allow the user to type in a value, we'll
need to use an HTML form.Here's the code (welcome3l):
<form action="welcome3.php" method="get">
First Name: <input type="text" name="firstname" /><br />
Last Name: <input type="text" name="lastname" /><br />
<input type="submit" value="GO" />
</form>
This form has the exact same effect as the second link we looked at
(with firstname=Kevin&lastname=Yank in the query string),
except that you can enter whatever names you like. When you click the submit
button (which has a label of "GO"), the browser will load welcome3.php and
automatically add the variables and their values to the query string for you.
It retrieves the names of the variables from the name attributes
of the input type="text" tags, and it obtains the values
from the information the user typed into the text fields.The method attribute of the form tag is
used to tell the browser how to send the variables and their values along
with the request. A value of get (as used above) causes
them to be passed in the query string (and appear in PHP's $_GET array),
but there is an alternative. It's not always desirable—or even technically
feasible—to have the values appear in the query string. What if we included
a <textarea> tag in the form, to let the user enter
a large amount of text? A URL that contained several paragraphs of text in
the query string would be ridiculously long, and would exceed by far the maximum
length of the URL in today's browsers. The alternative is for the browser
to pass the information invisibly, behind the scenes. The code for this looks
exactly the same, but where we set the form method to get in
the last example, here we set it to post (welcome4l):
<form action="welcome4.php" method="post">
First Name: <input type="text" name="firstname" /><br />
Last Name: <input type="text" name="lastname" /><br />
<input type="submit" value="GO" />
</form>
As we're no longer sending the variables as part of the query string,
they no longer appear in PHP's $_GET array. Instead, they
are placed in another array reserved especially for 'posted' form variables: $_POST[2].
We must therefore modify welcome3.php to retrieve the
values from this new array (welcome4.php):
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo( "Welcome to my Website, $firstname $lastname!" );
?>
This form is functionally identical to the previous one. The only difference
is that the URL of the page that's loaded when the user clicks the "GO" button
will not have a query string. On the one hand, this lets you include large
values, or sensitive values (like passwords) in the data that's submitted
by the form, without their appearing in the query string. On the other hand,
if the user bookmarks the page that results from the form's submission, that
bookmark will be useless, as it doesn't contain the submitted values. This,
incidentally, is the main reason that search engines like Google use
the query string to submit search terms. If you bookmark a search results
page on AltaVista, you can use that bookmark to perform the same search again
later, because the search terms are contained in the URL.Sometimes, you want access to a variable without having to worry about
whether it was sent as part of the query string or a form post. In cases like
these, the special $_REQUEST[3] array
comes in handy. It contains all the variables that appear in both $_GET and $_POST.
With this variable, we can modify welcome4.php one more
time so that it can receive the first and last names of the user from either
source (welcome5.php):
<?php
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
echo( "Welcome to my Website, $firstname $lastname!" );
?>
That covers the basics of using forms to produce rudimentary user interaction
with PHP. I'll cover more advanced issues and techniques in later examples.[1]Prior to PHP 4.1, this variable was called $HTTP_GET_VARS.
This variable name remains in current PHP versions for backwards compatibility.
If your server has an older version of PHP installed, or if you're writing
a script that must be compatible with older versions, you should use $HTTP_GET_VARS instead
of $_GET.[2]Prior to PHP 4.1, 'posted' form variables were available in the $HTTP_POST_VARS array.
This array remains available in current versions of PHP for backwards compatibility.[3]$_REQUEST is
not available in versions of PHP prior to PHP 4.1.