You are on page 1of 17

10 PHP Scripting Tips

NOTE: This article appears in CNet Builder.com, at: http://builder.cnet.com/webbuilding/0-3882-8-4639552-1.html

The administrators of more than 3 million Web sites have made PHP one of the most popular server-side scripting languages
around. It's fast, it's reliable, it's cross-platform, and it's open source. PHP can be as simple or as complex as you want it to
be. You can use it just for sending HTML form elements, or you can integrate Java and XML within your PHP application.

If you've taken a gander at PHP or read through an introductory tutorial, these tips will expand your knowledge a bit
further, introducing you to some common uses as well as advanced features of PHP.

Installing PHP as an Apache DSO


PHP is most often paired with the Apache Web server on a Linux/Unix platform. When installing PHP with Apache, you
have three installation options: static module, dynamic module (DSO), and CGI binary.

I recommend the DSO installation option as it's extremely easy to maintain and upgrade. For example, suppose you do a
simple installation of PHP with just database support. A few days later, you decide that you want to install encryption
support. All you have to do is type make clean, add the new configuration option, and followed by make and make install.
A new PHP module will be dumped in the proper location for Apache, and all you have to do is restart Apache, not
recompile it.

These basic steps will install a fresh version of Apache and PHP as a DSO:

1. Get the latest version of the Apache source code from the Apache Software Foundation.
2. Put this file somewhere logical, such as /usr/local/ or /opt/ or anywhere else you want.
3. Gunzip or uncompress the file, so that you're left with the *.tar file.
4. Type the following to un-tar the file into a directory called apache_[version]:

tar -xvf apache_[version].tar

5. cd into /usr/local/apache_[version] (or wherever you un-tar'd the compressed source file).
6. Type the following to prepare for building, replacing [path] with your own path, such as /usr/local/apache[version] (no
trailing slash!). You are now enabling mod_so, which will allow Apache to use DSOs.

./configure --prefix=[path] --enable-module=so

7. When you're back at the prompt, type make, and wait for the prompt to return again.
8. Type make install.

At this point, the compilation will create the final set of directories and files and return you to the prompt.

Next, install PHP:

1. Go to the Downloads area of the PHP home page and select the link for the latest source files.
2. Put this file somewhere logical, such as /usr/local/ or /opt/ or anywhere else you want.
3. Gunzip or uncompress the file, so that you're left with the *.tar file.
4. Type the following to un-tar the file into a directory called php-[version]:

tar -xvf php-[version]

1
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)

5. cd into /usr/local/php-[version] (or wherever you put it)

You're now ready to build the PHP DSO. Only one configuration option is necessary--with-apxs (a file in the Apache bin
directory)--but I'll throw MySQL support in for good measure.

./configure --with-mysql=/[path to mysql] --with-apxs=/[path to apxs]

6. When you're back at the prompt, type make, and wait for the prompt to return again.
7. Type make install.

At this point, the compilation will create the final DSO, plop it in the Apache modules directory, modify some parts of the
Apache httpd.conf file for you, and return you to the prompt. When you're back at the prompt, you'll need to go back to
the Apache httpd.conf and make a few modifications:

1. Find the line for ServerAdmin, and add your e-mail address, in other words:
ServerAdmin you@yourdomain.com

2. Find the line starting with ServerName, and change it to real values, such as:
ServerName localhost

3. Find a section like the following:

# And for PHP 4.x, use:


#
#AddType application/x-httpd-php .php
#AddType application/x-httpd-php-source .phps

Modify these lines so that the AddType for PHP 4.0 is uncommented, and add any more file extensions you want to use
with PHP, so that the block looks like this:

# And for PHP 4.x, use:


#
AddType application/x-httpd-php .php .phtml
AddType application/x-httpd-php-source .phps

Save the file, cd up a directory, and start Apache by typing:

./bin/apachectl start

If there are no errors on startup, you can test your installation of Apache and PHP by creating a file called phpinfo.php,
containing just this line:

<? phpinfo() ?>

Save this file and put it in Apache's document root (htdocs), then fire up your Web browser and go to http://localhost/
phpinfo.php, where you should see a long page of variables and their values.

If you want to reconfigure PHP, all you need to do is run make clean, then a new ./configure command with a new set of
options, then make and make install. A new module will appear in the Apache modules directory, and just restart Apache to
load this new module. Many headaches are now relieved.

2
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)

Using native sessions


One of the more long-awaited features of PHP 4.0 was its session support. Users of PHP 3.0 had to use a third-party library
or nothing at all, and the lack of session support was one of PHP's biggest detractions. No more, though, as session support
has been part of PHP 4.0 since the early beta releases.

You can use sessions to maintain user-specific variables throughout a user's stay at your Web site without setting multiple
cookies, using hidden form fields, or storing information in a database to which you'd probably have to connect way too
often.

Starting a session on a page tells the PHP engine that you want to either start a session (if one isn't already started) or
continue a current session:

session_start();

Starting a session will send an identification string (such as 940f8b05a40d5119c030c9c7745aead9) to the user via a cookie;
on the server side, a matching temporary file is created with the same name, such as
sess_940f8b05a40d5119c030c9c7745aead9. This file contains the registered session variables and their values.

The most common example used to show sessions in action is an access counter:

Start your PHP block, and be absolutely sure that the PHP code is the first line of your file: no white space, no HTML
output, nothing. As session functions send a header; if you send white space or HTML output before the session_start()
call, you'll get an error.

<?
// if a session does not yet exist for this user, start one
session_start();

Next, register a variable called count.

session_register('count');

Registering a session variable tells PHP that for as long as this session exists, a variable called count also exists. Currently,
the variable has no value. However, if you increment it, it will have a value of 1:

$count++;

Put this all together, and you'll have started a session if one wasn't already started, assigned a session id to a user if one
doesn't exist, registered the variable called count, and incremented $count by one to represent the initial time the user has
accessed the page:

To show users how many times they've accessed this page in their current session, just print the value of $count:

echo "<P>You've been here $count times.</p>";

3
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
The entire access count code looks like this:

<?
session_start();
session_register('count');
$count++;
echo "<P>You've been here $count times.</p>";
?>

If you reload the script, you can watch the count increment. Very exciting.

You can register arrays in sessions as well. Suppose you have an array called $faves:

$faves = array ('chocolate','coffee','beer','linux');

You can register this array just like any single variable:

session_register('faves');

You reference the array like any single variable, as well: $faves. If your user indicates his or her favorite things in life on
one page of your Web site, and you register those things in a session variable called $faves, then on another page, you can
simply print those values out:

<?
session_start();
echo "My user likes:
<ul>";

while (list(,$v) = each ($faves)) {


echo "<li>$v"; }

echo "</ul>";
?>

There you have it: a nice bullet list of your user's favorite things.

Session variables cannot be overwritten by a query string, meaning that you can't type http:///www.yourdomain.com/
yourscript.php?count=56 and assign a new value to the registered session variable called $count. This is an extremely
important concept for security: you can modify or delete (unregister) session variables on only the server side, within your
scripts.

If you want to completely delete a session variable, you unregister it from the system:

session_unregister('count');

To delete a session in its entirety, as from a Logout button, the script would be simple:

session_destroy();

Using sessions to store values alleviates database connectivity overhead as well as messy coding nightmares and long
privacy statements about why you're sending fifty cookies to the user throughout his or her visit to your site. One cookie,

4
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
one value, one big ethereal blob holding everything else: It can't get much simpler than that!

Include files are your friends


If you do Web site development on any scale, you'll recognize the importance of reusable code snippets, whether it's blocks
of HTML or PHP. For example, you'll change a footer containing your copyright information at least once a year, and if you
have 1,000 pages (or even 10), it's a pain to have to do it all manually.

With PHP, you have a few different functions that help you to reuse code. The function you use depends on what you're
reusing.

The main functions are:

• include() and include_once()


• require() and require_once()

The include() function includes and evaluates the given file. For example:

include('/home/me/myfile');

Any code in the included file will be executed with a variable scope equal to that point at which the include() occurred in
the parent code. You can include static files on your server or target files on another server, using a combination of
include() and fopen().

The include_once() function does the same thing as the include() function, only it will check to see if the code from a file
has already been included in the current script. If the code has already been included, the function will not include it
again.

The require() function replaces itself with the contents of the given file. This replacement happens when the PHP engine is
compiling your code, and not at the time it's executing it, unlike include(), which is evaluated first. The require() function
should be used for more static elements, leaving include() for the dynamic elements. Like include_once(), the
require_once() function checks to see if the given code has been inserted already and will not insert the code again, should
it already exist.

I tend to use the require function for things such as copyrights, static text, and other elements that contain no variables or
that rely on other scripts executing in order to realize their content. For example:

<HTML>
<HEAD><TITLE>Something</TITLE></HEAD>
<BODY>
[a lot of content]

<?
// insert copyright
require('/home/me/mycopyright');
?>

</BODY>
</HTML>

5
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
On the other hand, I often use include() to pull in a library of functions or some such, at the outset of my script:

<?
// get my function library
include('/home/me/myfunctions');

// do PHP things with my functions ?>

<HTML>
<HEAD><TITLE>Something</TITLE></HEAD>
<BODY>
[a lot of content]
</BODY>
</HTML>

The next logical question would be, "Where do the included or required files come from?" The short answer is, "Anywhere
on your system." However, if these are just code snippets, which sometimes contain important information such as data-
base connectivity functions with exact usernames or passwords, then obviously you won't want them sitting in your
document root for all the world to see.

You can put included or required files anywhere on your system, as long as the user under which PHP runs (www, nobody,
whatever) has read access to those files. You can also give them any file extension that you want, or none at all.

Using include() and require() to externalize those elements of your Web site that are omnipresent as well as subject to
change will make your architecture much easier to deal with when you have to do updates.

PHP and file system maintenance


PHP has numerous functions relating to your file system, allowing you not only to open files, but also display the contents
of directories, move files around, and much more. Many people even write Web-based file explorers in PHP.

First, a note regarding file paths: On Windows, you can use both the forward slash (/) and the backslash (\) in file paths,
whereas other operating systems use only the forward slash. For consistency's sake, these examples will use the forward-
slash method.

This sample script shows you a basic directory listing. Comments are inside the code, explaining each step:

<?
/* Put the full path to the directory you want to read, in a variable called
$dir_name */
$dir_name = "/home/me/";

/* Create a handle, the result of opening the given directory */


$dir = opendir($dir_name);

/* Start a text block, into which you'll place the list elements (your filenames) */
$file_list = "<ul>";

6
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
/* Using a while statement, read all of the elements in the open directory. If the
name of the file is not "." or "..", print the name in your list */

while ($file_name = readdir($dir)) {


if (($file_name != ".") && ($file_name != "..")) {
$file_list .= "<li>$file_name";
}
}

/* Finish up your bullet list */


$file_list .= "</ul>";

/* Close the open directory handle and end your PHP block*/
closedir($dir);

?>

<!-- Start your HTML -->


<HTML>
<HEAD>
<TITLE>Directory Listing</TITLE>
</HEAD>
<BODY>
<!-- Use PHP to print the name of the directory you read -->

<P>Files in: <? echo "$dir_name"; ?></p>

<!-- Use PHP to print the directory listing -->


<? echo "$file_list"; ?>

</BODY>
</HTML>

Voilà, you have a directory listing. Remember, to read the contents of a directory or a file (which you'll see in a moment),
the user under which PHP runs must have at least read permissions for that directory or file.

This next example shows how to copy a file:

<?
/* Put the full path to the file you want to copy in a variable called $original, and
the full path to the copied file in a variable called $copied */

$original = "/home/me/mydatabasedump";
$copied = "/archive/mydatabasedumo_1010";

/* use the copy() function to copy the original to the new, or die and print an error
*/
@copy($original, $copied) or die("Couldn't copy file.");

?>

7
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
This example script can be the first step in a rudimentary backup system; when the script is run, it copies a database dump
to a different location for safekeeping. With a modification to your crontab, you can execute this file at a time of day that
you choose; this requires no user intervention.

Assuming you have Lynx on your system, you can create a crontab entry to fire off Lynx and access this file. Accessing the
file will run the script and create the copied file. The example below will run the script at 5 a.m., and then shut Lynx back
down:

0 5 * * * [username] lynx -dump http://localhost/copyfile.php 1>/dev/null 2>&1

If you're running the CGI version of PHP, you can skip the Lynx part altogether, and reference the binary file:

0 5 * * * [username] php /path/to/copyfile.php 1>/dev/null 2>&1

A wealth of array functions


With PHP 4.0 comes more than 30 new array-related functions. Some of the more common functions let you determine if
something is in a given array or not, count the number of elements in an array, add or delete array elements, and sort array
elements.

If you have a large array and all you need to do is find out if a given value exists, you can use in_array() to return true or
false. The following will print "Not found in this array" because you're looking for "Albert" in the $namesArray, which does
not exist.

<?
$namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John");
$lookingFor = "Albert";

if (in_array($lookingFor, $namesArray)) {
echo "You've found it!";
} else {
echo "Not found in this array!";
}
?>

If you change the value of $lookingFor to "Mary", you will receive the "You've found it!" message, since "Mary" is part of
the $namesArray.

If you want to count the number of elements in an array, you can use the handy count() function:

<?
$namesArray = array("Joe", "Jane", "Bob", "Mary", "Paul", "Eddie", "John");
$count = count($namesArray);
?>

The value of $count is 7.

You can add elements to any array, either at the end or the beginning of an existing array. You can also use array_merge()
to create a new array consisting of the elements of two or more arrays. When merging, each array is tacked on in the order
that it is requested. If your arrays have an internal sort order already in place, you'll have to re-sort your new, merged
array.

8
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
Let's start with adding elements at the end of an existing array, using array_push():

<?
/* create the original array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* add to the original array */


array_push($fruitArray, "grape", "pineapple", "tomato");

/* list each element, with its key */


while (list($key,$value) = each($fruitArray)) {
echo "$key : $value<br>";
}
?>

This will display:


0 : apple
1 : orange
2 : banana
3 : kiwi
4 : pear
5 : grape
6 : pineapple
7 : tomato

The code is remarkably similar if you need to add some elements to the beginning of an array,. The only difference is the
function name: array_unshift() instead of array_push().

<?
/* create the original array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* add to the original array */


array_unshift($fruitArray, "grape", "pineapple", "tomato");

/* list each element, with its key */


while (list($key,$value) = each($fruitArray)) {
echo "$key : $value<br>";
}

?>

This will display:


0 : grape
1 : pineapple
2 : tomato
3 : apple
4 : orange
5 : banana
6 : kiwi
7 : pear

9
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
The array_merge() function smashes two or more arrays together.

<?
/* create the first array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* create the second array */


$vegArray = array("carrot", "green beans", "asparagus", "artichoke", "corn");

/* merge the arrays into one */


$goodfoodArray = array_merge($fruitArray, $vegArray);

/* list each element, with its key */


while (list($key,$value) = each($goodfoodArray)) {
echo "$key : $value<br>";
}
?>

This will display:


0 : apple
1 : orange
2 : banana
3 : kiwi
4 : pear
5 : carrot
6 : green beans
7 : asparagus
8 : artichoke
9 : corn

Now that you've added and merged arrays, let's run through the functions for deleting elements from arrays. You can delete
one element from the end of an array, using array_pop(). If you use array_shift(), you're deleting an element from the
beginning of an array. While you are in fact deleting the element from the array, this element is still available to you as a
variable, when you pop it or shift it from the existing array.

Try using array_pop() to delete a value from the end of an array:

<?
/* create an array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* pop something off the end */


$popped = array_pop($fruitArray);

/* list the contents of the new array, as well as the value you popped off */
while (list($key,$value) = each($fruitArray)) {
echo "$key : $value<br>";
}
echo "<br>and finally, in $popped: $popped";
?>

10
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
This will display:
0 : apple
1 : orange
2 : banana
3 : kiwi

and finally, in $popped: pear

Next, delete an element from the end of an array:

<?
/* create an array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* shift something from the beginning */


$shifted = array_shift($fruitArray);

/* list the contents of the new array, as well as the value you shifted off */
while (list($key,$value) = each($fruitArray)) {
echo "$key : $value<br>";
}

echo "<br>and finally, in $shifted: $shifted";


?>

This will display:


0 : orange
1 : banana
2 : kiwi
3 : pear

and finally, in $shifted: apple

There are several functions that assist you in sorting array elements, but I'll show you just the basic sort so that you
understand the process:

<?
/* create the original array */
$fruitArray = array("apple", "orange", "banana", "kiwi", "pear");

/* sort the array */


sort($fruitArray);

/* reset it so you can display it properly from beginning to end */

/* list each element, with its key */


while (list($key,$value) = each($fruitArray)) {
echo "$key : $value<br>";
}

?>

11
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
This will display:
0 : apple
1 : banana
2 : kiwi
3 : orange
4 : pear

Dynamic image creation


With a few installed third-party libraries and a bit of geometric skill, you can create and manipulate images on the fly with
PHP. Actually, you don't need all that much skill in geometry, because I flunked it in high school and can still create
images in PHP!

Before you can use the basic image creation functions, you need to install the GD library. To use the JPEG-related subset of
image creation functions, you need to install jpeg-6b. If you want to use Type 1 fonts in your images, you must install
t1lib.

There are a few more tweaks you that have to do to get your environment set up. First, install t1lib and get it out of the
way. Next, install jpeg-6b. Third, install the GD library. Do those three things in the order given here, because you need to
compile the GD library to make use of the jpeg-6b library, and if jpeg-6b isn't there first, the compilation won't be correct
and you'll run around chasing your tail for a while.

After these three libraries are installed, you need to reconfigure PHP. This would be one of those instances in which you're
glad you installed the DSO version of PHP. Do a make clean, then add the following into the current configuration directive:

--with-gd=[/path/to/gd]
--with-jpeg-dir=[/path/to/jpeg-6b]
--with-t1lib=[/path/to/t1lib]

Finish it up by doing a make, then make install. Restart Apache, do a phpinfo() to see if your new functionality shows up,
and you're on your way.

Depending on which version of the GD library you have installed, you may or may not be able to create GIFs or PNGs. Here's
the key: If you installed gd-1.6 or earlier, you can work with GIFs but not PNGs. If you installed gd-1.6 or later, you can
work with PNGs but not GIFs.

Creating a simple image requires a number of functions. I'll step through them one by one.

Output a header containing the MIME type of the image that you're creating--in this case, a PNG.

<?
header ("Content-type: image/png");

Create a variable to hold the blank image you'll make using ImageCreate(). This function requires a size in pixels. The
format is ImageCreate(x_size, y_size), so for a 250-by-250-pixel image, you'd use:

$newImg = ImageCreate(250,250);

12
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
Because your image is blank, you're going to want to fill it with a color of some sort. However, first you need to allocate a
name for a color by its RGB values, using the ImageColorAllocate() function. The format for this function is
ImageColorAllocate([image], [red], [green], [blue]). For a nice sky-blue color, you'd use:

$skyblue = ImageColorAllocate($newImg,136,193,255);

Next, you need to fill the image with this color using the ImageFill() function. There are actually several versions of
ImageFill(), such as ImageFillRectangle(), ImageFillPolygon(), and so on. For simplicity's sake, we'll just use ImageFill() to
do a flood file, with the following format:

ImageFill([image], [start x point], [start y point], [color])


ImageFill($newImg,0,0,$skyblue);

Lastly, you create the final image and destroy the graphics stream to free up memory and clean up after yourself:

ImagePNG($newImg);
ImageDestroy($newImg);
?>

Your code should look something like this:

<?
header ("Content-type: image/png");
$newImg = ImageCreate(250,250);
$skyblue = ImageColorAllocate($newImg,136,193,255);
ImageFill($newImg,0,0,$skyblue);
ImagePNG($newImg);
ImageDestroy($newImg);
?>

If you call this script skyblue.php and access it with your browser, you should see a 250-by-250-pixel, sky-blue PNG.

You can also use image creation functions to manipulate images, as in creating a thumbnail of a larger image.

Suppose you have an image from which you want to make a 35-by-35-pixel thumbnail. What you'll be doing is creating a
new image that is 35 by 35 pixels in size; making a graphics stream containing the contents of the original image; and
then placing a resized version of the original image into the new, empty graphic.

The key function used to achieve this is ImageCopyResized(), which requires a format like this: ImageCopyResized([new
image handle],[original image handle],[new image X], [new Image Y], [original image X], [original image Y], [new image
X], [new image Y], [original image X], [original image Y]);

13
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
Comments are in the code below:

<?
/* send a header so that the browser knows the content-type of the file */
header("Content-type: image/png");

/* set up variables to hold the height and width of your new image */
$newWidth = 35;
$newHeight = 35;

/* create a blank, new image of the given new height and width */
$newImg = ImageCreate($newWidth,$newHeight);

/* get the data from the original, large image */


$origImg = ImageCreateFromPNG("test.png");

/* copy the resized image. Use the ImageSX() and ImageSY functions to get the x and y
sizes of the orginal image. */
ImageCopyResized($newImg,$origImg,0,0,0,0,$newWidth,$newHeight,ImageSX($origImg),ImageSY($origImg));

/* create final image and free up the memory */


ImagePNG($newImg);
ImageDestroy($newImg);
?>

If you call this script resized.php and access it with your browser, you should see a 35-by-35-pixel thumbnail PNG.

PHP-based user authentication


If you are looking to password-protect on a per-script basis, you can use a combination of header() statements and the
$PHP_AUTH_USER and $PHP_AUTH_PW global variables to create a basic authentication scheme. The usual server-based
challenge/response sequence goes something like this:

1. The user requests a file from a Web server. If the file is within a protected area the server responds by sending out a 401
(Unauthorized User) string in the header of the response.

2. The browser sees that response and pops up the Username/Password dialog box.

3. The user enters a username and password in the dialog box, then clicks OK to send the information back to the server for
authentication.

4. If the username and password pair is valid, the protected file will be displayed to the user, and the validation will be
carried through for as long as the now-authenticated user is within the protected area.

A simple PHP script can mimic the HTTP authentication challenge/response system by sending the appropriate HTTP
headers that cause the automatic display of the username/password dialog box. PHP stores the information entered in the
dialog box in $PHP_AUTH_USER and $PHP_AUTH_PW. Using these variables, you can validate input against a username/
password list kept in a text file, database, or whatever your pleasure might be.

14
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
Note: The $PHP_AUTH_USER, $PHP_AUTH_PW, and $PHP_AUTH_TYPE global variables are available only when PHP is
installed as a module. If you're using the CGI version of PHP, you're limited to .htaccess-based authentication or database-
driven authentication using HTML forms to input the username and password, and PHP to validate matches.

This example shows the validation occurring against two hard-coded values, but the theory is exactly the same no matter
where your usernames and passwords are stored.

<?
/* Check for values in $PHP_AUTH_USER and $PHP_AUTH_PW */

if ((!isset($PHP_AUTH_USER)) || (!isset($PHP_AUTH_PW))) {

/* No values: send headers causing dialog box to appear */


header('WWW-Authenticate: Basic realm="My Private Stuff"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
exit;

} else if ((isset($PHP_AUTH_USER)) && (isset($PHP_AUTH_PW))){

/* Values contain some values, so check to see if they're correct */

if (($PHP_AUTH_USER != "validname") || ($PHP_AUTH_PW != "goodpassword")) {


// If either the username entered is incorrect, or the password entered
//is incorrect, send the headers causing dialog box to appear
header('WWW-Authenticate: Basic realm="My Private Stuff"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authorization Required.';
exit;
} else if (($PHP_AUTH_USER == "validname") || ($PHP_AUTH_PW == "goodpassword")) {
/* if both values are correct, print success message */
echo "<P>You're authorized!</p>";
}
}
?>

Remember, when you're using file-based protection, it's not blanket security on everything in the directory. That may be
obvious to most of you, but if your brain makes a connection between the pop-up box and protecting everything in the
given directory, you'll have to tweak your thought process a little bit.

PHP and COM


If you're an adventurous soul, and you're running PHP on Windows using the CGI, ISAPI or Apache module version, you can
access the COM functions. Now, explaining COM (Microsoft's Component Object Model) is left to Microsoft and very large
books. However, for a little taste of what COM can do, here's a common (no pun intended) code snippet.

This code snippet uses PHP to open Microsoft Word in the background, open a new document, type some text, save the
document, and close the application:

15
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
<?
// create a reference to a new COM component (Word)
$word = new COM("word.application") or die("Can't start Word!");

// print the version of Word that's now in use


echo "Loading Word, v. {$word->Version}<br>";

// set the visibility of the application to 0 (false)


// to open the application in the forefront, use 1 (true)
$word->Visible = 0;

// create a new document in Word


$word->Documents->Add();

// add text to the new document


$word->Selection->TypeText("Testing 1-2-3...");

//save the document in the Windows temp directory


$word->Documents[1]->SaveAs("/Windows/temp/comtest.doc");

// close the connection to the COM component


$word->Quit();

// print another message to the screen


echo "Check for the file...";
?>

Suppose you're running an intranet Web site that has data stored in Microsoft SQL Server, and your users need that data in
Excel format. You can have PHP run the necessary SQL queries and format the output, then use COM to open Excel, dump
the data stream into it, and save the file on the user's desktop.

PHP and Java


Another fancy bit of PHP functionality is its ability to invoke methods of existing Java objects, letting you integrate PHP
into existing Java-based applications. This ability is pretty snazzy if you're pushing PHP in your workplace and the answer
you get is, "But everything's Java here."

To utilize this functionality, you need to have a Java Virtual Machine (JVM) installed on the server. If you install (or have
installed) JDKs from Sun, Kaffe, IBM, or Blackdown, you'll be up to speed.

When you configure PHP, you'll need to add --with-java to the configuration directives, then modify some elements of your
php.ini file. The php.ini modifications are usually along the lines of adding the following:

[Java]
java.library.path=/path/to/library
java.class.path=/classpath/
extension_dir=/path/to/extensions
extension=libphp_java.so

Please note, however, that these modifications depend on your type of installation. You should read the README in the
ext/java directory in your PHP installation directory to learn more about configuring for Java functionality.

16
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!
10 PHP Scripting Tips (cont’d)
Here's a very simple example of a PHP script creating a new Java object. The script will then access and print to the screen
certain Java properties. It's about as exciting as the COM example, but it gives you an idea of the possibilities.

<?
$system = new Java("java.lang.System");
echo "<P>Java version = " . $system->getProperty("java.version") . "<br>";
echo "Java vendor = " . $system->getProperty("java.vendor") . "</p>";
?>

If you have Java knowledge, by all means jump in and help the developers with this project. These types of integration
capabilities will be key in the future growth and acceptance of PHP, so the more people working on these types of things,
the better.

PHP and XML


PHP contains an optional XML extension that supports the Expat parser. The XML-related functions in PHP let you create a
parser to handle valid XML documents. If you are using a version of Apache later than 1.3.7, you don't need any additional
libraries. All you need to do is configure PHP --with-xml.

There are several good examples of creating a PHP-based XML parser in the PHP Manual. Additionally, the New Riders book
Web Application Development with PHP 4.0 includes a good overview of using XML with PHP, and one of the authors of
that book has also written a great tutorial at Zend.com

Just as with Java and COM support, XML support in PHP is in its infancy but growing rapidly. If you have experience with
Expat or LibXML, please jump in and lend your expertise.

17
© 2001 thickbook.com. Please ask before reprinting. No steal, no sue. Thanks!

You might also like