Copy of materials from W.J.Gilmore book (EN)

Listing1-1.php   Listing1-2.php   Listing1-3.php   Listing1-4.php   Listing1-5.php   Listing4-1.php   Listing4-2.php   Listing4-3.php   Listing4-4.php   Listing4-5.php   Listing4-6.php   Listing4-7.phps   Listing4-8.phps   Listing5-1.php   Listing5-2.php   Listing6-1.phps   Listing6-2.php   Listing6-3.php   Listing6-4.phps   Listing6-5.phps   Listing6-6.php   Listing6-7.phps   Listing6-8.php   Listing6-9.php   Listing6-10.php   Listing6-11.phps   Listing6-12.phps   Listing6-13.phps   Listing6-14.phps   Listing7-1.txt   Listing7-2.html   Listing7-3.php   Listing7-4.php   Listing7-5.php   Listing7-6.php   Listing7-7.php   Listing7-9.php   Listing7-10.php   Listing8-1.php   Listing8-2.php   Listing8-3.php   Listing9-1.phps   Listing9-2.phps   Listing9-4.php   Listing9-8.php   Listing9-9.php   Listing9-11.php   Listing9-15.php   Listing10-1.html   Listing10-2.html   Listing10-3.php   Listing10-4.php   Listing10-5.php   Listing10-6.php   Listing10-7.php   Listing10-8.php   Listing10-9.php   Listing11-1.php   Listing11-2.html   Listing11-3.php   Listing11-4.php   Listing11-5.php   Listing11-6.php   Listing11-7.php   Listing11-8.php   Listing11-11.php   Listing11-12.html   Listing12-1.html   Listing12-2.phps   Listing12-3.phps   Listing12-4.phps   Listing12-5.phps   Listing12-6.php   Listing12-7.php   Listing12-11.php   Listing12-12.php   Listing13-1.php   Listing13-2.php   Listing13-3.php   Listing13-4.php   Listing13-5.php   Listing13-6.php   Listing13-7.php   Listing13-8.php   Listing13-9.php   Listing13-10.php   Listing13-11.php   Listing14-1.xml   Listing14-3.php   Listing15-1.php   Listing15-2.php   Listing15-3.php   Listing15-4.php   Listing15-5.php   Listing15-6.php   Listing15-7.php   Listing16-1.phps   Listing16-2.php   Listing16-3.php   Listing16-4.php   Listing16-5.txt   Listing16-6.php   Listing16-7.php  

File:Listing1-1.php


<?

// Set a few variables
$site_title = "PHP Recipes";
$bg_color = "white";
$user_name = "Chef Luigi";
?>

<html>
<head>
<title><? print $site_title; ?></title>
</head>
<body bgcolor="<? print $bg_color; ?>" >
<?
// Display an intro. message with date and user name.
print "
PHP Recipes | "
.date("F d, Y")." <br>
Greetings, $user_name! <br>
"
;
?>
</body>
</html>

File:Listing1-2.php


<html>

<head>
<title>Basic PHP/HTML integration</title>
</head>
<body>
<?
// Notice how HTML tags are included within the print statement.
print "<h3>PHP/HTML integration is cool.</h3>";
?>
</body>
</html>

File:Listing1-3.php


<title>PHP Recipes | <? print (date("F d, Y")); ?></title>

File:Listing1-4.php


<html>

<head>
<title>PHP Recipes | <? print (date("F d, Y")); ?></title>
</head>
<?
$big_font
= "h3";
?>
<body>
<? print "<$big_font>PHP Recipes</$big_font>"; ?>
</body>
</html>

File:Listing1-5.php


<html>

<head>
<title>
<?
print "Another PHP-enabled page";
$variable = "Hello World!";
?>
</title></head>
<body>
<? print $variable; ?>
</body>
</html>

File:Listing4-1.php


<?


function display_footer($site_name) {

         function
display_copyright($site_name) {
              print
"Copyright &copy ". date("Y"). " $site_name. All Rights Reserved.";
         }

          print
"<center>
          <a href = \"\">home</a> | <a href = \"\">recipes</a> | <a href = \"\">events</a><br>
          <a href = \"\">tutorials</a> | <a href = \"\">about</a> | <a href = \"\">contact us</a><br>"
;

         
display_copyright($site_name);

         print
"</center>";

}

$site_name = "PHP Recipes";



display_footer($site_name);
display_copyright($site_name);
?>

File:Listing4-2.php


<?


$price
= 24.99;
$tax = .06;

function
calculate_cost($tax, $price) {

     
$sales_tax = $tax;
     return
$price + ($price * $sales_tax);

}

// Notice how calculate_cost() returns a value.
$total_cost = calculate_cost ($tax, $price);
// round the cost to two decimal places.
$total_cost = round($total_cost, 2);

print
"Total cost: $".$total_cost;
// $total_cost = 26.49

?>

File:Listing4-3.php


<?


$cost
= 456.22;
$limit = 1000.00;

function
check_limit($total_cost, $credit_limit) {

     if (
$total_cost > $credit_limit) :
          return
0;
     endif;

     return
1;

}

if (
check_limit($cost, $limit)) :
// let the user keep shopping
print "Keep shopping!";
else :
print
"Please lower your total bill to less than $".$limit."!";
endif;

?>

File:Listing4-4.php


<?



// wine for which best years will be displayed
$label = "merlot";

// This function merely makes use of various arrays and a variable variable to return multiple values.
function best_years($label) {

     
$merlot = array("1987", "1983", "1977");
     
$zinfandel = array("1992", "1990", "1989");

     return $
$label;

}
// a list() is used to display the wine's best years.
list ($yr_one, $yr_two, $yr_three) = best_years($label);

print
"$label had three particularly remarkable years: $yr_one, $yr_two, and $yr_three.";

?>

File:Listing4-5.php


<?


function summation ($count) {

    if (
$count != 0) :

        return
$count + summation($count-1);

    endif;

}


$sum = summation(10);

print
"Summation = $sum";

?>

File:Listing4-6.php


<?


// italian welcome message.
function italian() {
     print
"Benvenuti al PHP Recipes.";
}

// english welcome message
function english() {
     print
"Welcome to PHP Recipes.";
}

// set the user language to italian
$language = "english";

// execute the variable function
$language();

?>

File:Listing4-7.phps


<?

// file: array_sorting.inc
// purpose: library containing functions used for sorting arrays.
// date: July 17, 2000

function merge_sort($array, $tmparray, $right, $left) {
. . .
}

function
bubble_sort($array, $n) {
. . .
}

function
quick_sort($array, $right, $left) {
. . .
}

?>

File:Listing4-8.phps


<?

// this assumes that the array_sorting.inc library resides in the same folder as this script.
include("array_sorting.inc");

// you are now free to use any function in array_sorting.inc
$some_array = array(50, 42, 35, 46);

// make use of the bubble_sort() function

$sorted_array = bubble_sort($some_array, 1);

?>

File:Listing5-1.php


<?


// declare associative array of countries and languages
$languages = array ("Country" => "Language",
                    
"Spain" => "Spanish",
                    
"USA" => "English",
                    
"France" => "French",
                    
"Russia" => "Russian");

// begin new table
print "<table border=1>";

// move pointer to first element position
reset ($languages);
// extract the first key and element
$hd1 = key ($languages);
$hd2 = $languages[$hd1];

// Print first key and element as table headers
print "<tr><th>$hd1</th><th>$hd2</th></tr>";

next($languages);

// Print table rows including keys and elements of array
while ( list ($ctry,$lang) = each ($languages)) :
     print
"<tr><td>$ctry</td><td>$lang</td></tr>";
endwhile;

// close table
print "</table>";

?>

File:Listing5-2.php


<?


$vocab
= array("Socrates","Aristophanes", "Plato", "Aeschylus", "Thesmophoriazusae");

function
compare_length($str1, $str2) {

$length1 = strlen($str1);
$length2 = strlen($str2);

if (
$length1 == $length2) :

    return
0;

elseif (
$length1 < $length2) :

    return -
1;

else :

    return
1;

endif;

}


usort($vocab, "compare_length");

while (list (
$key, $val) = each ($vocab)) {

    echo
"$val<br>";

}


?>

File:Listing6-1.phps


class Class_name {

    var $attribute_1;
    ...
    var $attribute_N;

    function function1() {
    ...
    }
    ...
    function functionN() {
    ...
    }

} // end Class_name

File:Listing6-2.php


<?

class Webpage {
    var
$bgcolor;

    function
Webpage($color) {
        
$this->bgcolor = $color;
    }
}

// call the Webpage constructor
$page = new Webpage("brown");
?>

File:Listing6-3.php


<?


class Vehicle {
    var
$model;
    var
$current_speed;

    function
setSpeed($mph) {
        
$this->current_speed = $mph;
    }

    function
getSpeed() {
        return
$this->current_speed;
    }

}
// end class Vehicle

class Auto extends Vehicle {
    var
$fuel_type;

    function
setFuelType($fuel) {
        
$this->fuel_type = $fuel;
    }

    function
getFuelType() {
        return
$this->fuel_type;
    }

}
// end Auto extends Vehicle

class Airplane extends Vehicle {
    var
$wingspan;
    
    function
setWingSpan($wingspan) {
        
$this->wingspan = $wingspan;
    }

    function
getWingSpan() {
        return
$this->wingspan;
    }
    
}
// end Airplane extends Vehicle

?>

File:Listing6-4.phps


<?


class Vehicle {
    
Attribute declarations...
    
Method declarations...
}

class
Land extends Vehicle {
    
Attribute declarations...
    
Method declarations...
}

class
Car extends Land {
    
Attribute declarations...
    
Method declarations...
}

$nissan = new Car;

?>

File:Listing6-5.phps


<?


class Vehicle {
    
Attribute declarations...

    function
Vehicle() }
        die (
"Cannot create Abstract Vehicle class!");
    }    

    
Other Method declarations...
}

class
Land extends Vehicle {
    
Attribute declarations...

    function
Land() }
        die (
"Cannot create Abstract Land class!");
    }    

    
Other Method declarations...
}

class
Car extends Land {
    
Attribute declarations...
    
Method declarations...
}

$nissan = new Car;

?>

File:Listing6-6.php


<?


class Page {
     var
$bgcolor;
     var
$textcolor;    

     function
Page() {
          
// Determine the number of arguments passed in, and create correct method name
          
$name = "Page".func_num_args();
          
// Call $name with correct number of arguments passed in
          
if ( func_num_args() == 0 ) :
               
$this->$name();
          else :
               
$this->$name(func_get_arg(0));
          endif;
     }

     function
Page0() {
          
$this->bgcolor = "white";
          
$this->textcolor = "black";    
          print
"Created default page";
     }

     function
Page1($bgcolor) {
          
$this->bgcolor = $bgcolor;
          
$this->textcolor = "black";            
          print
"Created custom page";
     }
}
$html_page = new Page("red");

?>

File:Listing6-7.phps


<?

...
class
Airplane extends Vehicle {
    var
$wingspan;

    function
setWingSpan($wingspan) {
        
$this->wingspan = $wingspan;
    }

    function
getWingSpan() {
        return
$this->wingspan;
    }

}
// end Airplane extends Vehicle

$cls_methods = get_class_methods(Airplane);
// $cls_methods will contain an array of all methods
// declared in the classes "Airplane" and "Vehicle"


?>

File:Listing6-8.php


<?


class Vehicle {
     var
$model;
     var
$current_speed;
}

class
Airplane extends Vehicle {
     var
$wingspan;
}

$a_class = "Airplane";

$attribs = get_class_vars($a_class);
// $attribs = array ( "wingspan", "model", "current_speed")

?>

File:Listing6-9.php


<?


class Vehicle {
     var
$wheels;
}

class
Land extends Vehicle {
     var
$engine;
}

class
car extends Land {
     var
$doors;

     function
car($doors, $eng, $wheels) {
          
$this->doors = $doors;
          
$this->engine = $eng;
          
$this->wheels = $wheels;
     }

     function
get_wheels() {
          return
$this->wheels;
     }

}

$toyota = new car(2,400,4);

$vars = get_object_vars($toyota);

while (list(
$key, $value) = each($vars)) :

    print
"$key ==> $value <br>";

endwhile;
// displays:// doors ==> 2
// engine ==> 400
// wheels ==> 2

?>

File:Listing6-10.php


    <?

class Vehicle {
var
$motor;
     }

     class
Land extends Vehicle {
          var
$fourWheel;
          function
setFourWheelDrive() {
               
$this->fourWeel = 1;
          }
     }

     
//  create object named $car
     
$car = new Land;

     
// if method "fourWheelDrive" is a part of classes "Land" or "Vehicle",
     // then the call to method_exists will return true; Otherwise false will be returned.
     // Therefore, in this case, method_exists() will return true.

     
if (method_exists($car, "setfourWheelDrive")) :
          print
"This car is equipped with 4-wheel drive";
     else :
          print
"This car is not equipped with 4-wheel drive";
     endif;
?>

File:Listing6-11.phps


<?


class Vehicle {
var
$motor;
}

class
Land extends Vehicle {
var
$wheels;
}

// create object named $car
$car = new Land;

// $class_a is assigned "Land"
$class_a = get_class($car);

?>

File:Listing6-12.phps


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}

// create object named $car
$car = new Land;

// $parent is assigned "Vehicle"
$parent = get_parent_class($car);
?>

File:Listing6-13.phps


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}
$auto = new Land;
// $is_subclass receives the value "true"
$is_subclass = is_subclass_of($auto, "Vehicle");

?>

File:Listing6-14.phps


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}

$declared_classes = get_declared_classes();
// $declared_classes = array("Vehicle", "Land")

?>

File:Listing7-1.txt


Recipe: Pastry Dough

1 1/4 cups all-purpose flour
3/4 stick (6 tablespoons) unsalted butter, chopped
2 tablespoons vegetable shortening
1/4 teaspoon salt
3 tablespoons water

File:Listing7-2.html


<html>

<head>
<title>Breaking News - Science</title>
<body>
<h1>Alien lifeform discovered</h1><br>
<b>August 20, 2000</b><br>
Early this morning, a strange new form of fungus was found growing in the closet of W. J. Gilmore's old apartment refrigerator. It is not known if powerful radiation emanating from the tenant's computer monitor aided in this evolution.
</body>
</html>

File:Listing7-3.php


<?

$fh
= fopen("science.html", "r");

while (!
feof($fh)) :
    print
fgetss($fh, 2048);
endwhile;

fclose($fh);
?>

File:Listing7-4.php


<?

$fh
= fopen("science.html", "r");
$allowable = "<br>";
while (!
feof($fh)) :
    print
fgetss($fh, 2048, $allowable);
endwhile;
fclose($fh);
?>

File:Listing7-5.php


<?

$file_array
= file( "pastry.txt" );

while ( list(
$line_num, $line ) = each( $file_array ) ) :
     print
"<b>Line $line_num:</b> " . htmlspecialchars( $line ) . "<br>\n";
endwhile;
?>

File:Listing7-6.php


<?

function getthehost($host,$path) {
     
// open the host
     
$fp = fsockopen($host, 80, &$errno, &$errstr, 30);
     
// take control of server timeout
     
socket_set_blocking($fp, 1);
     
// send the appropriate headers
     
fputs($fp,"GET $path HTTP/1.1\r\n");
     
fputs($fp,"Host: $host\r\n\r\n");
     
$x = 1;
     
// grab a bunch of headers
     
while($x < 10) :
          
$headers = fgets($fp,4096);
        print
$headers;
          
$x++;
     endwhile;

     
// close the filepointer.
     
fclose($fp);
}

getthehost("www.apress.com", "/");
?>

File:Listing7-7.php


<?

exec
("ping -n 5  www.php.net", $ping);       // For Windows, do exec("ping -n 5 www.php.net", $ping);
for ($i=0; $i < count($ping); $i++) :
     print
"<br>$ping[$i]";
endfor;
?>

File:Listing7-9.php


<?

// script: simple access counter
// purpose: uses a file to keep track of visitor count

$access = "hits.txt";
$visits = @file($access);
$current_visitors = $visits[0];
++
$current_visitors;
$fh = fopen($access, "w");

@
fwrite($fh, $current_visitors);
fclose($fh);

?>

File:Listing7-10.php


<?

// file: sitemap.php
// purpose: display a map of entire site structure

// From which parent directory should the sitemap begin?
$beg_path = "C:\Program Files\Apache Group\Apache\htdocs\phprecipes";

// What Is the location of the folder graphic?
// This path should be *relative* to the Apache server root directory
$folder_location = "C:\My Documents\PHP for Programmers\FINAL CHPS\graphics\folder.gif";

// What should be displayed in the sitemap title bar?
$page_name = "PHPRecipes SiteMap";

// Will this script be used on a Linux or Windows server? (0 for Windows; 1 for Linux)
$using_linux = 0;
// function: display_directory
// purpose: Parses a directory specified by $dir1 and formats directory and file structure.
// This function is recursively called.

function display_directory($dir1, $folder_location, $using_linux, $init_depth) {

// update the directory path
$dir .= $dir1;
$dh = opendir($dir);

while (
$file = readdir($dh)) :
     
// do not display the "." and ".."in each directory.
     
if ( ($file != ".") && ($file != "..") ) :

          if (
$using_linux == 0 ) :
               
$depth = explode("\\", $dir);
          else :
               
$depth = explode("/", $dir);
          endif;
          
$current_depth = sizeof($depth);

          
// Build path In accordance with what OS Is being used.
          
if ($using_linux == 0) :
               
$tab_depth = $current_depth - $init_depth;    
               
$file = $dir."\\".$file;
          else :
               
$file = $dir."/".$file;
          endif;

          
// Is $file a directory?
          
if ( is_dir($file) ) :
               
$x = 0;
               
// calculate tab depth
               
while ( $x < ($tab_depth * 2) ) :
                    print
"&nbsp;";
                    
$x++;
              endwhile;

               print
"<img src=\"$folder_location\" alt=\"[dir]\"> ".basename($file)."<br>";
               
// Increment the &nbsp; count
  
               // Recursive call to display_directory() function
              
display_directory($file, $folder_location, $using_linux, $init_depth);

          
// Not dealing with a directory
          
else :
               
// Build path In accordance with what OS Is being used.
               
if ($using_linux == 0) :
                    
$tab_depth = ($current_depth - $init_depth) - 2;                
                    
$x = 0;
                    
// calculate tab depth
                    
while ( $x < (($tab_depth * 2) + 5) ) :
                         print
"&nbsp;";
                         
$x++;
                    endwhile;
                    print
"<a href = \"".$dir."\\".basename($file)."\">".basename($file)."</a> <br>";
               else :
                    print
"<a href = \"".$dir."/".basename($file)."\">".basename($file)."</a> <br>";
               endif;

          endif;
// Is_dir(file)
     
endif; // If ! "." or ".."

endwhile;

// close the directory
closedir($dh);
}
?>
<html>
<head>
<title> <? print "$page_name"; ?> </title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#000000" vlink="#000000" alink="#000000">
<?
// calculate Initial tab depth
if ($using_linux == 0) :
         
$depth = explode("\\", $beg_path);
else :
    
$depth = explode("/", $beg_path);
endif;
$init_depth = sizeof($depth);
display_directory($beg_path, $folder_location, $using_linux, $init_depth);
?>
</body>
</html>

File:Listing8-1.php


<?

$url
= "http://www.apress.com";

// break $url down into three distinct pieces: "http://www", "apress", and "com"
$www_url = ereg("^(http://www)\.([[:alnum:]]+)\.([[:alnum:]]+)", $url, $regs);

if (
$www_url) :          // if $www_url is a valid URL
     
echo $regs[0];     // outputs the entire string "http://www.apress.com"
     
print "<br>";
     echo
$regs[1];     // outputs "http://www"
     
print "<br>";
     echo
$regs[2];     // outputs "apress"
     
print "<br>";
     echo
$regs[3];     // outputs "com"
endif;
?>

File:Listing8-2.php


<?

$meta_tags
= get_meta_tags("example.html");

// $meta_tags will return an array containing the following information:

// $meta_tags["keywords"] = "gourmet, PHP, food, code, recipes, chef, programming, Web";
// $meta_tags["description"] = "PHP Recipes provides savvy readers with the latest in PHP programming and gourmet cuisine";
// $meta_tags["author"] = "WJ Gilmore";

?>

File:Listing8-3.php


<?

/*
File: sniffer.php
Purpose: Determines browser type / version and platform information
Author: WJ Gilmore
Date: August 24, 2000
*/

// Function: browser_info
// Purpose: Returns browser type and version

function browser_info ($agent) {
     
// Determine browser type
     //  Search for Internet Explorer signature.
     
if (ereg( 'MSIE ([0-9].[0-9]{1,2})', $agent, $version)) :
          
$browse_type = "IE";
          
$browse_version = $version[1];

     
//  Search for Opera signature.
     
elseif (ereg( 'Opera ([0-9].[0-9]{1,2})', $agent, $version)) :
          
$browse_type = "Opera";
          
$browse_version = $version[1];

     
//  Search for Netscape signature. The search for the Netscape browser
     //  *must* take place after the search for the Internet Explorer and Opera
     //  browsers, because each likes to call itself
     //  Mozilla as well as by its actual name.
     
elseif (ereg( 'Mozilla/([0-9].[0-9]{1,2})', $agent, $version)) :
          
$browse_type = "Netscape";
          
$browse_version = $version[1];

     
// If not Internet Explorer, Oper,a or Netscape, then call it unknown.
     
else :
          
$browse_type = "Unknown";
          
$browse_version = "Unknown";

     endif;

     
// return the browser type and version as array
     
return array($browse_type, $browse_version);

}
// end browser_info

// Function: opsys_info
// Purpose: Returns the user operating system

function opsys_info($agent) {
     
// Determine operating system
     // Search for Windows platform
     
if ( strstr ($agent, 'Win') ) :
          
$opsys = "Windows";

     
// Search for Linux platform
     
elseif ( strstr($agent, 'Linux') ) :
          
$opsys = "Linux";

     
// Search for UNIX platform
     
elseif ( strstr ($agent, 'Unix') ) :
          
$opsys = "Unix";

     
// Search for Macintosh platform
     
elseif ( strstr ($agent,'Mac') ) :
          
$opsys = "Macintosh";

     
// Platform is unknown
     
else :
          
$opsys = "Unknown";

     endif;

     
// return the operating system
     
return $opsys;

}
// end opsys_info

// receive returned array as a list

list ($browse_type, $browse_version) = browser_info ($HTTP_USER_AGENT);
$operating_sys = opsys_info ($HTTP_USER_AGENT);

print
"Browser Type: $browse_type <br>";
print
"Browser Version: $browse_version <br>";
print
"Operating System: $operating_sys <br>";

?>

File:Listing9-1.phps


<?


. . .

if (
some_conditional)
     include (
'text91a.txt');
else
     include (
'text91b.txt');

. . .

?>

File:Listing9-2.phps


<?


. . .

if (
some_conditional) :

     include (
'text91a.txt');

else :

     include (
'text91b.txt');

endif;
. . .

?>

File:Listing9-4.php


<? require ('init.tpl'); ?>

<html>
<head>
<title><? print $site_title; ?></title>
</head>
<body>
<? print "Welcome to $site_title. For questions, contact <a href = \"mailto:$contact_email\">$contact_name</a>."; ?>
</body>
</html>

File:Listing9-8.php


<?

// file: index.php
// purpose: Home page of PHPRecipes
// date: August 23, 2000
// Include the header
include ("header.tpl");
// Include the index body
include ("index_body.tpl");
// Include the footer
include ("footer.tpl");
?>

File:Listing9-9.php


<html>

<head>
<title> PHPRecipes </title>
</head>
<body bgcolor="#7b8079" text="#ffffff" link="#e7d387" alink="#e7d387" vlink="#e7f0e4">
<table width = "95%" cellpadding="0" cellspacing="0" border="1">
    <tr>
    <td valign = "top">
    PHP Recipes    
    </td>
    <td valign = "top" align="right">
    August 23, 03:17 pm
    </td>
    </tr>
</table><table width="95%" cellspacing="0" cellpadding="0" border="1">
<tr>
<td valign="top" width="25%">
<a href = "http://localhost/phprecipes/tutorials.php">tutorials</a> <br>
<a href = "http://localhost/phprecipes/articles.php">articles</a> <br>
<a href = "http://localhost/phprecipes/scripts.php">scripts</a> <br>
<a href = "http://localhost/phprecipes/contact.php">contact</a> <br>
</td>
<td valign="top" width="75%">
Welcome to PHPRecipes, the starting place for PHP scripts, tutorials, and gourmet cooking tips and recipes!
</td>
</tr>
</table><table width="95%" cellspacing="0" cellpadding="0" border="1">
<tr><td valign="top" align="middle">
Copyright &copy; 2000 PHPRecipes. All rights reserved.<br>
<a href = "mailto:wj@hotmail.com">contact</a> | <a href = "http://localhost/phprecipes/privacy.php">your privacy</a>
</td></tr>
</table>
</body>
</html>

File:Listing9-11.php


<?

// Include site initialization information
include("site_init.tpl");

// display the header
show_header($site_name);
?>
This is some body information
<?
// display the footer
show_footer();
?>

File:Listing9-15.php


<?

// file: static.php
// purpose: display various requested static pages.
// IMPORTANT: It is assumed that "site_init.tpl" and all of the
// static files are located in the same directory.

// load functions and site variables
include("site_init.tpl");

// display the page header
show_header($site_name);

// display the requested content
include("$content.html");

// display the page footer
show_footer();

?>

File:Listing10-1.html


<form action = "process.php" method = "post">

<b>Please take a moment to tell us what you think about our site:</b><p>
<b>Name:</b><br>
<input type="text" name="name" size="15" maxlength="25" value=""><br>
<b>Email:</b><br>
<input type="text" name="email" size="15" maxlength="45" value=""><br>
<b>How frequently do you visit our site?:</b><br>
<select name="frequency">
<option value="">Site frequency:
<option value="0">This is my first time
<option value="1">&lt; 1 time a month
<option value="2">Roughly once a month
<option value="3">Several times a week
<option value="4">Every day
<option value="5">I'm addicted
</select><br>
<b>I frequently purchase the following products from our site:</b><br>
<input type="checkbox" name="software" value="software">Software<br>
<input type="checkbox" name="cookware" value="cookware">Cookware<br>
<input type="checkbox" name="hats" value="hats">Chef's Hats<br>
<b>Our site's greatest asset is:</b><br>
<input type="radio" name="asset" value="products">Product selection<br>
<input type="radio" name="asset" value="design">Cool design<br>
<input type="radio" name="asset" value="service">Customer Service<br>
<b>Comments:</b><br>
<textarea name="comments" rows="3" cols="40"></textarea><br>
<input type="submit" value="Submit!">
</form>

File:Listing10-2.html


<html>

<head>
<title>Listing 10-2</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">

<form action="listing10-3.php" method="post">
<b>Give us some information!</b><br>
Your Name:<br>
<input type="text" name="name" size="20" maxlength="20" value=""><br>
Your Email:<br>
<input type="text" name="email" size="20" maxlength="40" value=""><br>
<input type="submit" value="go!">
</form>

</body>
</html>

File:Listing10-3.php


<html>

<head>
<title>Listing 10-3</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// output the user's name and email address.
print "Hi, $name!. Your email address is $email";
?>
</body>
</html>

File:Listing10-4.php


<html>

<head>
<title>Listing 10-4</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// all double quotations in $form must be escaped, otherwise a parse error will occur
$form = "
<form action=\"listing10-4.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
<b>Give us some information!</b><br>
Your Name:<br>
<input type=\"text\" name=\"name\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Your Email:<br>
<input type=\"text\" name=\"email\" size=\"20\" maxlength=\"40\" value=\"\"><br>
<input type=\"submit\" value=\"subscribe!\">
</form>"
;
// If we haven't already seen the form ($seenform passed by hidden form value), show the form.
if ($seenform != "y"):
     print
"$form";
else :
     print
"Hi, $name!. Your email address is $email";
endif;
?>
</body>
</html>

File:Listing10-5.php


<html>

<head>
<title>Listing 10-5</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">

<?
// all double quotations in $form must be escaped, otherwise a parse error will occur
$form = "
<form action=\"listing10-5.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
<b>Send us your comments!</b><br>
Your Name:<br>
<input type=\"text\" name=\"name\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Your Email:<br>
<input type=\"text\" name=\"email\" size=\"20\" maxlength=\"40\" value=\"\"><br>
Your Comments:<br>
<textarea name=\"comments\" rows=\"3\" cols=\"30\"></textarea><br>
<input type=\"submit\" value=\"submit!\">
</form>
"
;

// If we haven't already seen the form ($seenform passed by hidden form value), show the form.
if ($seenform != "y") :
     print
"$form";
else :
     
// change $recipient to be the recipient of the form information
     
$recipient = "yourname@youremail.com";
     
// email subject
     
$subject = "User Comments ($name)";
     
// extra email headers
     
$headers = "From: $email";
     
// send the email or produce an error
     
mail($recipient, $subject, $comments, $headers) or die("Could not send email!");
     
// send the user an appropriate message
     
print "Thank you $name for taking a moment to send us your comments!";

endif;
?>
</body>
</html>

File:Listing10-6.php


<html>

<head>
<title>Listing 10-5</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?

$form
= "
<form action=\"Listing10-6.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
<b>Receive information about our site!</b><br>
Your Email:<br>
<input type=\"text\" name=\"email\" size=\"20\" maxlength=\"40\" value=\"\"><br>
<input type=\"checkbox\" name=\"information[site]\" value=\"y\">Site Architecture<br>
<input type=\"checkbox\" name=\"information[team]\" value=\"y\">Development Team<br>
<input type=\"checkbox\" name=\"information[events]\" value=\"y\">Upcoming Events<br>
<input type=\"submit\" value=\"send it to me!\">
</form>"
;

if (
$seenform != "y") :
     print
"$form";
else :
     
$headers = "From: devteam@yoursite.com";
     
// cycle through each array key/value element
     
while ( list($key, $val) = each ($information) ) :
          
// verify if the current value is "y"
          
if ($val == "y") :
               
               
// create filename that corresponds with current key
               
$filename = "$key.txt";
               
$subject = "Requested $key information";
               
               
// open the filename
               
$fd = fopen ($filename, "r");
               
// read the entire file into a variable
               
$contents = fread ($fd, filesize ($filename));
               
               
// send email.
               
mail($email, $subject, $contents, $headers) or die("Can't send email!");;
               
fclose($fd);
          endif;
     endwhile;
     
// Notify user of success
     
print sizeof($information)." informational newsletters have been sent to $email!";
endif;
?>
</body>
</html>

File:Listing10-7.php


<html>

<head>
<title>Listing 10-7</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// create the form
$form = "
<form action=\"Listing10-7.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
<b>Give us your personal info!</b><br>
Your Name:<br>
<input type=\"text\" name=\"name\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Your Email:<br>
<input type=\"text\" name=\"email\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Your Preferred Language:<br>
<select name=\"language\">
<option value=\"\">Choose a language:
<option value=\"English\">English
<option value=\"Spanish\">Spanish
<option value=\"Italian\">Italian
<option value=\"French\">French
<option value=\"Japanese\">Japanese
<option value=\"newyork\">NewYork-ese
</select><br>
Your Occupation:<br>
<select name=\"job\">
<option value=\"\">What do you do?:
<option value=\"student\">Student
<option value=\"programmer\">Programmer
<option value=\"manager\">Project Manager
<option value=\"slacker\">Slacker
<option value=\"chef\">Gourmet Chef
</select><br>
<input type=\"submit\" value=\"submit!\">
</form>"
;

// has the form already been filled in?
if ($seenform != "y") :
     print
"$form";
else :
     
$fd = fopen("user_information.txt", "a");

     
// make sure user has not entered a vertical bar in the input
     
$name = str_replace("|", "", $name);
     
$email = str_replace("|", "", $email);

     
// assemble user information
     
$user_row = $name."|".$email."|".$language."|".$job."\n";
     
fwrite($fd, $user_row) or die("Could not write to file!");
     
fclose($fd);
     print
"Thank you for taking a moment to fill out our brief questionnaire!";

endif;
?>
</body>
</html>

File:Listing10-8.php


<html>

<head>
<title>Listing 10-8</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// create the form
$form = "
<form action=
\"Listing10-8.php\" method=\"post\">
<input type=
\"hidden\" name=\"seenform\" value=\"y\">
<b>Give us some information!</b><br>
Your Name:<br>
<input type=
\"text\" name=\"name\" size=\"20\" maxlength=\"20\" value=\"$name\"><br>
Your Email:<br>
<input type=
\"text\" name=\"email\" size=\"20\" maxlength=\"40\" value=\"$email\"><br>
<input type=
\"submit\" value=\"subscribe!\">
</form>"
;

// has the form already been filled in?
if ($seenform != "y"):
     print
"$form";

// The user has filled out the form. Now verify the information
else :
     
$error_flag = "n";
     
// ensure that the name variable is not empty
     
if ($name == "") :
          print
"<font color=\"red\">* You forgot to enter your name!</font> <br>";
          
$error_flag = "y";
     endif;
     
// ensure that the email variable is not empty
     
if ($email == "") :

          print
"<font color=\"red\">* You forgot to enter your email!</font> <br>";
          
$error_flag = "y";

     else :    
          
// convert all email alphabetical characters to lowercase
          
$email = strtolower(trim($email));
          
// ensure the email address is of valid syntax
          
if (! @eregi('^[0-9a-z]+'.
                              
'@'.
                              
'([0-9a-z-]+\.)+'.
                              
'([0-9a-z]){2,4}$', $email)) :

               print
"<font color=\"red\">* You entered an invalid email address!</font> <br>";
               
$error_flag = "y";
          endif;    
     endif;

     
// If the $error_flag has been set, redisplay the form
     
if ($error_flag == "y") :
          print
"$form";
     else :
          
// do something with that user information
          
print "You entered valid form information!";
     endif;
endif;
?>
</body>
</html>

File:Listing10-9.php


<?

if ($site != "") :
    
header("Location: http://$site");
    exit;
else :
?>

<html>
<head>
<title>Listing 10-9</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
$favsites
= array ("www.k10k.com",
                             
"www.yahoo.com",
                             
"www.drudgereport.com",
                             
"www.phprecipes.com",
                             
"www.frogdesign.com");

// now build the form
?>
<form action = "Listing10-9.php" method="post">
<select name="site">
<option value = "">Choose a site:
<?
$x
= 0;

while (
$x < sizeof ($favsites) ) :
          print
"<option value='$favsites[$x]'>$favsites[$x]";
          
$x++;
endwhile;
?>
</select>
<input type="submit" value="go!">
</form>
<?
endif;
?>

File:Listing11-1.php


<?

@mysql_connect("localhost", "web", "ffttss")
            or die(
"Could not connect to MySQL server!");
@
mysql_select_db("company")
            or die(
"Could not select products database!");

// select all rows in the products table
$query = "SELECT * FROM products";
$result = mysql_query($query);

$x = 0;
print
"<table>\n";
print
"<tr>\n<th>Product ID</th><th>Product Name</th><th>Product Price</th>\n</tr>\n";
while (
$x < mysql_numrows($result)) :

    
$id = mysql_result($result, $x, 'prod_id');
    
$name = mysql_result($result, $x, 'prod_name');
    
$price = mysql_result($result, $x, 'prod_price');

    print
"<tr>\n";
    print
"<td>$id</td>\n<td>$name</td>\n<td>$price</td>\n";
    print
"</tr>\n";
     
    
$x++;

endwhile;
print
"</table>";
mysql_close();
?>

File:Listing11-2.html


<table>

    <tr>
    <th>Product ID</th><th>Product Name</th><th>Product Price</th>
    </tr>
    <tr>
        <td>
            1000pr
        </td>
        <td>
            apples
        </td>
        <td>
            1.23
        </td>
    </tr>
    <tr>
        <td>
            1001pr
        </td>
        <td>
            oranges
        </td>
        <td>
            2.34
        </td>
    </tr>
    <tr>
        <td>
            1002pr
        </td>
        <td>
            bananas
        </td>
        <td>
            3.45
        </td>
    </tr>
    <tr>
        <td>
            1003pr
        </td>
        <td>
            pears
        </td>
        <td>
            4.45
        </td>
    </tr>
</table>

File:Listing11-3.php


<?

@mysql_connect("localhost", "web", "ffttss")
            or die(
"Could not connect to MySQL server!");
@
mysql_select_db("company")
            or die(
"Could not select products database!");

$query = "SELECT * FROM products";
$result = mysql_query($query);

print
"<table>\n";
print
"<tr>\n<th>Product ID</th><th>Product Name</th><th>Product Price</th>\n</tr>\n";
while (
$row = mysql_fetch_array($result)) :
    print
"<tr>\n";
    print
"<td>".$row["prod_id"]."</td>\n<td>".$row["prod_name"]."</td>\n<td>".$row["prod_price"]."</td>\n";
    print
"</tr>\n";
endwhile;
print
"</table>";
mysql_close();
?>

File:Listing11-4.php


<?

@mysql_connect("localhost", "web", "ffttss")
                or die(
"Could not connect to MySQL server!");
@
mysql_select_db("company")
                or die(
"Could not select products database!");

$query = "SELECT * FROM products";
$result = mysql_query($query);

print
"<table>\n";
print
"<tr>\n<th>Product ID</th><th>Product Name</th>
    <th>Product Price</th>\n</tr>\n"
;

while (
$row = mysql_fetch_array($result)) :
    print
"<tr>\n";
    print
"<td>".$row["prod_id"]."</td>\n
        <td>"
.$row["prod_name"]."</td>\n
        <td>"
.$row["prod_price"]."</td>\n";
    print
"</tr>\n";
endwhile;

print
"</table>";
mysql_close();
?>

File:Listing11-5.php


<?

$form
=
"<form action=\"Listing11-5.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
Keyword:<br>
<input type=\"text\" name=\"keyword\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Search Focus:<br>
<select name=\"category\">
<option value=\"\">Choose a category:
<option value=\"cust_id\">Customer ID
<option value=\"cust_name\">Customer Name
<option value=\"cust_email\">Customer Email
</select><br>
<input type=\"submit\" value=\"search\">
</form>
"
;
// If the form has not been displayed, show it.
if ($seenform != "y") :
     print
$form;
else :
     
// connect to MySQL server and select database
     
@mysql_connect("localhost", "web", "ffttss")
                or die(
"Could not connect to MySQL server!");
     @
mysql_select_db("company")
                or die(
"Could not select company database!");

     
// form and execute query statement
     
$query = "SELECT cust_id, cust_name, cust_email
            FROM customers WHERE $category = '$keyword'"
;
     
$result = mysql_query($query);

     
// If no matches found, display message and redisplay form
     
if (mysql_num_rows($result) == 0) :
          print
"Sorry, but no matches were found. Please try your search again:";
          print
$form;
     
// matches found, therefore format and display results
     
else :
          
// format and display returned row values.
          
list($id, $name, $email) = mysql_fetch_row($result);
          print
"<h3>Customer Information:</h3>";
          print
"<b>Name:</b> $name <br>";
          print
"<b>Identification #:</b> $id <br>";
          print
"<b>Email:</b> <a href=\"mailto:$email\">$email</a> <br>";
   
          print
"<h3>Order History:</h3>";
          
// form and execute 'orders' query
          
$query = "SELECT order_id, prod_id, quantity FROM orders WHERE cust_id = '$id'
                          ORDER BY quantity DESC"
;
          
$result = mysql_query($query);

          print
"<table border = 1>";
          print
"<tr><th>Order ID</th><th>Product ID</th><th>Quantity</th></tr>";
          
// format and display returned row values.
          
while (list($order_id, $prod_id, $quantity) = mysql_fetch_row($result)) :
               print
"<tr>";
               print
"<td>$order_id</td><td>$prod_id</td><td>$quantity</td>";
               print
"</tr>";    
          endwhile;
          print
"</table>";
     endif;
endif;
?>

File:Listing11-6.php


<?

// connect to MySQL server and select database
@mysql_connect("localhost", "web", "ffttss")
            or die(
"Could not connect to MySQL server!");
@
mysql_select_db("company")
            or die(
"Could not select company database!");

// If the $key variable is not set, default to 'quantity'
if (! isset($key)) :
     
$key = "quantity";
endif;
// create and execute query. Any retrieved data is sorted in descending order
$query = "SELECT order_id, cust_id, prod_id, quantity FROM orders ORDER BY $key DESC";
$result = mysql_query($query);
// create table header
print "<table border = 1>";
print
"<tr>
<th><a href=\"Listing11-6.php?key=order_id\">Order ID</a></th>
<th><a href=\"Listing11-6.php?key=cust_id\">Customer ID</a></th>
<th><a href=\"Listing11-6.php?key=prod_id\">Product ID</a></th>
<th><a href=\"Listing11-6.php?key=quantity\">Quantity</a></th></tr>"
;
// format and display each row value
while (list($order_id, $cust_id, $prod_id, $quantity) = mysql_fetch_row($result)) :
     print
"<tr>";
     print
"<td>$order_id</td><td>$cust_id</td><td>$prod_id</td><td>$quantity</td>";
     print
"</tr>";    
endwhile;
// close table
print "</table>";
?>

File:Listing11-7.php


<?php


// Connect to the ODBC datasource 'ContactDB'
$connect = odbc_connect("ContactDB","","")
            or die(
"Couldn't connect to datasource.");

// form query statement

$query = "SELECT First_Name, Last_Name, Cell_Phone, Email FROM Contacts";

// prepare query statement
$result = odbc_prepare($connect,$query);

// execute query statement and display results
odbc_execute($result);
odbc_result_all($result,"BGCOLOR='#c0c0c0' border=1");

// We're done with the query results, so free memory  
odbc_free_result($result);

// close connection
odbc_close($connect);

?>

File:Listing11-8.php


<?

// file: init.inc
// purpose: provides global variables for use in bookmark project

// Default page title
$title = "My Bookmark Repository";

// Background color
$bg_color = "white";

// Posting date
$post_date = date("Ymd");

// bookmark categories
$categories = array(
                    
"computers",
                    
"entertainment",
                    
"dining",
                    
"lifestyle",
                    
"government",
                    
"travel");

// MySQL Server Information
$host = "localhost";
$user = "root";
$pswd = "";

// database name
$database = "book";

// bookmark table name
$bookmark_table = "bookmarks";

// Table cell color
$cell_color = "#c0c0c0";

// Connect to the MySQL Server
@mysql_pconnect($host, $user, $pswd) or die("Couldn't connect to MySQL server!");

// Select the database
@mysql_select_db($database) or die("Couldn't select $database database!");

// function: add_bookmark()
// purpose: Add new bookmark to bookmark table.

function add_bookmark ($category, $site_name, $url, $description) {
     GLOBAL
$bookmark_table, $post_date;

     
$query = "INSERT INTO $bookmark_table
                    VALUES(
\"$category\", \"$site_name\", \"$url\", \"$post_date\", \"$description\")";

     
$result = @mysql_query($query) or die("Couldn't insert bookmark information!");

}
// add_bookmark

// function: view_bookmark()
// purpose: Extract all bookmarks having category of $category from bookmark table.

function view_bookmark ($category) {

     GLOBAL
$bookmark_table, $cell_color, $categories;

     
$query = "SELECT site_name, url, DATE_FORMAT(date_added,'%m-%d-%Y') AS date_added, description
                    FROM $bookmark_table WHERE category = $category
                    ORDER BY date_added DESC"
;

     
$result = @mysql_query($query);

     print
"<div align=\"center\"><table cellpadding=\"2\" cellspacing=\"1\" border = \"0\" width = \"600\">";

     print
"<tr><td bgcolor=\"$cell_color\"><b>Category: $categories[$category]</b></td></tr>";

     if (
mysql_numrows($result) > 0) :

          while (
$row = mysql_fetch_array($result)) :

               print
"<tr><td>";
               print
"<b>".$row["site_name"]."</b> | Posted: ".$row["date_added"]."<br>";
               print
"</td></tr>";

               print
"<tr><td>";
               print
"<a href = \"http://".$row["url"]."\">http://".$row["url"]."</a><br>";
               print
"</td></tr>";

               print
"<tr><td valign=\"top\">";
               print
$row["description"]."<br>";
               print
"</td></tr>";

               print
"<tr><td><hr></td></tr>";

          endwhile;

     else :

          print
"<tr><td>There are currently no bookmarks falling under this category.
               Why don't you <a href=\"add_bookmark.php\">add one</a>?</td></tr>"
;

     endif;

     print
"</table><a href=\"Listing11-11.php\">Return to index</a> |";
     print
"<a href=\"add_bookmark.php\">Add a bookmark</a></div>";

}
// view_bookmark

?>

File:Listing11-11.php


<html>

<?
INCLUDE("init.inc");
?>
<head>
<title><?=$title;?></title>
</head>
<body bgcolor="<?=$bg_color;?>" text="#000000" link="#808040" vlink="#808040" alink="#808040">
<h4>Choose bookmark category to view:</h4>
<?
// cycle through each category and display appropriate link
while (list($key, $value) = each($categories)) :
     print
"<a href = \"view_bookmark.php?category=$key\">$value</a><br>";
endwhile;
?>
<p>
<b><a href="add_bookmark.php">Add a new bookmark</a></b>
</body>
</html>

File:Listing11-12.html


<html>

<head>
<title></title>
</head>
<body bgcolor="white" text="#000000" link="#808040" vlink="#808040" alink="#808040">
<h4>Choose bookmark category to view:</h4>
<a href = "view_bookmark.php?category=0">computers</a><br>
<a href = "view_bookmark.php?category=1">entertainment</a><br>
<a href = "view_bookmark.php?category=2">dining</a><br>
<a href = "view_bookmark.php?category=3">lifestyle</a><br>
<a href = "view_bookmark.php?category=4">government</a><br>
<a href = "view_bookmark.php?category=5">travel</a><br>
<p>
<b><a href="add_bookmark.php">Add a new bookmark</a></b>
</body>
</html>

File:Listing12-1.html


<html>

<head>
<title>:::::{page_title}:::::</title>
</head>
<body bgcolor="{bg_color}">
Welcome to your default home page, {user_name}!<br>
You have 5 MB and 3 email addresses at your disposal.<br>
Have fun!
</body>
</html>

File:Listing12-2.phps


function register_file($file_id, $file_name) {


// Open $file_name for reading, or exit and print an error message
$fh = fopen($file_name, "r") or die("Couldn't open $file_name!");

// Read in the entire contents to a position in the array.
$file_contents = fread($fh, filesize($file_name));

// Assign these contents to a position in the array
// This position is denoted by the key $file_id
$this->files[$file_id] = $file_contents;

// We're finished with the file, so close it.
fclose($fh);


} // end register_file

File:Listing12-3.phps


function register_variables($file_id, $variable_name) {


    // attempt to create array from passed in variable names
    $input_variables = explode(",", $variable_name);

    // assign variable name to next position in $file_id array
    while (list(,$value) = each($input_variables)) :

        // assign the value to a new position in the $this->variables array
        $this->variables[$file_id][] = $value;

    endwhile;

} // end register_variables()

File:Listing12-4.phps


function file_parser($file_id) {


     // How many variables are registered for this particular file?
     $varcount = count($this->variables[$file_id]);

     // How many files are registered?
     $keys = array_keys($this->files);

     // If the $file_id exists in the $this->files array and it has some registered variablesÉ
     if ( (in_array($file_id, $keys)) && ($varcount > 0) ) :

          // reset $x
          $x = 0;

          // while there are still variables to parse...
          while ($x < sizeof($this->variables[$file_id])) :

               // retrieve the next variable
               $string = $this->variables[$file_id][$x];
               
               // retrieve this variable value! Notice that I'm using a variable variable to retrieve this value.
               // this value will be substituted into the file contents, taking the place of the corresponding variable
               // name.
               GLOBAL $$string;

               // What exactly is to be replaced within the file contents?
               $needle = $this->opening_escape.$string.$this->closing_escape;

               // Perform the string replacement.
               $this->files[$file_id] = str_replace(
                                                  $needle,   // needle
                                                  $$string,   // string
                                                  $this->files[$file_id]); // haystack
               // increment $x
               $x++;
          endwhile;
     endif;
} // end file_parser

File:Listing12-5.phps


function print_file($file_id) {


    // print out the contents pointed to by $file_id
    print $this->files[$file_id];

} // end print_file()

File:Listing12-6.php


<?

// Include the template class
include("template.class");

// Assign a few variables
$page_title = "Welcome to your homepage!";
$bg_color = "white";
$user_name = "Chef Jacques";

// Instantiate a new object
$template = new template;

// Register the file "homepage.html", assigning it the pseudonym "home"
$template->register_file("home", "homepage.html");

// Register a few variables
$template->register_variables("home", "page_title,bg_color,user_name");
$template->file_parser("home");
// output the file to the browser
$template->print_file("home");

?>

File:Listing12-7.php


<?

class template {

VAR
$files = array();
VAR
$variables = array();
VAR
$opening_escape = '{';
VAR
$closing_escape = '}';

// Function: register_file()
// Purpose: Store contents of file specified by $file_id

function register_file($file_id, $file_name) {

     
// Open $file_name for reading, or exit and print an error message.
     
$fh = fopen($file_name, "r") or die("Couldn't open $file_name!");

     
// Read in the entire contents of $file_name.
     
$file_contents = fread($fh, filesize($file_name));

     
// Assign these contents to a position in the array. This position is denoted by the key $file_id
     
$this->files[$file_id] = $file_contents;

     
// We're finished with the file, so close it.
     
fclose($fh);
}
// end register_file;

// Function: register_variables()
// Purpose: Store variables passed in via $variable_name under the corresponding
// array key, specified by $file_id

function register_variables($file_id, $variable_name) {

     
// attempt to create array from passed in variable names
     
$input_variables = explode(",", $variable_name);

     
// assign variable name to next position in $file_id array
     
while (list(,$value) = each($input_variables)) :

          
// assign the value to a new position in the $this->variables array
          
$this->variables[$file_id][] = $value;        

     endwhile;            

}
// end register_variables

// Function: file_parser()
// Purpose: Parse all registered variables found within file contents
//                 specified by input parameter $file_id

function file_parser($file_id) {

     
// How many variables are registered for this particular file?
     
$varcount = count($this->variables[$file_id]);

     
// How many files are registered?
     
$keys = array_keys($this->files);

     
// If the $file_id exists in the $this->files array and it has some registered variablesÉ
     
if ( (in_array($file_id, $keys)) && ($varcount > 0) ) :

          
// reset $x
          
$x = 0;

          
// while there are still variables to parseÉ
          
while ($x < sizeof($this->variables[$file_id])) :

               
// retrieve the next variable
               
$string = $this->variables[$file_id][$x];
               
               
// retrieve this variable value! Notice that I'm using a variable variable to retrieve this value.
               // this value will be substituted into the file contents, taking the place of the corresponding variable
               // name.
               
GLOBAL $$string;

               
// What exactly is to be replaced within the file contents?
               
$needle = $this->opening_escape.$string.$this->closing_escape;

               
// Perform the string replacement.
               
$this->files[$file_id] = str_replace(
                                                  
$needle,   // needle
                                                  
$$string,   // string
                                                  
$this->files[$file_id]); // haystack
               // increment $x
               
$x++;
          endwhile;
     endif;
}
// end file_parser

// Function: print_file()
// Purpose: Print out the file contents specified by input parameter $file_Id

function print_file($file_id) {
     
// print out the contents pointed to by $file_id     
     
print $this->files[$file_id];
}

}

File:Listing12-11.php


<?

// class.template.inc


class template {

    VAR
$files = array();
    VAR
$variables = array();
    VAR
$sql = array();
    VAR
$opening_escape = '{';
    VAR
$closing_escape = '}';
    VAR
$sql_delimiter = "|";

    VAR
$host = "localhost";
    VAR
$user = "root";
    VAR
$pswd = "";
    VAR
$db = "book";

    VAR
$address_table = "addressbook";





    function
register_file($file_id, $file_name) {

        
$fh = fopen($file_name, "r") or die("Couldn't open $file_name!");

        
$file_contents = fread($fh, filesize($file_name));

        
$this->files[$file_id] = $file_contents;

        
fclose($fh);

    }
// end register_file;





    
function register_variables($file_id, $variable_name) {

        
// attempt to create array from passed in variable names

        
$input_variables = explode(",", $variable_name);

        
// assign variable name to next position in $file_id array

        
while (list(,$value) = each($input_variables)) :

                
$this->variables[$file_id][] = $value;                

        endwhile;            

    }
// end register_variables






    // This function is called when the addressbook must be retrieved

    
function address_sql($file_id, $variable_name, $letter) {

        
mysql_connect($this->host, $this->user, $this->pswd) or die("Couldn't connect to MySQL server!");
        
        
mysql_select_db($this->db) or die("Couldn't select MySQL database!");

        
$query = "SELECT last_name, first_name, tel, email
                    FROM $this
->address_table WHERE last_name LIKE '$letter%'";
        
        
$result = mysql_query($query);

        
$fh = fopen("$variable_name", "r");
        
        
$file_contents = fread($fh, filesize("rows.addresses") );

        while (
$row = mysql_fetch_array($result)) :

            
$new_row = $file_contents;

            
$new_row = str_replace($this->opening_escape."last_name".$this->closing_escape,
                                        
$row["last_name"],
                                        
$new_row);

            
$new_row = str_replace($this->opening_escape."first_name".$this->closing_escape,
                                        
$row["first_name"],
                                        
$new_row);

            
$new_row = str_replace($this->opening_escape."telephone".$this->closing_escape,
                                        
$row["tel"],
                                        
$new_row);

            
$new_row = str_replace($this->opening_escape."email".$this->closing_escape,
                                        
$row["email"],
                                        
$new_row);

            
$complete_table .= $new_row;

        endwhile;

        
$sql_array_key = $variable_name;

        
$this->sql[$sql_array_key] = $complete_table;

        
// add the key to the variables array for later lookup
        
$this->variables[$file_id][] = $variable_name;        

        
fclose($fh);

    }
// end sql_address



    
function file_parser($file_id) {

        
$varcount = count($this->variables[$file_id]);

        
$keys = array_keys($this->files);

        if ( (
in_array($file_id, $keys)) && ($varcount > 0) ) :

            
$x = 0;

            while (
$x < sizeof($this->variables[$file_id])) :

                
$string = $this->variables[$file_id][$x];
                GLOBAL $
$string;

                
$needle = $this->opening_escape.$string.$this->closing_escape;

                
// Verify whether the {string} is meant for variable replacement or SQL processing

                
if (eregi("rows", $this->variables[$file_id][$x])) :

                    
$sql_replacement = $this->sql[$this->variables[$file_id][$x]];

                    
$this->files[$file_id] = str_replace(
                                                    
$needle,                                      // needle
                                                    
$sql_replacement,                        // string
                                                    
$this->files[$file_id]);                        // haystack                    

                
else :

                    
$this->files[$file_id] = str_replace(
                                                    
$needle,                                      // needle
                                                    
$$string,                                     // string
                                                    
$this->files[$file_id]);                        // haystack

                
endif;

                
$x++;

            endwhile;

        endif;

    }
// end file_parser


    
function print_file($file_id) {

        print
$this->files[$file_id];

    }


}
// END templater class


?>

File:Listing12-12.php


<?


include("Listing12-11.php");

$page_title = "Address Book";

if (! isset(
$letter) ) :

    
$letter = "a";

endif;

$tpl = new template;
$tpl->register_file("book", "book.html");
$tpl->register_variables("book", "page_title,letter");
$tpl->address_sql("book", "rows.addresses","$letter");
$tpl->file_parser("book");
$tpl->print_file("book");

?>

File:Listing13-1.php


<?

// If the variable $bgcolor exists
if (isset($bgcolor)) :
     
setcookie("bgcolor", $bgcolor, time()+3600);
?>

<html>
<body bgcolor="<?=$bgcolor;?>">

<?
// else, $bgcolor is not set, therefore show the form
else :
?>
<body bgcolor="white">
<form action="<? print $PHP_SELF; ?>" method="post">
     What's your favorite background color?
     <select name="bgcolor">
          <option value="red">red
          <option value="blue">blue
          <option value="green">green
          <option value="black">black
     </select>
          <input type="submit" value="Set background color">
</form>

<?
endif;
?>
</body>
</html>

File:Listing13-2.php


<?

setcookie
("phprecipes[uid]", "4139b31b7bab052", time()+3600);
setcookie("phprecipes[color]", "black", time()+3600);
setcookie("phprecipes[preference]", "english", time()+3600);

if (isset(
$phprecipes)) :
    while (list (
$name, $value) = each ($phprecipes)) :
        echo
"$name = $value<br>\n";
    endwhile;
endif;

?>

File:Listing13-3.php


<?


if (! isset($userid)) :
    
$id = 15;
    
setcookie ("userid", $id, time()+3600);
    print
"A cookie containing your userID has been set on your machine.
    Please refresh the page to retrieve your user information"
;
else:

@
mysql_connect("localhost", "web", "4tf9zzzf") or die("Could not connect to MySQL server!");
@
mysql_select_db("user") or die("Could not select user database!");

// declare query
$query = "SELECT * FROM users13 WHERE user_id = '$userid'";

// execute query
$result = mysql_query($query);

// If a match is found, display user information.
if (mysql_num_rows($result) == 1) :
    
$row = mysql_fetch_array($result);
     print
"Hi ".$row["fname"].",<br>";
     print
"Your email address is ".$row["email"];
else:
   print
"Invalid User ID!";
endif;
mysql_close();

endif;

?>

File:Listing13-4.php


<?

// build form
$form = "
<form action=\"Listing13-4.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
Your first name?:<br>
<input type=\"text\" name=\"fname\" size=\"20\" maxlength=\"20\" value=\"\"><br>
Your email?:<br>
<input type=\"text\" name=\"email\" size=\"20\" maxlength=\"35\" value=\"\"><br>
<input type=\"submit\" value=\"Register!\">
</form>
"
;
// If the form has not been displayed and the user does not have a cookie.
if ((! isset ($seenform)) && (! isset ($userid))) :

     print
$form;

// If the form has been displayed but the user information has not yet been processed
elseif (isset ($seenform) && (! isset ($userid))) :

     
srand ((double) microtime() * 1000000);
     
$uniq_id = uniqid(rand());
     
// connect to the MySQL server and select the users database
     
@mysql_pconnect("localhost", "root", "") or die("Could not connect to MySQL server!");
     @
mysql_select_db("book") or die("Could not select user database!");
    
     
// declare and execute query
     
$query = "INSERT INTO users13 VALUES('$uniq_id', '$fname', '$email')";
     
$result = mysql_query($query) or die("Could not insert user information!");

     
// set cookie "userid" to expire in one month.
     
setcookie ("userid", $uniq_id, time()+2592000);

     print
"Congratulations $fname! You are now registered! Your user information will be displayed uponon each subsequent visit to this page.";
// else if the cookie exists, use the userID to extract information from the users database
elseif (isset($userid)) :
     
// connect to the MySQL server and select the users database
     
@mysql_pconnect("localhost", "root", "") or die("Could not connect to MySQL server!");
     @
mysql_select_db("book") or die("Could not select user database!");
    
     
// declare and execute query
     
$query = "SELECT * FROM users13 WHERE user_id = '$userid'";
     
$result = mysql_query($query) or die("Could not extract user information!");
    
     
$row = mysql_fetch_array($result);
     print
"Hi ".$row["fname"].",<br>";
     print
"Your email address is ".$row["email"];

endif;

?>

File:Listing13-5.php


<?

session_start
();
if (!
session_is_registered('hits')) :
    
session_register('hits');
endif;
$hits++;
print
"You've seen this page $hits times.";

?>

File:Listing13-6.php


<?

// Initiate session and create a few session variables
session_register('bgcolor');
session_register('fontcolor');

// assume that the variable $usr_id (containing a unique user ID)
// is stored in a cookie on the user's machine.

// use session_id() to set the session ID to be the user's
// unique user ID stored in the cookie and In the database
$id = session_id($usr_id);

// these variables could be set by the user via an HTML form
$bgcolor = "white";
$fontcolor = "blue";

// encode all session data into a single string
$usr_data = session_encode();

// connect to the MySQL server and select users database
@mysql_pconnect("localhost", "web", "4tf9zzzf")
                or die(
"Could not connect to MySQL server!");
@
mysql_select_db("users")
                or die(
"Could not select user database!");

// update the user's page preferences
$query = "UPDATE user_info set page_data='$usr_data' WHERE user_id= '$id'";
$result = mysql_query($query) or die("Could not update user information!");
?>

File:Listing13-7.php


<?

// assume that the variable $usr_id (containing a unique user ID)
// is stored in a cookie on the user's machine.

$id = session_id($usr_id);

// connect to the MySQL server and select user's database
@mysql_pconnect("localhost", "web", "4tf9zzzf")
                or die(
"Could not connect to MySQL server!");
@
mysql_select_db("users")
                or die(
"Could not select company database!");

// select data from the MySQL table
$query = "SELECT page_data FROM user_info WHERE user_id= '$id'";
$result = mysql_query($query);
$user_data = mysql_result($result, 0, "page_data");

// decode the data
session_decode($user_data);

// output one of the regenerated session variables
print "BGCOLOR: $bgcolor";

?>

File:Listing13-8.php


<?

// MySQL implementation of session-handling functions

// mysql server host, username, and password values
$host = "localhost";
$user = "web";
$pswd = "4tf9zzzf";

// database and table names
$db = "users";
$session_table = "user_session_data";

// retrieve sess.gc_lifetime value from php.ini file
$sess_life = get_cfg_var("sess.gc_lifetime");

// Function: mysql_sess_open()
// mysql_sess_open() connects to the MySQL server
// and selects the database.

function mysql_sess_open($save_path, $session_name) {

     GLOBAL
$host, $user, $pswd, $db;

     @
mysql_connect($host, $user, $pswd)
                or die(
"Can't connect to MySQL server!");

     @
mysql_select_db($db)
                or die(
"Can't select session database!");

}
// end mysql_sess_open()

// Function: mysql_sess_close()
// mysql_sess_close() is not needed within the MySQL implementation.
// *However*, it still must be defined.

function mysql_sess_close() {

    return
true;

}
// end mysql_sess_close()


// Function: mysql_sess_read()
// mysql_sess_read() reads the information from the MySQL database.

function mysql_sess_read($key) {

    GLOBAL
$session_table;

    
$query = "SELECT value FROM $session_table WHERE sess_key = '$key'";

    
$result = mysql_query($query);

    if (list(
$value) = mysql_fetch_row($result)) :

        return
$value;

    endif;

    return
false;

}
// end mysql_sess_read()

// Function: mysql_sess_write()
// mysql_sess_write() writes the information to the MySQL database.

function mysql_sess_write($key, $val) {

    GLOBAL
$sess_life, $session_table;

    
$expiration = time() + $sess_life;

    
$query = "INSERT INTO $session_table VALUES('$key', '$expiration', '$value')";

    
$result = mysql_query($query);

    
// if the insert query failed because of the Primary key setting the sess_key column,
    // perform an update instead.

    
if (! $result) :

        
$query = "UPDATE $session_table
                SET sess_expiration = '$expiration', sess_value='$value'
                WHERE sess_key = '$key'"
;

        
$result = mysql_query($result);

    endif;

}
// end mysql_sess_write()


// Function: mysql_sess_destroy()
// mysql_sess_destroy() deletes all table rows having the session key = $sess_id

function mysql_sess_destroy($sess_id) {

    GLOBAL
$session_table;

    
$query = "DELETE FROM $session_table WHERE sess_key = '$sess_id'";

    
$result = mysql_result($query);

    return
$result;

}
// end mysql_sess_destroy()


// Function: mysql_sess_gc()
// mysql_sess_gc() deletes all table rows
// having an expiration < current time - session.gc_lifetime

function mysql_sess_gc($max_lifetime) {

    GLOBAL
$session_table;

    
$query = "DELETE FROM $session_table WHERE sess_expiration < " . time();
    
$result = mysql_query($query);

    return
mysql_affected_rows();

}
// end mysql_sess_gc




session_set_save_handler("mysql_sess_open", "mysql_sess_close", "mysql_sess_read",
                    
"mysql_sess_write", "mysql_sess_destroy", "mysql_sess_gc");

?>

File:Listing13-9.php


<?

// file: init.inc
// purpose: initialization file for Visitor Logging project


// Connect to the MySQL Server

$host = "localhost";
$user = "root";
$pswd = "";

// database name

$database = "myTracker";

// polls table name

$visitors_table = "visitors";

@
mysql_pconnect($host, $user, $pswd) or die("Couldn't connect to MySQL server!");

// Choose the database

@mysql_select_db($database) or die("Couldn't select $database database!");


// Number of recent visitors to display in table

$maxNumVisitors = "5";

// Cookie Name

$cookieName = "visitorLog";

// Cookie Value

$cookieValue="1";

// Timeframe between acknowledgement of subsequent visit by same user
// If $timeLimit is set to 0, every user visit to that page will be recorded
// regardless of the frequency. All other integer settings will be regarded as number SECONDS
// that must pass between visits in order to be recorded.

$timeLimit = 3600;

// How would you like the date-of-visit displayed in the browser?

$header_color = "#cbda74";
$table_color = "#000080";
$row_color = "#c0c0c0";
$font_color = "#000000";
$font_face = "Arial, Times New Roman, Verdana";
$font_size = "-1";

function
recordUser() {

    GLOBAL
$visitors_table, $HTTP_USER_AGENT, $REMOTE_ADDR, $REMOTE_HOST;

    if (
$REMOTE_HOST == "") :

        
$REMOTE_HOST = "localhost";

    endif;

    
$timestamp = date("Y-m-d H:i:s");

    
$query = "INSERT INTO $visitors_table VALUES('$HTTP_USER_AGENT', '$REMOTE_ADDR', '$REMOTE_HOST', '$timestamp')";

    
$result = @mysql_query($query);

}
// recordUser

function viewStats() {

    GLOBAL
$visitors_table, $maxNumVisitors, $table_color, $header_color;
    GLOBAL
$row_color, $font_color, $font_face, $font_size;

    
$query = "SELECT browser, ip, host, TimeofVisit FROM $visitors_table ORDER BY TimeofVisit desc LIMIT 0, $maxNumVisitors";

    
$result = mysql_query($query);

    print
"<table cellpadding=\"2\" cellspacing=\"1\" width = \"700\" border = \"0\" bgcolor=\"$table_color\">";

    print
"<tr bgcolor= \"$header_color\"><th>Browser</th><th>IP</th><th>Host</th><th>TimeofVisit</th></tr>";

    while(
$row = mysql_fetch_array($result)) :

        list (
$browse_type, $browse_version) = browser_info ($row["browser"]);
        
$op_sys = opsys_info ($row["browser"]);

        print
"<tr bgcolor=\"$row_color\">";
        print
"<td><font color=\"$font_color\" face=\"$font_face\" size=\"$font_size\">$browse_type $browse_version - $op_sys</font></td>";
        print
"<td><font color=\"$font_color\" face=\"$font_face\" size=\"$font_size\">".$row["ip"]."</font></td>";
        print
"<td><font color=\"$font_color\" face=\"$font_face\" size=\"$font_size\">".$row["host"]."</font></td>";
        print
"<td><font color=\"$font_color\" face=\"$font_face\" size=\"$font_size\">";
        print
$row["TimeofVisit"]."</font></td>";
        print
"</tr>";
    

    endwhile;

    print
"</table>";

}
// viewStats


?>

File:Listing13-10.php


<?

include("Listing13-9.php");
if (! isset($
$cookieName)) :

    
// Set a new cookie
    
setcookie($cookieName, $cookieValue, time()+$timeLimit);

    
// Record the visitor information.
    
recordUser();

endif;

?>

<html>

<head>
<title>Welcome to My Site!</title>
</head>

<body bgcolor="#c0c0c0" text="#000000" link="#808040" vlink="#808040" alink="#808040">
Welcome to my site. <a href = "visitors.php">Check out who else has recently visited</a>.
</body>

</html>

File:Listing13-11.php


<?


// assume that the variable $usr_id (containing a unique user ID)
// is stored within a cookie on the users machine.

$usr_id = 15;

$id = session_id($usr_id);

@
mysql_connect("", "root", "") or die("Could not connect to MySQL server!");
@
mysql_select_db("book") or die("Could not select company database!");

$query = "SELECT fname FROM users13 WHERE user_id= '$usr_id'";
$result = mysql_query($query);
$user_data = mysql_result($result, 0, "fname");

session_decode($user_data);

print
"BGCOLOR: $bgcolor";

mysql_close();

?>

File:Listing14-1.xml


<?xml version="1.0"?>

<!DOCTYPE cookbook SYSTEM "cookbook.dtd">
<cookbook>
<recipe category="italian">
<title>Spaghetti alla Carbonara</title>
<description>This traditional Italian dish is sure to please even the most discriminating critic.</description>
<ingredients>
<ingredient>2 large eggs</ingredient>
<ingredient>4 strips of bacon</ingredient>
<ingredient>1 clove garlic</ingredient>
<ingredient>12 ounces spaghetti</ingredient>
<ingredient>3 tablespoons olive oil</ingredient>
</ingredients>
<process>
<step>Combine oil and bacon in large skillet over medium heat. Cook until bacon is brown and crisp.</step>
<step>Whisk eggs in bowl. Set aside.</step>
<step>Cook pasta in large pot of boiling water to taste, stirring occasionally. Add salt as necessary.</step>
<step>Drain pasta and return to pot, adding whisked eggs. Stir over medium-low heat for 2-3 minutes.</step>
<step>Mix in bacon. Season with salt and pepper to taste.</step>
</process>
</recipe>
</cookbook>

File:Listing14-3.php


<?


class XMLHTML {

    VAR
$xmlparser;
    VAR
$tagcolor = "#800000";
    VAR
$datacolor = "#0000ff";

    function
XMLHTML() {

        
$this->xmlparser = xml_parser_create();
        
xml_set_object($this->xmlparser, &$this);
        
xml_set_element_handler($this->xmlparser, "startTag", "endTag");
        
xml_set_character_data_handler($this->xmlparser, "characterData");

    }

// This function is responsible for handling all starting element tags.

function startTag($parser, $tagname, $attributes) {
     GLOBAL
$tagcolor;
     print
"<font size=\"-2\" color=\"$this->tagcolor\" face=\"arial, verdana\">&lt;$tagname&gt;</font> <br>";
}

// This function is responsible for handling all character data.

function characterData($parser, $characterData) {
     GLOBAL
$datacolor;
     print
"<font size=\"-2\" color=\"$this->datacolor\" face=\"arial,  
               verdana
\">&nbsp;&nbsp;&nbsp;$characterData</font> <br>";
}

// This function is responsible for handling all ending element tags.

function endTag($parser, $tagname) {
    GLOBAL
$tagcolor;
    print
"<font size=\"-2\" color=\"$this->tagcolor\" face=\"arial, verdana\">&lt;/$tagname&gt;</font> <br>";
}

function
parse($fp) {

    
// xml_parse($this->xmlparser,$data);

    // Parse the XML file
    
while ( $line = fread($fp, 4096) ) :
         
        
// If something goes wrong, stop and print an error message.

         
if ( ! xml_parse($this->xmlparser, $line, feof($fp))) :
              die(
sprintf("XML error: %s at line %d",
                   
xml_error_string(xml_get_error_code($this->xmlparser)),
                   
xml_get_current_line_number($this->xmlparser)));
         endif;

    endwhile;

}

}
// end class

// Open the XML file for parsing
$xml_file = "bookmarks.xml";

$fp = fopen($xml_file, "r");

$xml_parser = new XMLHTML;

$xml_parser->parse($fp);


?>

File:Listing15-1.php


<?

// retrieve browser information
$browser = get_browser();

// typeset $browser to an array
$browser = (array) $browser;

while (list (
$key, $value) = each ($browser)) :

     
// clarify which of the browser elements are empty
     
if ($value == "") :
          
$value = 0;
     endif;

     print
"$key : $value <br>";

endwhile;
?>

File:Listing15-2.php


<?

$browser
= get_browser();

// typeset $browser to an array
$browser = (array) $browser;

if (
$browser["javascript"] == 1) :
     print
"Javascript enabled!";
else :
     print
"No javascript allowed!";
endif;
?>

File:Listing15-3.php


<html> 

<head>
<title>Browser Information</title>
</head>
<body>
<script language="Javascript1.2">
<!--//

document.write('<form method=POST action ="<? echo $PHP_SELF; ?>">');
document.write('<input type=hidden name=version value=' + navigator.appVersion + '>');
document.write('<input type=hidden name=type value=' + navigator.appName + '>');
document.write('<input type=hidden name=screenWidth value=' + screen.width + '>');
document.write('<input type=hidden name=screenHeight value=' + screen.height + '>');
document.write('<input type=hidden name=browserHeight value=' + window.innerWidth + '>');
document.write('<input type=hidden name=browserWidth value=' + window.innerHeight + '>');
//-->
</script>
<input type="submit" value="Get browser information"><p>
</form>

<?
//if (isset($screenWidth)) :
     
echo "<b>Browser:</b> $type Version: $version<br>";
     echo
"<b>Screen Resolution:</b> $screenWidth x $screenHeight pixels.<br>";
     if (
$browserWidth != 0) :
          echo
"<b>Browser resolution:</b> $browserWidth x $browserHeight pixels.";
     else :
          echo
"No javascript browser resolution support for Internet Explorer";
     endif;
//endif;
?>
</body>
</html>

File:Listing15-4.php


<html>

<head>
<title>Listing 15-4</title>
<SCRIPT language="Javascript">
<!--
     // declare a new Javascript variable
     var popWindow;
     // declare a new function, newWindow
     function newWindow(winID) {
          // declare variable winURL, setting it to the name of the PHP file and accompanying data.
          var  winURL = "Listing15-5.php?winID=" + winID;
          // If the popup window does not exist, or it is currently closed, open it.
          if (! popWindow || popWindow.closed) {
               // open new window having width of 200 pixels, height of 300 pixels, positioned
               // 150 pixels left of the linking window, and 100 pixels from the top of the linking  window.
               popWindow = window.open(winURL, 'popWindow',
                                                            'dependent,width=200,height=300,left=150,top=100');
               }
               // If the popup window is already open, make it active and update its location to winURL.
          else {
               popWindow.focus();
               popWindow.location = winURL;
          }
     }
//-->
</SCRIPT>
</head>
<body bgcolor="#ffffff" text="#000000" link="#808040" vlink="#808040" alink="#808040">

<a href="#" onClick="newWindow(1);">Contact Us</a><br>
<a href="#" onClick="newWindow(2);">Driving Directions</a><br>
<a href="#" onClick="newWindow(3);">Weather Report</a><br>

</body>
</html>

File:Listing15-5.php


<html>

<head>
<title>Popup Window Fun</title>
</head>

<body bgcolor="#ffffff" text="#000000" link="black" vlink="gray" alink="#808040">

     <table width="100%" border="0" cellpadding="0" cellspacing="0">
          <tr>
               <td>
               <?
               
// Include file specified by input parameter
               
INCLUDE("$winID.inc");
               
?>
               </td>
          </tr>
          <tr>
               <td>
               <a href="#" onClick="parent.self.close();">close window</a>
               </td>
          </tr>
     </table>

</body>
</html>

File:Listing15-6.php


<?

// Instantiate a new object pointing to the MS Word application
$word=new COM("word.application") or die("Couldn't start Word!");

// Make MS Word the active window.
$word->visible =1;

// Create a new document
$word->Documents->Add();

// Insert some text into the document
$word->Selection->Typetext("php's com functionality is cool\n");

// Set the default document format to Text
$ok = com_set($word->Application, DefaultSaveFormat, "Text");

// Prompt the user to name and save the document.
// Notice that the default document format is Text!
$word->Documents[1]->Save;

// Quit MS Word
$word->Quit();
?>

File:Listing15-7.php


<?

// Connect to the MySQL server
$host = "localhost";
$user = "root";
$pswd = "";
$db = "book";
$address_table = "addressbook";

mysql_connect($host, $user, $pswd) or die("Couldn't connect to MySQL server!");
mysql_select_db($db) or die("Couldn't select database!");

// Query the company database for all 'addresses' rows
$query = "SELECT * FROM $address_table ORDER BY last_name";
$result = mysql_query($query);

// Instantiate a new COM object. In this case, one pointing to the MS Word application
$word=new COM("word.application") or die("Couldn't start Word!");

// Make MS Word the active Window
$word->visible =1;

// Declare a new, empty document.
$word->Documents->Add();

// Cycle through each address table row.
while($row = mysql_fetch_array($result)) :
     
$last_name = $row["last_name"];
     
$first_name = $row["first_name"];
     
$tel = $row["tel"];
     
$email = $row["email"];

     
// Output table data to the open Word document.

     
$word->Selection->Typetext("$last_name, $first_name\n");
     
$word->Selection->Typetext("tel. $tel\n");
     
$word->Selection->Typetext("email. $email:\n");

endwhile;

// Prompt the user for a document name
$word->Documents[1]->Save;

// Quit the MS Word Application
$word->Quit();
?>

File:Listing16-1.phps


<?

$user_pass
= "123456";

// extract the first two characters of $user_pass for use as salt.
$salt = substr($user_pass, 0, 2);

// encrypt and store password somewhere
$crypt1 = crypt($user_pass, $salt);
// $crypt1 = "12tir.zIbWQ3c"

// . . . user enters password
$entered_pass = "123456";

// get the first two characters of the stored password
$salt1 = substr($crypt, 0, 2);

// encrypt $entered_pass using $salt1 as the salt.
$crypt2 = crypt($entered_pass, $salt1);
// $crypt2 = "12tir.zIbWQ3c";

// Therefore, $crypt1 = $crypt2

?>

File:Listing16-2.php


<?

header
('WWW-Authenticate: Basic realm="Secret Family Recipes"');
header('HTTP/1.0 401 Unauthorized');
exit;
?>

File:Listing16-3.php


<?


if ( (! isset ($PHP_AUTH_USER)) || (! isset ($PHP_AUTH_PW)) ):  
     
header('WWW-Authenticate: Basic realm="Secret Family Recipes"');
     
header('HTTP/1.0 401 Unauthorized');
     print
"You are attempting to enter a restricted area. Authorization is required.";
     exit;
endif;  

?>

File:Listing16-4.php


<?


if ( (! isset ($PHP_AUTH_USER)) || (! isset ($PHP_AUTH_PW)) ||
   (
$PHP_AUTH_USER != 'secret') || ($PHP_AUTH_PW != 'recipes') ) :
  
     
header('WWW-Authenticate: Basic realm="Secret Family Recipes"');
     
header('HTTP/1.0 401 Unauthorized');
     print
"You are attempting to enter a restricted area. Authorization is required.";
     exit;
endif;  

?>

File:Listing16-5.txt


brian:snaidni00

alessia:aiggaips
gary:9avaj9
chris:poghsawcd
matt:tsoptaes

File:Listing16-6.php


<?


$file
= "Listing16-5.txt";
$fp = fopen($file, "r");
$auth_file = fread ($fp, filesize($fp));
fclose($fp);

$authorized = 0;

// assign each line of file as array element
$elements = explode ("\n", $auth_file);

foreach (
$elements as $element) {

     list (
$user, $pw) = split (":", $element);

     if ((
$user == $PHP_AUTH_USER) && ($pw == $PHP_AUTH_PW)) :
          
$authorized = 1;
          break;     
     endif;

}
// end foreach

if (! $authorized) :
          
header('WWW-Authenticate: Basic realm="Secret Family Recipes"');
          
header('HTTP/1.0 401 Unauthorized');
          print
"You are attempting to enter a restricted area. Authorization is required.";
          exit;
else :
          print
"Welcome to the family's secret recipe collection";
endif;
?>

File:Listing16-7.php


<?

if (!isset($PHP_AUTH_USER)) :

     
header('WWW-Authenticate: Basic realm="Secret Family Recipes"');
     
header('HTTP/1.0 401 Unauthorized');
     exit;

else :

     
// connect to the mysql database
     
mysql_connect ("host", "user", "password")
                or die (
"Can't connect to database!");
     
mysql_select_db ("user_info")
                or die (
"Can't select database!");
     
     
// query the user_authenticate table for authentication match
     
$query = "select userid from user_authenticate where
                                              username = '$PHP_AUTH_USER' and
                                              password = '$PHP_AUTH_PW'"
;

    
$result = mysql_query ($query);

     
// if no match found, display authentication window
     
if (mysql_numrows($result) != 1) :

          
header('WWW-Authenticate: Basic realm="Secret Family Recipes"');
          
header('HTTP/1.0 401 Unauthorized');
          exit;

     
// else, retrieve user-Id
     
else :
          
$userid = mysql_result (user_authenticate, 0, $result);
     endif;

endif;

?>