<<

. 21
( 132 .)



>>

“last_name” => “doe”,
“age” => 52
)
);

Here the $people array contains information on two people, Jay and John. To
access information on any single value, you would need to use both keys. To print
out John™s age, the following two commands would work:

echo $people[˜john™][˜age™]; //prints 52

You could access all of the elements in a two-dimensional array by looping
through both of the array™s dimensions:

foreach ($people as $person => $person_array)
{
echo “<b>What I know about $person</b><br>\n”;
foreach ($person_array as $person_attribute => $value)
{
echo “$person_attribute = $value<br>\n”;
}
}
100 Part II: Working with PHP


Accessing Variables Passed
from the Browser
The whole point of using PHP, or any other middleware package for that matter, is
to deliver customized information based on user preferences and needs. Often, the
information will come via HTML forms. But information can come from other
places, including HTML anchors, cookies, and sessions.

HTML forms variables
One of the most common ways in which variable information is delivered is
through HTML forms.


Appendix B presents detailed information on creating HTML forms. Refer to
that appendix before you read this section if you are unfamiliar with this
topic.



For each of your form elements you have to assign name and value attributes
(name and value are settings defined in HTML code). When the form is submitted,
the name/value pairs are passed to PHP. They can be passed to PHP by either the
GET or POST methods, depending on what you chose in the METHOD attribute of your
<FORM> tag (the default is GET).
In older versions of PHP (prior to PHP 4.2), once a form was submitted, the form
elements automatically become global variables in PHP. (Global variables and vari-
able scope are discussed in Chapter 7). Consider the following simple HTML form:

<form action=”mypage.php” method=”POST”>
<input type=text name=email>
<input type=text name=first_name>
<input type=submit name=submit value=add>
</form>

Once the user hit the Submit button, variables named $email, $first_name, and
$submit were made available in the called PHP page. Listing 4-1 is a brief example
of how scripts were usually written for PHP versions 4.1 and lower. (Assume the
name of the page is mypage.php.)

Listing 4-1: Common Variable Use in Older Versions of PHP
<?php
if (isset($submit) && $submit==”yes”)
{
echo “thank you for submitting your form.”;
Chapter 4: Getting Started with PHP ” Variables 101

}
else
{

?>
<form action=”mypage.php” method=”POST”>
<input type=”text” name=”email”>
<input type=”text” name=”first_name”>
<input type=”submit” name=”submit” value=”yes”>
</form>

<?php
}
?>

On his or her first visit to this page the user would be presented with a form.
Once the form was submitted and the page had recalled itself with the new variable
information, only the “thank you” message would appear. There was, however, a
major problem with the global variables that came from forms. Even the code in
Listing 4-1, which is about as simple as scripting gets, demonstrates this problem.
The user-entered variables should come to the PHP script by way of the POST
method ” not by way of GET. However, if a user wanted to see the “thank you” mes-
sage without entering anything into the form elements, he or she could simply tack
some information onto the URL typed into the browser. For example:

http://localhost/mypage.php?submit=yes

In older versions of PHP, when the PHP engine encountered the submit variable in
the querystring, it would automatically register the variable as a global and thus the
test at the beginning of this script ” if (isset($submit) && $submit==”yes”) ”
would be true.
Many programmers wrote applications that took advantage of the global vari-
ables and unintentionally made their scripts vulnerable to attacks. We won™t get into
the details of the exploits here; it™s enough to mention that, even if you have the
opportunity, you should not be using global variables that come from form ele-
ments. Instead you should use a series of arrays that contain variables sent via HTTP.


In PHP 4.2 and higher you can opt to have GET, POST, session, and cookie
variables available as globals by altering the register_globals item in
the php.ini file. Current versions of PHP default to a setting of off, meaning
that HTTP variables will not be available as globals. In most circumstances
you should keep this setting the way it is. However, if you are running older
scripts that you don™t have time to change, you may have to alter this setting.
102 Part II: Working with PHP

In PHP versions 4.2 or later, you should be getting your form data via the super-
global (so called because they are globally available without ever having to be
declared as global) array variables $_POST and $_GET, depending on the method
used in your form. You can also use the $_REQUEST variable, which is a combina-
tion of GET, POST, and cookie values.
To add a bit more security to the previous listing, you could rewrite Listing 4-1
to look like Listing 4-2:

Listing 4-2: Simple Script That Does Not Use Globals
if (isset($_POST[˜submit™]) && $_POST[˜submit™]==”yes”)
{
echo “thank you for submitting your form.”;
}
else
{
?>
<form action=”test1.php” method=”POST”>
<input type=”text” name=”email”>
<input type=”text” name=”first_name”>
<input type=”submit” name=”submit” value=”yes”>
</form>

<?php
}

You can access any individual element as you would an element in any associa-
tive array ($_POST [˜email™]). Or you can loop through all the contents of an
array as follows:

foreach ($_POST as $key => $value)
{
echo “variable = $key value = $value <br>”;
}


Passing arrays
Sometimes passing scalar variables won™t be enough, and you™ll need to pass arrays
from your HTML page to your PHP script. This will come up when the user can
choose one or more form elements on a page. Take, for example, multiple select
boxes, which enable users to pass one or more items from a number of items. The
form element is made with the HTML in the following code example. The multiple
attribute indicates that the user can choose more than one element, as shown in
Figure 4-1. To choose more than one element on the PC, hold down the Ctrl key
while selecting additional values. On the Mac, use the Apple key. Gnome users can
select and unselect individual elements with a click.
Chapter 4: Getting Started with PHP ” Variables 103

<form action=”mypage.php” method=”POST”>
<select name=”j_names[]” size=”4” multiple>
<option value=”2”>John
<option value=”3”>Jay
<option value=”4”>Jackie
<option value=”5”>Jordan
<option value=”6”>Julia
</select>
<input type=”submit” value=”submit”>
</form>




Figure 4-1: Multiple select boxes


Notice that in the select name attribute we™ve added opening and closing brack-
ets ([]). This tells PHP to expect an array. If we didn™t include the brackets, two val-
ues might end up fighting for the same variable name, and that™s no good at all.
Once it has been submitted you can address this array like any other two-
dimensional array:

if (is_array($_POST[˜j_names™]))
{
echo “<b>the select values are:<br> <br>”;

foreach ($_POST[˜j_names™] as $value) {
104 Part II: Working with PHP

echo $value . “<br>\n”;
}
}

Passing arrays can also be useful when you want to present a series of check-
boxes that the user may or may not check before pressing the Submit button.
Chapter 8 contains a code example for a page that enables the program™s adminis-
trator to use checkboxes to select which entries should be deleted. Figure 4-2 shows
a sample of this type of page. If you were to assign a different name to each check-
box, you would have to check each one individually. With arrays, you can write a
three-line loop to check them all.




Figure 4-2: Series of checkboxes


Arrays passed from forms can also have associative keys, which can be multidi-
mensional. The name of the form element should take the form name=
”array_name[element_name]”. Or, for a multidimensional array, name=”array_
name[element_name][subelement_name]”.


Cookies
Cookies are small pieces of information that are stored by a user™s Web browser.
Some are kept in memory and discarded after a short time, and others are written to
the user™s hard drive for long-term use. Once a Web browser has accepted a cookie
Chapter 4: Getting Started with PHP ” Variables 105

from a server, it resends the same cookie to its owner(s) on each HTTP request until
the cookie expires or is deleted. Cookies provide the only way to keep track of users
over the course of several visits. Remember that the Web is a stateless environment.
Your Web server really has no idea who is requesting a page. Cookies help you keep
track of users as they move around your site.
When they exist, cookies become part of the HTTP request sent to the Web
server. But first you™ll need to set a cookie. The PHP developers have made this, like
everything else in PHP, exceedingly simple. Use the setcookie() function. This
function takes the following arguments:

setcookie(name [, value [, time_to_expire [, path [, domain [,
security setting]]]]]);

We will discuss this function in more detail in Chapter 6, but for now, suffice it
to say that the following statement ”

setcookie(“mycookie”,
“my_id”,time()+(60*60*24*30),”/”,”.mydomain.com”, 0)

” would set a cookie with the following parameters:

— Stores a variable named my_cookie

— The value of mycookie is “my_id”.

— The cookie will expire 30 days from the time it is set (current time plus
the number of seconds in 30 days).
— The cookie will be available to every page in the domain. (You could
restrict it to a specific path within a domain by including a path.)
— The cookie will be available to every site with a mydomain.com address.

— There are no special security settings.

Once the cookie is set, you can retrieve cookie values through the $_COOKIE
superglobal array variable. The value of the cookie set with the previous
setcookie() function is available as $_COOKIE[˜mycookie™].
You can also set cookies that are accessible as arrays:

setcookie(“mycookie[first]”,
“dddd”,time()+2592000,”/”,”192.168.1.1”, 0);
setcookie(“mycookie[second]”,
“my_second_id”,time()+2592000,”/”,”192.168.1.1”, 0);

These two variables would be accessible as associative arrays within the
$_COOKIE array.
106 Part II: Working with PHP

<<

. 21
( 132 .)



>>