. 22
( 132 .)


The preceding code works fine on Internet Explorer 5 on the PC. However, it
might not work on other browsers. In any case, you are probably better off
avoiding situations that require arrays within cookies.

PHP, like ASP and ColdFusion, natively supports sessions, only it does a much bet-
ter job. What™s a session? Basically, it™s another means of maintaining state between
pages. Your script declares that a session should start by accessing the $_SESSION
superglobal variable (you can also use the older-style session_start() function).
At that point PHP registers a unique session ID, and usually that ID is sent to the
user via a cookie. PHP then creates a corresponding file on the server that can then
keep track of any number of variables. The file has the same name as the session ID.
Once the session is created, you can register any number of variables. The values
of these variables are kept in the file on the server. As long as the session cookie
lives, these variables will be available to any page within the same domain that
wishes to access them. This setup is much more convenient than sending variables
from page to page through hidden form elements or bloated cookies.
Of course, it is possible that some users will not allow cookies. For this reason,
PHP enables you to track the session ID through the querystring. You can do this
manually by appending the session ID to the querystring, or by changing the
session.use_cookies value in your php.ini file to equal 1.
The constant SID is predefined as “session-name=session-ID”. To add it to the
querystring manually, use <?php echo SID; ?>. This automatically prints out a
string like this:


Adding this value to a link will cause PHPSESSID to be passed via the query-
string. Use something like this:

<a href=”mypage.php?<?php echo SID; ?>”>click to page</a>

The following script will register a session variable named my_var, and will
assign it a value of “hello world”.

$_SESSION[˜my_var™] = “hello world”;

On subsequent pages, you are able to access this by simply referring to
Chapter 4: Getting Started with PHP ” Variables 107

It can take a little work with if statements to make your session variables prop-
erly accessible. Look at the short script in Listing 4-3 for an example.

Listing 4-3: Code Using Sessions

//check to see if $_SESSION[˜your name™] contains anything
if (!empty($_SESSION[˜your_name™]))
//this portion will run the first time to
//this page.
echo “I already know your name,” , $_SESSION[˜your_name™];
if (empty($_POST[˜submit™]))
{ echo “<form name=myform method=post action=$PHP_SELF>
<input type=text name=first_name> first name<br>
<input type=text name=last_name> last name<br>
<input type=submit name=submit value=submit>

//if the form has been submitted, this portion will
//run and make an assignment to $_SESSION[˜your_name™].
$_SESSION[˜your_name™] = “$first_name $last_name”;
echo “Thank you, {$_SESSION[˜your_name™]}”;

After running this code, hit Refresh on your browser. You will see that the script
remembers who you are.

If your script sends anything to the browser prior to setting a cookie ” even
so much as a blank line at the end of an included file ” you will get error
messages. So if you are setting cookies manually, or using cookies to store
your session ID, you should make sure that either that part of your code is at
the very top of your script file or use the output-buffering functions to keep
your script from sending anything to the browser until you™re ready.
108 Part II: Working with PHP

Using Built-In Variables
A variety of variables are set by your server and PHP environment. You can find a
complete list of these variables by running phpinfo(). If you haven™t done it yet,
go to your keyboard, run the following script:


This script delivers a page listing these variables.

It™s a good idea to delete this page when you™re done with it. No need to
give crackers any more information than absolutely necessary.

You can use this variety of variables in a variety of ways. We™ll take a look at
some of these variables now, and show you where and when you might use them.
Some variables come from the PHP engine, while others originate from your Web

PHP variables
Many of the most useful values supplied by PHP are available as keys of the
$_SERVER superglobal.

The relative path of the script being run. This is very helpful when a form is both
presented and processed in the same PHP page.

//do some form processing here
echo “thanks for the submission”;
} else {
<form name=”myform” method=”POST” action=”<?php echo $PHP_SELF; ?>>
<input type=”text” name=”first_name”> first name<br>
<input type=”text” name=”last_name”> last name<br>
<input type=”submit name=”submit” value=”submit”>
Chapter 4: Getting Started with PHP ” Variables 109


Keep in mind that PHP_SELF always refers to the name of the script being exe-
cuted in the URL. So in an include file, PHP_SELF will not refer to the file that has
been included; it will refer to the script being run.
It™s worth noting that PHP_SELF behaves strangely when PHP is run on Windows
or as a CGI module. Make sure to look at phpinfo() to see the value of $PHP_SELF
on your system.

Returns the domain of the host serving the page.

Returns the IP address of the host serving the domain.

Returns the path of the document being accessed, relative to the root directory of
the filesystem.

Very similar to PHP_SELF, except that querystring information is maintained in this
variable. So if you were visiting http://www.mydomain.com/info/products/
index.php?id=6, $_SERVER[˜REQUEST_URI™] would equal /info/products/

See your phpinfo() page for a full list of PHP variables.

Apache variables
Apache keeps track of dozens of variables. We can™t include a complete list of them
here, as the variables you use will vary depending on your current setup. Here are
some of the ones you might use frequently in your scripts.
As you look at this list and phpinfo(), keep in mind that if you are not getting
what you want out of your Web server variables, you will need to make changes to
your server configuration, not PHP. PHP just passes the information along and can-
not alter these variables. There is also a fair amount of overlap between PHP and
Apache variables. These are also available as keys of the $_SERVER array variable.
110 Part II: Working with PHP

Returns the full path to the root of your Web server. (For most Apache users this
directory will be something like /path/to/htdocs.) We use this variable throughout
the book to make our applications portable. Take this include statement as an


By using the $_SERVER[˜DOCUMENT_ROOT™] variable instead of an absolute path,
we can move the book directory and all its sub-folders to any other Apache server
without worrying that the include statements will break. Keep in mind that if you
are using a Web server other than Apache, $_SERVER[˜DOCUMENT_ROOT™] may not
be available.

If you set the include_path directive in your php.ini file, you will not need
to worry about specifying any path in your include statement ” PHP will
look through all the directories you specify and try to find the file you

Contains the URL of the page the user viewed prior to the one he or she is currently
viewing. Keep in mind when using $_SERVER[˜HTTP_REFERER™] that not every
page request has a referrer. If the user types the URL into a browser, or gets to your
page via bookmarks, no referrer will be sent. This variable can be used to present
customized information. If you had a relationship with another site and wished to
serve up a special, customized header for only those referred from that domain, you
might use a script like this:

//check if my user was referred from my_partners_domain.com
if(ereg (“http.*my_partners_domain.com.*” ,
include ˜normal_header.php™;

Keep in mind that $_SERVER[˜HTTP_REFERER™] is notoriously unreliable.
Different browsers serve up different values in certain situations. It is also easily
spoofed. So you wouldn™t want to use a script like the preceding to serve any secure
Chapter 4: Getting Started with PHP ” Variables 111

Anyone who has built a Web page knows how important browser detection is.
Some browsers will choke on fancy JavaScript, and others require very simple text.
The user_agent string is your key to serving the right content to the right people.
A typical user_agent string looks something like this:

Mozilla/4.0 (compatible; MSIE 5.01; Windows 98)

You can then parse this string to get what you are looking for.
You may be interested in PHP™s get_browser() function. Theoretically, this
function will determine the capabilities of your user™s browser so you can find out
if your script can safely serve out, for example, frames or JavaScript. The PHP
manual has instructions for installation and use of get_browser(), but we do not
recommend using it. Why? Using get_browser() you will be told that both
Internet Explorer 5 for the PC and Netscape Navigator 4.01 for the Mac support CSS
(Cascading Style Sheets) and JavaScript. But as anyone with client-side experience
knows, writing DHTML that works on both of these browsers is a major task (and a
major pain). The information you get from get_browser() can lead to a false sense
of security. You™re better off accessing $_SERVER[˜HTTP_USER_AGENT™] and mak-
ing decisions based on the specific browser and platform.

The IP address of the user that sent the HTTP request. $_SERVER[˜REMOTE_ADDR™]
is easily spoofed and doesn™t necessarily provide information unique to a user. You
might want to use it for tracking, but it should not be used to enforce security. On
some servers ” notably the default Apache installation shipped with Mac OS X ”
this is available as $_SERVER[˜HTTP_PC_REMOTE_ADDR™] instead.

The host machine sending the request. This has a value only if your server is
configured to do reverse DNS lookups, something that is commonly turned off for
performance reasons. When I dial it up through my ISP (att.net),
$_SERVER[˜REMOTE_HOST™] looks like this: 119.san-francisco-18-19rs.ca.

Contains the filesystem™s complete path to the file.

Other Web server variables
As mentioned earlier, phpinfo() is your friend. We developed applications for this


. 22
( 132 .)