Skip to main content

Beginning PHP4

Beginning PHP4

Wankyu Choi, Allan Kent, Chris Lea, Ganesh Prasad, Chris Ullman

ISBN: 978-0-764-54364-7

Nov 2000

816 pages

Select type: Paperback

Product not available for purchase


What is this book about?

PHP is a rapidly growing web technology which enables web designers to build dynamic, interactive web applications, incorporating information from a host of databases, and including features such as e-mail integration and dynamically generated images. PHP4 added tons of features to make web application development even easier, and this book will show you how to make the most of the language's powerful capabilities.

This book is a complete tutorial in PHP's language features and functionality, beginning with the basics and building up to the design and construction of complex data-driven websites. Fully working examples in the book include a directory-style web search engine, a mailing list management system, a web-based file editor, and a graphical online shopping mall guidebook.

What does this book cover?

Here are just a few of the things you'll find covered in this book:

  • Complete tutorial in the PHP language
  • Installation guide and troubleshooting tips
  • Introduction to relational databases and MySQL
  • Practical worked examples throughout, including a detailed case study
  • All code written for both Windows and UNIX systems
  • Detailed language reference included

Who is this book for?

Anybody who knows HTML can use this book. If you've done any programming, that will be useful, but it's not a requirement. You can run all of the code on either a Windows or UNIX (e.g., Linux) system, and the book explains how to set up a web server and database in both of these environments.


Chapter 1. Installation.

Chapter 2. Writing PHP Programs.

Chapter 3. Getting Data from the Client.

Chapter 4. Decision Making.

Chapter 5. Loops and Arrays.

Chapter 6. Organizing Your Code.

Chapter 7. Handling and Avoiding Errors.

Chapter 8. Working With the Client.

Chapter 9. Objects.

Chapter 10. File and Directory Handling.

Chapter 11. PHP Database Connectivity.

Chapter 12. Retrieving Data from MySQL Using PHP.

Chapter 13. Manipulating Data in MySQL Using PHP.

Chapter 14. XML.

Chapter 15. E-Mail Handling.

Chapter 16. Generating Graphics.

Chapter 17. Case Study A URL Directory Manager.

Appendix A. ODBC.

Appendix B. PHP Functions.

Function Index.


Download Linux code files for this book Download
Additional files for using ODBC databases with PHP4 Download
Download Windows code files for this book Download
0Code missing ,

The code quoted on page 610 is missing the keyword this from several of it's select case statements. The code should read:

case _age :
??????isValid = this.isValidAge(elementValue);

case _password :
??????isValid = this.isValidPassword(elementValue);

case _telephone :
??????isValid = this.isValidTelephoneNum(elementValue);

0Register Globals ,

register_globals and PHP security.

There's a very important thing that we must comment about the code in this book and future PHP code regarding a configuration variable called register_globals

What is register_globals?

register_globals is a PHP configuration variable that can be turned 'on' or 'off' from your PHP configuration file. When register_globals is turned 'on' ??? form, server, and environment variables are converted to global variables by the PHP engine. In fact, you should be very familiar with this feature , if you have an HTML form with an input element such as:

<input type= text name= username />

When you submit the form, you can use, validate, or do whatever you want with a variable $username that will have the data the user entered in the form's text field. This is because the form GET/POST variable was converted to a PHP variable in the global namespace: a global variable.

You may think that this is a nice feature and that you don't want to turn it 'off', but there're potential security problems when register_globals is turned 'on'. We can summarize the problem as: users can alias PHP script variables changing the normal execution of the script .

Let's suppose we validate the username in our PHP script in this way:

if($username= master ) {

?? $admin=true;


if($admin) {

??// Code for administrator features here


While the code may look in offensive, it's wrong, the user can pass not only username but admin in the form and then gain administrator privileges without knowing the username or password or whatever he would have need to know. Of course, you could have written the above code different and have no problem at all but the potential problem exists and it may be dangerous. 90% of the security problems found in PHP applications are a derivative from aliasing script variables when register_globals is turned 'on'.

If you do like register globals turned 'on', or you do need this setting 'on' because you have a lot of code written relying on this setting, you have to check your code and program carefully to avoid security problems. You can use the following checklist:

Programming safe with register_globals 'on':

  • Initialize all of your script variables at the beginning of the script. (this will overwrite a user variable that was intended to alias one of your variables)
  • Never rely on user input, validate all the data entered from the user
  • Check user data for length before using it (avoiding potential buffer overflow exploits)
  • Never store important information on cookies (the user can change it, for example userIds), use sessions that are stored on the server instead.
  • Be extremely careful with user uploads, use the is_uploaded_file() function to check if the file was uploaded to the server or not.
  • Always update your PHP version to the latest stable version to gain the security of the latest patches.
  • If register_globals is 'off' you need a way to access user entered data, from PHP 4.x you have new special arrays: 

In other words, all the information that is coming from the user, and that from a security point of view, cannot be trusted. $_SESSION, contains HTTP variables registered by the session module. So if we have a form with a $username variable and we submit the form using post you can use: 

The use of $_POST is not an advantage but a way to program when register_globals is turned 'off', in some installations you will find this setting 'on' and on some others it will be 'off' so your code will be more portable if you program assuming that register_globals is 'off'. 

How to check for

Use the phpinfo() function and check the PHP core section; you can find the status of the register_globals there.

The code in this book was written assuming that register_globals is 'on', you may find some pieces of code that will work with register_globals 'off' but some may not. If you want to port the code to work with register_globals'off', you can attack scripts that process forms and change the use of ?? $foo variables to $_GET[ foo ] or $_POST[ foo ] accordingly.

A normal way to do it is to use :


at the beginning of the script converting all the user entered variables to global variables in your script, with this modification you won't need to change the rest of the script.


8Typo in the URL ,

The slashes are incorrect in the URI at the top of the page. It says http:\\, but should be

13More on PHP4 Installation on Win98/Me ,

It appears that some users of Win98 and Win Me are experiencing great difficulty getting PHP4 to run using PWS. An Error 500 messge seems to be a common factor with these problems.

A common solution appears to be to try a different web server, such as Apache or BadBlue. For more on installing Apache/PHP4, see:

For more on BadBlue:

(Many thanks to Ray Carroll and Jordan Savage for this useful advice)

17Installing PHP4 on Win 98,

At the time of going to press, was the place to go to get a Windows download. However, now you can go to and obtain a distribution for all platforms. To install just click on the php-version-msi.exe file and it will automatically do a custom install for you. 1) Note that the download from doesnt contain php.ini with Win 98, but does contain php.ini-dist and php.ini-optimized . Rename one of these as php.ini and then edit it according to the book. Updated 11/3/03: 2) Note that the regedit file must have a carriage return after the final line of code to work. You can also check that the registry has been altered if you wish:
-go to the start menu and click run -type regedit in the box and press enter -in the resulting window, navigate through the tree structure to HKEY_LOCAL_MACHINE\System\CurrentControlSet
\Services\W3SVC\Parameters\Script Map The Script Map folder should contain an item called .php with data value C:\php\sapi\php4isapi.dll (or whatever the path is to this .dll on your system). If it just contains an item Default , whose value is not set, do the following: -in the right hand window, right click your mouse and choose New | String Value -give it the name .php and press enter -double click on this key and enter the path to php4isapi.dll in the Value Data field and press OK -restart your machine and all should be well.

17Note about extension_dir ,

On page 17 you have to edit the php.ini file. The path you have to set with the parameter extension_dir causes problems if a directory name is longer than 8 characters. However, you can use the ~ notation or to quote the path if you use directory names longer than 8 characters. For example: extension_dir=C:\Progra~1\Php4 extension_dir= C:\Program files\Php4\extensions . (Many thanks to Stephen Tittel for this info)

17Setting up PHP4 to pass variables between scripts,

In order to pass variables between PHP scripts (as shown in the text.html/php Try-It-Out on p77) you must make sure that

register_globals = On

in your php.ini file. Remember that if you adjust anything in the php.ini file, in order to apply changes, you must reboot.

18Launching Win 98 Personal Web Manager ,

To bring up the PWM window in Win 98 you can navigate through the Start menu to:

Start|Programs|Accessories|Internet Tools|Personal Web Server|Personal Web Manager

23Getting PHP4 up and running on IIS ,

Comment from Allan J Horwitz (

I know many of us have had
problems getting it to work so here's something that I tried and it now works
like a champ. In your book Beginning PHP4, there is a great example of how
to install php4 on IIS. One detail, however, is left out (I believe). They
forget to mention that when making up a name for your ISAPI filter, that you
should NOT use the same name as the directory that you store PHP in. What I did (just playing around on a lark) was to name my ISAPI filter PHP4 since I don't have a PHP4 directory anywhere on my system. When I did that,
everything worked without a hitch. So my pearl of wisdom is that you should
give your ISAPI filter a name like PHP405 (or whatever, as long as it is not one of your directories) and everything should work fine. This should save a lot of people the headache of getting Error 403 (or is it 404?) saying it can't find the program.

60missing semicolons,

The code snippet:

$Bread = 1.5
$Milk = 0.8
$DiscountCoupon = 0.5
$ShoppingTotal = $Bread + $Milk - $DiscountCoupon;

is missing terminating semicolons for the first 3 lines:

$Bread = 1.5; //added semicolon
$Milk = 0.8; //added semicolon
$DiscountCoupon = 0.5; //added semicolon
$ShoppingTotal = $Bread + $Milk - $DiscountCoupon;

(Thanks to Ming-Cheng Hsu)

63Code Error ,

In Constants section, the code line:

$IndependenceDay = 4th July ;

should have a normal (not a superscripted) th

63Code error,

Code error
There is a missing <br> tag in the code snippet following the first paragraph in the Constants section. The code snippet should read as follows:

$author = William Shakespeare ;
echo $author. <br> ;
$author= Herman Melville ;
echo $author;
64 In "The Define Keyword" section, the code line:,

define( INDEPENDENCEDAY , 4th July );

should have a normal (not a superscripted) th

65Missing Semicolons,

There are missing terminating semicolons for the following code snippet:

$EngineType = 2.0L ; //semi-c added
$TaxRate = 3; //and here
$TaxPaid = $EngineType * $TaxRate; //and here (Thanks to Ming-Cheng Hsu)
76Grammatical Error ,

The first sentence in the second paragraph of this page reads as follows:
???Which method you use depends on what you want to the form to do.???

It should be read as :

???Which method you use depends on what you want the form to do.???

105Typo on line 1 ,

The first line on page 105 has an extra and which is not required. The sentence that reads Our final line will return a 0 if we put in a value between 0 and 19 for the user's age, and 1 if we supply a value between 20 and 29, a 2 if we supply a value between and 30 and 39, and so on.... should read as below:

...Our final line will return a 0 if we put in a value between 0 and 19 for the user's age, and 1 if we supply a value between 20 and 29, a 2 if we supply a value between 30 and 39, and so on...
117Typo in code,
if ($Question1== Lisbon ) echo You are correct, Lisbon is the right answer ;
if ($Question1!= Lisbon ) echo You are incorrect, Lisbon is not the right answer ;

should be:

if ($Question1== Lisbon ) echo You are correct, Lisbon is the right answer ;
if ($Question1!= Lisbon ) echo You are incorrect, Lisbon is the right answer ;
123Usage of OR operator ,

The Section on Combining Operators has the wrong usage of the OR operator. The operator AND should be used instead. Also, an opening paranthesis is missing in the condition part of the if statement. The following is the correct usage:

if (($day != Monday )
AND ($day != Tuesday )
AND ($day != Wednesday )
AND ($day != Thursday )
AND ($day != Friday )
AND ($day != Saturday )
AND ($weather != Rainy )) echo ( off to the beach );
125Wrong filename in Try-It-Out ,

Open up board.html in your browser and fill in some information:

should be:

Open up quote.html in your browser and fill in some information (Thanks to Rebecca Wells)

140Incorrect usage of ,

The code snippet in the Form Validation section uses a break statement. break only works in conjunction with switch statement, and not with if statement.

if ($Age<1 or $Age>120)
   echo Incorrect Age value entered ;
183Code Error in Try It Out,

There are some missing semicolons in the script for the Try-It-Out Combining arrays in a practical example in Chapter 5.

In the while loop in exam.php, the following lines should be terminated with semicolons as shown:

echo <BR><BR> ; // added semicolon
</SELECT> ; // added semicolon

(Thanks to John Thorpe and David Leong for these errata)

249errata ,

In the box explaining listing Symbols and Matches, the regexp [^@\.] should be [^@ \.], i.e., there must be a space in there as in the code. (thanks to Rick Gawlik)

266inconsistency in bill.php, Ch8 ,

echo TOTAL BILL = $ . $total . <BR> ;

should be

echo TOTAL BILL = $$total<BR> ;
to be consistent with the explanation in the How It Works section (although both lines of code give the correct output).

(Thanks to Joe LoMoglio)

275Bug in hangman.php ,

The following line causes hangman.php to randomly choose a new word everytime the program loops, because of white spaces which cause the query string to be misread.

$links .= <A HREF=\ $PHP_SELFletters=$letters$var
&word_number=$word_number\ >

Putting the string together corrects the problem.

(This has been corrected in the latest code download. Thanks to Paul Agin)

354error in code for editor.php,

The lines of code at the top of the page should be interchanged, to

$filepath = $dir/$filename ;
if(!$is_new) $filebody = $implode( ,file($filepath));

(This has been corrected in the latest code download. Thanks to Peter Bakos)

356error in code in editor.php,

>in save_file() function

in the code:

echo &ltSCRIPT&gtself.location.href='$PHP_SELF?dir=$dir&
filename=$filename';</SCRIPT> ;

this should be: (note no line break)

echo &ltSCRIPT&gtself.location.href='$PHP_SELF?dir=$dir&filename=$filename';</SCRIPT> ;
(This has been corrected in the code download)

357error in code in editor.php ,

>in editor_page() function

in the book code:

editor_form( $dir/$filename , $is_new);

this should be:

(This has been corrected in the latest code download)

369Error in File Upload Try-It-Out ,

The line:

if(isset(!$WINDIR) && !@unlink($userfile))
die ( Can't delete the file $userfile_name. );

should read:

if(!isset($WINDIR) && !@unlink($userfile))
die ( Can't delete the file $userfile_name. );

(note the ! has been shifted to the beginning of the isset() function).
(This has been corrected in the latest code download)

371bugs in webeditor/editor/navigator scripts,

In all of these scripts problems have been caused because the regexp comparison for filepaths:

ereg($default_dir, $dir)

will not work properly for Windows machines due to the trailing slashes in Windows filepaths, which PHP interprets as escape characters.

To get around this, wherever the code in these scripts are supposed to have the line:

if (empty($dir) || !ereg($default_dir, $dir)) {

this has been replaced by:

if(!empty($dir)) $dir_test=substr($dir, 0, $def_length);

if(empty($dir) ||
($dir_test!=$default_dir)) {

instead. Note also, to stop PHP automatically escaping single quotes in strings with a trailing slash, you should switch off the magic_quotes_gpc environmental variable in your php.ini file.

405Code Error in , is missing a closing PHP tag ie ?> at the end of the script.

407Missing Semicolon ,

There should be a semi-colon at the end of the MySQL command

mysql> DROP DATABASE sample_db

mysql> DROP DATABASE sample_db; (thanks to Nick Bramwell.)

411Code Error in MySQL Query ,

In the instructions to create the access_log table in MySQL, the
comma at the end of the line:

PRIMARY KEY (userid, page),

should be omitted.

(Thanks to John Thorpe)

443A note about javascript functions ,

Some problems have been encountered by users when attempting to run PHP scripts incorporating javascript calls (which take the format javascript:function(), for example javascript:open_window()). It is important to note that the call itself must contain no line breaks, or the call will not work. Note that the code download has been corrected for this problem.

479code errors in access_logger.php, Ch13 ,

These errors are in the else statement starting on line 76:

else {
$query = SELECT userid FROM $access_log_tablename
//1st error...
WHERE page = '$userid'
AND userid = '$userpassword' ;
//end of first error
$result = mysql_query($query);
$query = INSERT INTO $access_log_tablename VALUES
//2nd error...
('$PHP_SELF', '$userid', 1, NULL) ;
//end of 2nd error
else $query = UPDATE $access_log_tablename

The 1st error lines should be replaced with:

WHERE page = '$PHP_SELF' AND userid = '$userid' ;

while the 2nd error line should be:


(Thanks to Robin Mukherjee)

484Code error ,

In the userman.php on page 484 (line 170 of downloaded code), comma is needed after ('$userpassword').


if(!empty($userpassword)) {

$field_str .= userpassword = password('$userpassword') ;

if(!empty($userpassword)) {

$field_str .= userpassword = password('$userpassword'), ;

577Code Error ,

In How It Works section related to mall2.php, we have line

$image = ImageCreateFromPNG( groundfloor.jpg );

This should reference the file groundfloor.png instead.

589Code Error,

Line of code in chapter 17 just before Palette Limitations heading:

$icon = ImageCreateFromPNG( pin.png );

Here $icon should be replaced with $image .

664Code Error in Case Study ,

top of page 664 (in edit_new() function of php_directory.php):


send_mail is a variable and therefore should have a $ in front. ie it should be: