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

1-1.txt   1-2.txt   1-4.txt   1-5.txt   3-1.txt   4-1.txt   4-2.txt   4-3.txt   4-4.txt   4-5.txt   4-6.txt   4-7.txt   4-8.txt   5-1.txt   5-2.txt   6-1.txt   6-2.txt   6-3.txt   6-4.txt   6-5.txt   6-6.txt   6-7.txt   6-8.txt   6-9.txt   6-10.txt   6-11.txt   6-12.txt   6-13.txt   6-14.txt   7-1.txt   7-2.txt   7-3.txt   7-4.txt   7-5.txt   7-6.txt   7-7.txt   7-8.txt   7-9.txt   7-10.txt   8-1.txt   8-2.txt   8-3.txt   9-4.txt   9-5.txt   9-6.txt   9-7.txt   9-8.txt   9-9.txt   9-10.txt   9-11.txt   9-12.txt   9-13.txt   9-14.txt   9-15.txt   10-1.txt   10-2.txt   10-3.txt   10-4.txt   10-5.txt   10-6.txt   10-7.txt   10-8.txt   10-9.txt   10-10.txt   10-11.txt   10-12.txt   10-13.txt   11-1.txt   11-2.txt   11-3.txt   11-4.txt   11-5.txt   11-6.txt   11-7.txt   11-8.txt   11-9.txt   11-10.txt   11-11.txt   11-12.txt   12-1.txt   12-2.txt   12-3.txt   12-4.txt   12-6.txt   12-7.txt   12-8.txt   12-9.txt   12-10.txt   12-11.txt   12-12.txt   13-1.txt   13-2.txt   13-3.txt   13-4.txt   13-5.txt   13-6.txt   13-7.txt   13-8.txt   13-9.txt   13-10.txt   14-1.txt   14-2.txt   14-3.txt   15-1.txt   15-2.txt   15-3.txt   15-4.txt   15-5.txt   15-6.txt   15-7.txt   16-1.txt   16-3.txt   16-4.txt   16-6.txt   16-7.txt  

File:1-1.txt


<?

// Присвоить значения нескольким переменным
$site_title = "PHP Recipes";
$bg_color = "white";
$user_name = "Chef Luigi";
?>

<html>
<head>
<title><? print $site_title; ?></title>
</head>
<body bgcolor="<? print $bg_color; ?>" >
<?
// Вывести приветствие с датой и именем пользователя.
print "
PHP Recipes | "
.date("F d, Y")." <br>
Greetings, $user_name! <br>
"
;
?>
</body>
</html>

File:1-2.txt


<html>

<head>
<title>Basic PHP/HTML integration</title>
</head>
<body>
<?
// Обратите внимание на присутствие тегов HTML в команде print.
print "<h3>PHP/HTML integration is cool.</h3>";
?>
</body>
</html>

File:1-4.txt


<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:1-5.txt


<html>

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

File:3-1.txt


<?

// Приложение: календарь
// Назначение: чтение и анализ содержимого файла
//             с последующим форматированием для вывода в броузере

// Открыть файловый манипулятор $events для файла events.txt
$events = fopen("events.txt", "r");

print
"<table border = 0 width = 250>"
print "<tr><td valign=top";

print
"<h3>Events Calendar:</h3>";

// Читать, пока не будет найден конец файла
while (! feof($events)) :
    
// Прочитать следующую строку файла events.txt
    
$event = fgets($events, 4096);

    
// Разделить компоненты текущей строки на элементы массива

    
$event_info = explode("|", $event);

    
// Отформатировать и вывести информацию о событии
    
print "$event_info[0] ( $event_info[1] ) <br>";
    print
"<b>$event_info[2]</b> <br>";
    print
"$event_info[3] <br> <br>";
endwhile;
// Завершить таблицу
print "</td></tr></table>";

fclose ($events);

?>

File:4-1.txt


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:4-2.txt


$price = 24.99;

$tax = .06;

function calculate_cost($tax, $price) {

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

}

// Обратите внимание на возврат значения функцией calculate_cost().
$total_cost = calculate_cost ($tax, $price);
// Округлить цену до двух десятичных цифр.
$total_cost = round($total_cost, 2);

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

File:4-3.txt


$cost = 1456.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)) :
// Продолжить закупки
print "Keep shopping!";
else :
print "Please lower your total bill to less than $".$limit."!";
endif;

File:4-4.txt


// Сорт вина, для которого выводятся лучшие годы

$label = "merlot";

// Функция использует массивы и "переменную в переменной"
// для возвращения нескольких значений.
function best_years($label) {

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

     return $$label;

}
// Функция list() используется получения возвращаемых значений.
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:4-5.txt


function summation ($count) {

    if ($count != 0) :
        return $count + summation($count-1);
    endif;
}


$sum = summation(10);
print "Summation = $sum";

File:4-6.txt


// Приветствие на итальянском языке.

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

// Приветствие на английском языке
function english() {
    print "Welcome to PHP Recipes.";
}

// Выбрать итальянский язык
$language = "italian";

// Выполнить функцию-переменную
$language();

File:4-7.txt


<?

// Файл: array_sorting.inc
// Назначение: библиотека функций для сортировки массивов.
// Дата: 17 июля 2000 г.

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

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

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

?>

File:4-8.txt


// Предполагается, что библиотека array_sorting.inc

// находится в одном каталоге со сценарием.
include("array_sorting.inc");

// Теперь вы можете использовать любые функции из array_sorting.inc
$some_array = array(50, 42, 35, 46);

// Использовать функцию bubble_sort()

$sorted_array = bubble_sort($some_array, 1);

File:5-1.txt


// Объявить ассоциативный массив стран и языков

$languages = array ("Country" => "Language",
    "Spain" => "Spanish",
    "USA" => "English",
    "France" => "French",
    "Russia" => "Russian");

// Начать новую таблицу
print "<table border=1>";

// Переместить указатель к позиции первого элемента
reset ($languages);
// Прочитать первый ключ и элемент
$hd1 = key ($languages);
$hd2 = $languages[$hd1];

// Вывести первый ключ и элемент в виде заголовков таблицы
print "<tr><th>$hd1</th><th>$hd2</th></tr>";

next($languages);

// Выводить строки таблицы с ключами и элементами массива
while ( list ($ctry,$lang) = each ($languages)) :
     print "<tr><td>$ctry</td><td>$lang</td></tr>";
endwhile;

// Завершить таблицу
print "</table>";

?>

File:5-2.txt


$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() с указанием функции compare_length()
// в качестве критерия сортировки
usort($vocab, "compare_length");

// Вывести отсортированный список
while (list ($key, $val) = each ($vocab)) {
    echo "$val<br>";
}

File:6-1.txt


class Class_name {

    var $attribute_1;
    ...
    var $attribute_N;

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

} // end Class_name

File:6-2.txt


<?

class Webpage {
    var
$bgcolor;

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

// Вызвать конструктор класса Webpage
$page = new Webpage("brown");
?>

File:6-3.txt


<?

// Транспортное средство
class Vehicle {
    var
$model;
    var
$current_speed;

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

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

}

// Автомобиль
class Auto extends Vehicle {
    var
$fuel_type;

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

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

}

// Самолет
class Airplane extends Vehicle {
    var
$wingspan;
    
    function
setWingSpan($wingspan) {
        
$this->wingspan = $wingspan;
    }

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

?>

File:6-4.txt


<?


class Vehicle {
    
Объявления атрибутов...
    
Объявления методов...
}

class
Land extends Vehicle {
    
Объявления атрибутов...
    
Объявления методов...
}

class
Car extends Land {
    
Объявления атрибутов...
    
Объявления методов...
}

$nissan = new Car;
?>

File:6-5.txt


<?


class Vehicle {
    
Объявления атрибутов...

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

    
Объявления других методов...
}

class
Land extends Vehicle {
    
Объявления атрибутов...

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

    
Объявления других методов...
}

class
Car extends Land {
    
Объявления атрибутов...
    
Объявления методов...
}

?>

File:6-6.txt


<?

class Page {
    var
$bgcolor;
    var
$textcolor;    

    function
Page() {
        
// Определить количество переданных аргументов
        // и вызвать метод с нужным именем
        
$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:6-7.txt


<?

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

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

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

$cls_methods = get_class_methods(Airplane);
// Массив $cls_methods содержит имена всех методов,
// объявленных в классах "Airplane" и "Vehicle"

?>

File:6-8.txt


<?


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:6-9.txt


<?

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;
// Выходные данные:
// doors ==> 2
// engine ==> 400
// wheels ==> 2
?>

File:6-10.txt


<?

class Vehicle {
    . . .
    }

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

    
//  Создать объект с именем $car
    
$car = new Land;

    
// Если метод "fourWheelDrive" поддерживается классом "Land"
    // или "Vehicle", вызов method_exists возвращает TRUE;
    // в противном случае возвращается FALSE.
    // В данном примере method_exists() возвращает 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:6-11.txt


<?

class Vehicle {
    . . .
}

class
Land extends Vehicle {
    . . .
}

// Создать объект с именем $car
$car = new Land;

// Переменной $class_a присваивается строка "Land"
$class_a = get_class($car);
?>

File:6-12.txt


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}

// Создать объект с именем $car
$car = new Land;

// Переменной $parent присваивается строка "Vehicle"
$parent = get_parent_class($car);
?>

File:6-13.txt


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}
$auto = new Land;
// Переменной $is_subclass присваивается TRUE
$is_subclass = is_subclass_of($auto, "Vehicle");
?>

File:6-14.txt


<?

class Vehicle {
. . .
}

class
Land extends Vehicle {
. . .
}

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

?>

File:7-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:7-2.txt


<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:7-3.txt


<?

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

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

fclose($fh);
?>

File:7-4.txt


<?

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

File:7-5.txt


<?

$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:7-6.txt


<?

function getthehost($host,$path) {
    
// Открыть подключение к узлу
    
$fp = fsockopen($host, 80, &$errno, &$errstr, 30);
    
// Перейти в блокирующий режим
    
socket_set_blocking($fp, 1);
    
// Отправить заголовки
    
fputs($fp,"GET $path HTTP/1.1\r\n");
    
fputs($fp,"Host: $host\r\n\r\n");
    
$x = 1;
    
// Получить заголовки
    
while($x < 10) :
        
$headers = fgets($fp,4096);
        print
$headers;
        
$x++;
    endwhile;

    
// Закрыть манипулятор
    
fclose($fp);
}

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

File:7-7.txt


<?

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

File:7-8.txt


drwxr-xr-x 4 root  wheel   512 Aug 13  13:51  book/

drwxr-xr-x 4 root  wheel   512 Aug 13  13:51  code/
-rw-r--r-- 1 root  wheel   115 Aug  4  09:53  index.html
drwxr-xr-x 7 root  wheel  1024 Jun 29  13:03  manual/
-rw-r--r-- 1 root  wheel   19  Aug 12  12:15  test.php

File:7-9.txt


<?

// Сценарий: простой счетчик обращений
// Назначение: сохранение количества обращений в файле

$access = "hits.txt";            // Имя файла выбирается произвольно
$visits = @file($access);        // Прочитать содержимое файла в масссив
$current_visitors = $visits[0];  // Извлечь первый (и единственный) элемент
++$current_visitors;             // Увеличить счетчик обращений
$fh = fopen($access, "w");       // Открыть файл hits.txt и установить
                            // указатель текущей позиции в начало файла
@fwrite($fh, $current_visitors); // Записать новое значение счетчика
                            // в файл "hits.txt"
fclose($fh);                     // Закрыть манипулятор файла "hits.txt"

?>

File:7-10.txt


<?

// Файл: sitemap.php
// Назначение: построение карты сайта

// Каталог, с которого начинается построение карты
$beg_path = "C:\Program Files\Apache Group\Apache\htdocs\phprecipes";

// Файл с графическим изображением папки.
// Путь должен задаваться *относительно* корневого каталога сервера Apache
$folder_location = "C:\My Documents\PHP for Programmers\FINAL CHPS\graphics\folder.gif";

// Текст в заголовке окна
$page_name = "PHPRecipes SiteMap";

// В какой системе будет использоваться сценарий - Linux или Windows?
// (0 - Windows; 1 - Linux)
$using_linux = 0;
// Функция:  display_directory
// Назначение: чтение содержимого каталога, определяемого параметром
// $dir1, с последующим форматированием иерархии каталогов и файлов.
// Функция может вызываться рекурсивно.

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

// Обновить путь
$dir .= $dir1;
$dh = opendir($dir);

while (
$file = readdir($dh)) :
    
// Элементы каталогов "." и ".." не выводятся.
    
if ( ($file != ".") && ($file != "..") ) :

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

        
// Построить путь по правилам используемой операционной системы.
        
if ($using_linux == 0) :
            
$tab_depth = $current_depth - $init_depth;    
            
$file = $dir."\\".$file;
        else :
            
$file = $dir."/".$file;
        endif;

        
// Переменная $file содержит каталог?
        
if ( is_dir($file) ) :
            
$x = 0;
            
// Вычислить отступ
            
while ( $x < ($tab_depth * 2) ) :
                print
"&nbsp;";
                
$x++;
            endwhile;

            print
"<img src=\"$folder_location\" alt=\"[dir]\"> ".basename($file)."<br>";
            
// Увеличить счетчик &nbsp;

            // Рекурсивный вызов функции display_directory()
            
display_directory($file, $folder_location, $using_linux, $init_depth);

        
// Не каталог
        
else :
            
// Построить путь по правилам используемой
            // операционной системы.
            
if ($using_linux == 0) :
                
$tab_depth = ($current_depth - $init_depth) - 2;
                
$x = 0;
                
// Вычислить отступ
                
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;

// Закрыть каталог
closedir($dh);
}
?>
<html>
<head>
<title> <? print "$page_name"; ?> </title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#000000" vlink="#000000" alink="#000000">
<?
// Вычислить начальный отступ
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:8-1.txt


<?

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

// Разделить $url на три компонента: "http://www", "apress" и "com"
$www_url = ereg("^(http://www)\.([[:alnum:]]+)\.([[:alnum:]]+)", $url, $regs);

if (
$www_url) :        // Если переменная $www_url содержит URL
    
echo $regs[0];     // Вся строка "http://www.apress.com"
    
print "<br>";
    echo
$regs[1];     // "http://www"
    
print "<br>";
    echo
$regs[2];     // "apress"
    
print "<br>";
    echo
$regs[3];     // "com"
endif;
?>

File:8-2.txt


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


// Переменная $meta_tags содержит массив со следующей информацией:

// $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:8-3.txt


<?

/*
Файл : sniffer.php
Назначение: Идентификация типа/версии броузера и платформы
Автор: В. Дж. Гилмор
Дата : 24 августа 2000 г.
*/

// Функция: browser_info
// Назначение: Возврщаает тип и версию броузера

function browser_info ($agent) {
    
// Определить тип броузера
    //  Искать сигнатуру Internet Explorer
    
if (ereg( 'MSIE ([0-9].[0-9]{1,2})', $agent, $version)) :
        
$browse_type = "IE";
        
$browse_version = $version[1];

    
// Искать сигнатуру Opera
    
elseif (ereg( 'Opera ([0-9].[0-9]{1,2})', $agent, $version)) :
        
$browse_type = "Opera";
        
$browse_version = $version[1];

    
//  Искать сигнатуру Netscape. Проверка броузера Netscape
    //  *должна* выполняться после проверки Internet Explorer и Opera,
    //  поскольку все эти броузеры любят сообщать имя
    //  Mozilla вместе с настоящим именем.
    
elseif (ereg( 'Mozilla/([0-9].[0-9]{1,2})', $agent, $version)) :
        
$browse_type = "Netscape";
        
$browse_version = $version[1];

    
// Если это не Internet Explorer, Opera или Netscape -
    // значит, мы обнаружили неизвестный броузер.
    
else :
        
$browse_type = "Unknown";
        
$browse_version = "Unknown";

    endif;

    
// Вернуть тип и версию броузера в виде массива
    
return array($browse_type, $browse_version);

}
// Конец функции browser_info

// Функция: opsys_info
// Назначение: Возвращает информацию об операционной системе пользователя

function opsys_info($agent) {
    
// Идентифицировать операционную систему
    // Искать сигнатуру Windows
    
if ( strstr ($agent, 'Win') ) :
        
$opsys = "Windows";

    
// Искать сигнатуру Linux
    
elseif ( strstr($agent, 'Linux') ) :
        
$opsys = "Linux";

    
// Искать сигнатуру UNIX
    
elseif ( strstr ($agent, 'Unix') ) :
        
$opsys = "Unix";

    
// Искать сигнатуру Macintosh
    
elseif ( strstr ($agent,'Mac') ) :
        
$opsys = "Macintosh";

    
// Неизвестная платформа
    
else :
        
$opsys = "Unknown";

    endif;

    
// Вернуть информацию об операционной системе
     
return $opsys;

}
// Конец функции opsys_info

// Сохранить возвращаемый массив в списке

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:9-4.txt


<? 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:9-5.txt


<?

// Файл: header.tpl
// Назначение: заголовочный файл для сайта PhpRecipes
// Дата: 22 августа 2000 г.

$site_name = "PHPRecipes";
$site_email = "wjgilmore@hotmail.com";
$site_path = "http://localhost/phprecipes";
?>
<html>
<head>
<title> <? print $site_name; ?> </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">
    PHPRecipes    
    </td>
    <td valign = "top" align="right">
    <?
    
// Вывести текущую дату и время
    
print date ("F d, h:i a");
    
?>
    </td>
    </tr>
</table>

File:9-6.txt


<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:<?=$site_email;?>">contact</a> | <a href = "<?=$site_path;?>/privacy.php">your privacy</a>
</td></tr>
</table>
</body>
</html>

File:9-7.txt


<table width="95%" cellspacing="0" cellpadding="0" border="1">

<tr>
<td valign="top" width="25%">
<a href = "<?=$site_path;?>/tutorials.php">tutorials</a> <br>
<a href = "<?=$site_path;?>/articles.php">articles</a> <br>
<a href = "<?=$site_path;?>/scripts.php">scripts</a> <br>
<a href = "<?=$site_path;?>/contact.php">contact</a> <br>
</td>
<td valign="top" width="75%">
Welcome to PHPRecipes, the starting place for PHP scripts, tutorials, and information about gourmet cooking!
</td>
</tr>
</table>

File:9-8.txt


<?

// Файл: index.php
// Назначениее: домашняя страница PHPRecipes
// Дата: 23 августа 2000 г.
// Вывести заголовок
include ("header.tpl");
// Вывести основную часть
include ("index_body.tpl");
// Вывести колонтитул
include ("footer.tpl");
?>

File:9-9.txt


<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:9-10.txt


<?

// Файл: site_init.tpl
// Назначение: инициализационный файл PhpRecipes
// Дата: 22 августа 2000 г.

$site_name = "PHPRecipes";
$site_email = "wjgilmore@hotmail.com";
$site_path = "http://localhost/phprecipes/";

function
show_header($site_name) {
?>
<html>
<head>
<title> <? print $site_name; ?> </title>
</head>
<body bgcolor="#7b8079" text="#ffffff" link="#e7d387" alink="#e7d387" vlink="#e7f0e4">
This is the header
<hr>
<?
}

function
show_footer() {
?>
<hr>
This Is the footer
</body>
</html>
<?
}
?>

File:9-11.txt


<?

// Включить инициализацонный файл
include("site_init.tpl");

// Вывести заголовок
show_header($site_name);
?>
// Содержимое основной части
This is some body information
<?
// Вывести колонтитул
show_footer();
?>

File:9-12.txt


<h3>About PHPRecipes</h3>

What programmer doesn't mix all night programming with gourmet cookies. Here at PHPRecipes, hardly a night goes by without one of our coders mixing a little bit of HTML with a tasty plate of Portobello Mushrooms or even Fondue. So we decided to bring you the best of what we love most: PHP and food!
<p>
That's right, readers. Tutorials, scripts, souffles and more. <i>Only</i> at PHPRecipes.

File:9-13.txt


<h3>Advertising Information</h3>

Regardless of whether they come to learn the latest PHP techniques or for brushing up on how to bake chicken, you can bet our readers are decision makers. They are the Industry professionals who make decisions about what their company purchases.
For advertising information, contact <a href = "mailto:ads@phprecipes.com ">ads@phprecipes.com</a>.

File:9-14.txt


<h3>Contact Us</h3>

Have a coding tip? <br>
Know the perfect topping for candied yams?<br>
Let us know! Contact the team at <a href = "mailto:theteam@phprecipes.com">team@phprecipes.com</a>.

File:9-15.txt


<?

// Файл: static.php
// Назначение: отображение запрашиваемых статических страниц.
// ВНИМАНИЕ: предполагается, что файл "site_init.tpl" и все
// статические файлы находятся в том же каталоге.

// Загрузить функции и переменные
include("site_init.tpl");

// Вывести заголовок
show_header($site_name);

// Вывести запрашиваемое содержание
include("$content.html");

// Вывести колонтитул
show_footer();

?>

File:10-1.txt


<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:10-2.txt


<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:10-3.txt


<html>

<head>
<title>Listing 10-3</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// Вывести имя и адрес электронной почты.
print "Hi, $name!. Your email address is $email";
?>
</body>
</html>

File:10-4.txt


<html>

<head>
<title>Listing 10-4</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// Все кавычки внутри $form должны экранироваться,
// в противном случае произойдет ошибка.
$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>"
;
// Если форма ранее не отображалась, отобразить ее.
// Для проверки используется значение скрытой переменной $seenform.
if ($seenform != "y"):
    print
"$form";
else :
    print
"Hi, $name!. Your email address is $email";
endif;
?>
</body>
</html>

File:10-5.txt


<html>

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

<?
// Все кавычки внутри $form должны экранироваться,
// в противном случае произойдет ошибка.
$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>
"
;

// Если форма ранее не отображалась, отобразить ее.
// Для проверки используется значение скрытой переменной $seenform.
if ($seenform != "y") :
    print
"$form";
else :
    
// Переменная $recipient определяет получателя данных формы
    
$recipient = "yourname@youremail.com";
    
// Тема сообщения
    
$subject = "User Comments ($name)";
    
// Дополнительные заголовки
    
$headers = "From: $email";
    
// Отправить сообщение или выдать сообщение об ошибке
    
mail($recipient, $subject, $comments, $headers) or die("Could not send email!");
    
// Вывести сообщение для пользователя
    
print "Thank you $name for taking a moment to send us your comments!";

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

File:10-6.txt


<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";
    
// Перебрать все пары "ключ/значение"
    
while ( list($key, $val) = each ($information) ) :
        
// Сравнить текущее значение с "y"
        
if ($val == "y") :
               
               
// Построить имя файла, соответствующее текущему ключу
               
$filename = "$key.txt";
               
$subject = "Requested $key information";
               
               
// Открыть файл
               
$fd = fopen ($filename, "r");
               
// Прочитать содержимое всего файла в переменную
               
$contents = fread ($fd, filesize ($filename));
               
               
// Отправить сообщение
               
mail($email, $subject, $contents, $headers) or die("Can't send email!");;
               
fclose($fd);
          endif;
     endwhile;
     
// Известить пользователя об успешной отправке
     
print sizeof($information)." informational newsletters have been sent to $email!";
endif;
?>
</body>
</html>

File:10-7.txt


<html>

<head>
<title>Listing 10-7</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// Создать форму
$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>"
;

// Заполнялась ли форма ранее?
if ($seenform != "y") :
    print
"$form";
else :
    
$fd = fopen("user_information.txt", "a");

    
// Убедиться, что во введенных данных не встречается
    // вертикальная черта.
    
$name = str_replace("|", "", $name);
    
$email = str_replace("|", "", $email);

    
// Построить строку с пользовательскими данными
    
$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:10-8.txt


<html>

<head>
<title>Listing 10-8</title>
</head>
<body bgcolor="#ffffff" text="#000000" link="#cbda74" vlink="#808040" alink="#808040">
<?
// Создать форму
$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>"
;

// Заполнялась ли форма ранее?
if ($seenform != "y"):
    print
"$form";

// Пользователь заполнил форму. Проверить введенные данные.
else :
    
$error_flag = "n";
    
// Убедиться в том, что поле имени содержит информацию
    
if ($name == "") :
        print
"<font color=\"red\">* You forgot to enter your name!</font> <br>";
        
$error_flag = "y";
    endif;
    
// Убедиться в том, что поле адреса содержит информацию
    
if ($email == "") :

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

    else :    
        
// Преобразовать все алфавитные символы в адресе
        // электронной почты к нижнему регистру
        
$email = strtolower(trim($email));
        
// Убедиться в правильности синтаксиса
        // адреса электронной почты
        
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;

    
// Если флаг ошибки $error_flag установлен,
    // заново отобразить форму
    
if ($error_flag == "y") :
        print
"$form";
    else :
        
// Обработать данные пользователя
        
print "You entered valid form information!";
    endif;
endif;
?>
</body>
</html>

File:10-9.txt


<?

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");

// Создать форму
?>
<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:10-10.txt


<?

// Файл: init.inc
// Назначение: глобальные переменные и функции для проекта гостевой книги

// Заголовок страницы по умолчанию
$title = "My Guestbook";

// Цвет фона
$bg_color = "white";

// Гарнитура шрифта
$font_face = "Arial, Verdana, Times New Roman";

// Цвет шрифта
$font_color = "black";

// Дата отправки
$post_date = date("M d y");

// Файл данных гостевой книги
$guest_file = "comments.txt";

// Функция читает данные гостевой книги
// и отображает их в броузере
function view_guest($guest_file) {

    GLOBAL
$font_face, $font_color;
    print
"Return to <a href=\"index.php\">index</a>.<br><br>";

    
// Если в файле гостевой книги имеются данные...
    
if (filesize($guest_file) > 0) :

        
// Открыть файл данных гостевой книги
        
$fh = fopen($guest_file, "r") or die("Couldn't open $guest_file");
        print
"<table border=1 cellpadding=2 cellspacing=0 width=\"600\">";

        
// Повторять до конца файла
        
while (! feof($fh)) :

            
// Прочитать следующую строку
            
$line = fgets($fh, 4096);

            
// Разбить строку на компоненты
            // и присвоить каждый компонент переменной
            
list($date, $name, $email, $comments) = explode("|", $line);

            
// Если указано имя посетителя, вывести его
            
if ($name != "") :
            print
"<tr>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">Date:</font></td>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">$date</font></td>";
            print
"</tr>";

            print
"<tr>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">Name:</font></td>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">$name</font></td>";
            print
"</tr>";

            print
"<tr>";        
            print
"<td><font color=\"$font_color\" face=\"$font_face\">Email:</font></td>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">$email</font></td>";
            print
"</tr>";

            print
"<tr>";
            print
"<td valign=\"top\"><font color=\"$font_color\" face=\"$font_face\">Message:</font></td>";
            print
"<td><font color=\"$font_color\" face=\"$font_face\">$comments</font></td>";
            print
"</tr>";

            print
"<tr><td colspan=\"2\">&nbsp;</td></tr>";
            endif;

        endwhile;

        print
"</table>";

        
// Закрыть файл
        
fclose($fh);

    else :

        print
"<h3>Currently there are no entries in the guestbook!</h3>";

    endif;

}
// view_guest

// Функция сохраняет новую информацию в файле данных
function add_guest($name, $email, $comments) {

    GLOBAL
$post_date, $guest_file;

    
// Отформатировать данные для ввода
    
$contents = "$post_date|$name|$email|$comments\n";

    
// Открыть файл данных
    
$fh = fopen($guest_file, "a") or die("Could not open $guest_file!");

    
// Записать данные в файл
    
$wr = fwrite($fh, $contents) or die("Could not write to $guest_file!");

    
// Закрыть файл
    
fclose($fh);

}
// add_guest


?>

File:10-11.txt


<html>

<?
INCLUDE("init.inc");
?>
<head>
<title><?=$page_title;?></title>
</head>

<body bgcolor="<?=$bg_color;?>" text="#000000" link="#808040" vlink="#808040" alink="#808040">


<a href="view_guest.php">View the guestbook!</a><br>
<a href="add_guest.php">Sign the guestbook!</a><br>

</body>

</html>

File:10-12.txt


<html>

<?
INCLUDE("init.inc");
?>
<head>
<title><?=$page_title;?></title>
</head>

<body bgcolor="<?=$bg_color;?>" text="#000000" link="#808040" vlink="#808040" alink="#808040">

<?

view_guest
($guest_file);

?>

File:10-13.txt


<html>

<?
INCLUDE("init.inc");
?>
<head>
<title><?=$page_title;?></title>
</head>

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

<?
// Если форма еще не отображалась - запросить данные у пользователя
if (! $seenform) :
?>

<form action="add_guest.php" method="post">
<input type="hidden" name="seenform" value="y">

Name:<br>
<input type="text" name="name" size="15" maxlength="30" value=""><br>

Email:<br>
<input type="text" name="email" size="15" maxlength="35" value=""><br>

Comment:<br>
<textarea name="comment" rows="3" cols="40"></textarea><br>
<input type="submit" value="submit">
</form>
<?

// Форма уже отображалась - добавить данные в текстовый файл.
else :

    
add_guest($name, $email, $comment);

    print
"<h3>Your comments have been added to the guestbook. <a href=\"index.php\">Click here</a> to return to the index.</h3>";

endif;

?>

File:11-1.txt


<?

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

// Выбрать все записи из таблицы products
$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:11-2.txt


<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:11-3.txt


<?

@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:11-4.txt


<?

@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:11-5.txt


<?

$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 ($seenform != "y") :
    print
$form;
else :
    
// Подключиться к серверу MySQL и выбрать базу данных
    
@mysql_connect("localhost", "web", "ffttss")
                or die(
"Could not connect to MySQL server!");
    @
mysql_select_db("company")
                or die(
"Could not select company database!");

    
// Построить и выполнить запрос
    
$query = "SELECT cust_id, cust_name, cust_email
            FROM customers WHERE $category = '$keyword'"
;
    
$result = mysql_query($query);

    
// Если совпадения не найдены, вывести сообщение
    // и заново отобразить форму
    
if (mysql_num_rows($result) == 0) :
        print
"Sorry, but no matches were found. Please try your search again:";
        print
$form;
    
// Найдены совпадения. Отформатировать и вывести результаты.
    
else :
        
// Отформатировать и вывести значения полей.
        
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>";
        
// Построить и выполнить запрос к таблице 'orders'
        
$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>";
        
// Отформатировать и вывести найденные записи.
        
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:11-6.txt


<?

// Подключиться к серверу MySQL и выбрать базу данных
@mysql_connect("localhost", "web", "ffttss")
            or die(
"Could not connect to MySQL server!");
@
mysql_select_db("company")
            or die(
"Could not select company database!");

// Если значение переменной $key не задано, по умолчанию
// используется значение 'quantity'
if (! isset($key)) :
    
$key = "quantity";
endif;
// Создать и выполнить запрос.
// Выбранные данные сортируются по убыванию столбца $key
$query = "SELECT order_id, cust_id, prod_id, quantity FROM orders ORDER BY $key DESC";
$result = mysql_query($query);
// Создать заголовок таблицы
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>"
;
// Отформатировать и вывести каждую строку таблицы
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;
// Завершить таблицу
print "</table>";
?>

File:11-7.txt


<?php


// Подключиться к источнику данных ODBC 'ContactDB'
$connect = odbc_connect("ContactDB","","")
            or die(
"Couldn't connect to datasource.");

// Создать текст запроса

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

// Подготовить запрос
$result = odbc_prepare($connect,$query);

// Выполнить запрос и вывести результаты
odbc_execute($result);
odbc_result_all($result,"BGCOLOR='#c0c0c0' border=1");

// Обработка результатов закончена, освободить память
odbc_free_result($result);

// Закрыть соединение
odbc_close($connect);

?>

File:11-8.txt


<?

// Файл: init.inc
// Назначение: глобальные переменные и функции,
// используемые в проекте

// Стандартный заголовок страницы
$title = "My Bookmark Repository";

// Цвет фона
$bg_color = "white";

// Дата
$post_date = date("Ymd");

// Категории
$categories = array(
        
"computers",
        
"entertainment",
        
"dining",
        
"lifestyle",
        
"government",
        
"travel");

// Данные сервера MySQL
$host = "localhost";
$user = "root";
$pswd = "";

// Имя базы данных
$database = "book";

// Имя таблицы
$bookmark_table = "bookmarks";

// Цвет ячеек таблицы
$cell_color = "#c0c0c0";

// Установить соединение с сервером MySQL
@mysql_pconnect($host, $user, $pswd) or die("Couldn't connect to MySQL server!");

// Выбрать базу данных
@mysql_select_db($database) or die("Couldn't select $database database!");

// Функция: add_bookmark()
// Назначение: включение новой ссылки в таблицу bookmark.

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

// Функция: view_bookmark()
// Назначение: выборка из таблицы bookmark всех ссылок,
// относящихся к категории $category.

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:11-9.txt


<html>

<?
INCLUDE("init.inc");
?>
<head>
<title><?=$title;?></title>
</head>

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

<?
if (! $seenform) :
?>

<form action="add_bookmark.php" method="post">
<input type="hidden" name="seenform" value="y">

Category:<br>
<select name="category">
<option value="">Choose a category:
<?
while (list($key, $value) = each($categories)) :

     print
"<option value=\"$key\">$value";

endwhile;
?>
</select><br>

Site Name:<br>
<input type="text" name="site_name" size="15" maxlength="30" value=""><br>

URL: (do <i>not</i> include "http://"!)<br>
<input type="text" name="url" size="35" maxlength="50" value=""><br>

Description:<br>
<textarea name="description" rows="4" cols="30"></textarea><br>
<input type="submit" value="submit">
</form>
<?
else :

    
add_bookmark($category, $site_name, $url, $description);

    print
"<h4>Your bookmark has been added to the repository. <a href=\"Listing11-11.php\">Click here</a> to return to the index.</h4>";

endif;
?>

File:11-10.txt


<html>

<?
INCLUDE("Listing11-8.php");
?>
<head>
<title><?=$title;?></title>
</head>

<body bgcolor="<?=$bg_color;?>" text="#000000" link="#808040" vlink="#808040" alink="#808040">
<?
view_bookmark
($category);
?>

File:11-11.txt


<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>
<?
// Перебрать категории и создать соответствующие ссылки
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:11-12.txt


<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:12-1.txt


<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:12-2.txt


function register_file($file_id, $file_name) {


// Открыть $file_name для чтения или завершить программу
// с выдачей сообщения об ошибке.
$fh = fopen($file_name, "r") or die("Couldn't open $file_name!");

// Прочитать все содержимое файла $file_name в переменную.
$file_contents = fread($fh, filesize($file_name));

// Присвоить содержимое элементу массива
// с ключом $file_id.
$this->files[$file_id] = $file_contents;

// Работа с файлом завершена, закрыть его.
fclose($fh);

}

File:12-3.txt


function register_variables($file_id, $variable_name) {


    // Попытаться создать массив,
    // содержащий переданные имена переменных
    $input_variables = explode(",", $variable_name);

    // Перебрать имена переменных
    while (list(,$value) = each($input_variables)) :

        // Присвоить значение очередному элементу массива $this->variables
        $this->variables[$file_id][] = $value;

    endwhile;

}

File:12-4.txt


function file_parser($file_id) {


    // Сколько переменных зарегистрировано для данного файла?
    $varcount = count($this->variables[$file_id]);

    // Сколько файлов зарегистрировано?
    $keys = array_keys($this->files);

    // Если файл $file_id существует в массиве $this->files
    // и с ним связаны зарегистрированные переменные
    if ( (in_array($file_id, $keys)) && ($varcount > 0) ) :

        // Сбросить $x
        $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;

            // Выполнить замену.
            $this->files[$file_id] = str_replace(
                                        $needle,
                                        $$string,
                                        $this->files[$file_id]);
            // Увеличить $x
            $x++;
        endwhile;
    endif;
}

File:12-6.txt


<?

// Включить класс шаблона.
include("template.class");

// Присвоить значения переменным
$page_title = "Welcome to your homepage!";
$bg_color = "white";
$user_name = "Chef Jacques";

// Создать новый экземпляр класса
$template = new template;

// Зарегистрировать файл "homepage.html" с псевдонимом "home"
$template->register_file("home", "homepage.html");

// Зарегистрировать переменные
$template->register_variables("home", "page_title,bg_color,user_name");
$template->file_parser("home");
// Передать результат в броузер
$template->print_file("home");

?>

File:12-7.txt


<?

class template {

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

// Функция: register_file()
// Назначение: сохранение в массиве содержимого файла,
// определяемого идентификатором $file_id

function register_file($file_id, $file_name) {

    
// Открыть $file_name для чтения или завершить программу
    // с выдачей сообщения об ошибке.
    
$fh = fopen($file_name, "r") or die("Couldn't open $file_name!");

    
// Прочитать все содержимое файла $file_name в переменную.
    
$file_contents = fread($fh, filesize($file_name));

    
// Присвоить содержимое элементу массива
    // с ключом $file_id.
    
$this->files[$file_id] = $file_contents;

    
// Работа с файлом завершена, закрыть его.
    
fclose($fh);
}

// Функция: register_variables()
// Назначение: сохранение переменных, переданных
// в параметре $variable_name, в массиве с ключом $file_id.

function register_variables($file_id, $variable_name) {

    
// Попытаться создать массив,
    // содержащий переданные имена переменных
    
$input_variables = explode(",", $variable_name);

    
// Перебрать имена переменных
    
while (list(,$value) = each($input_variables)) :

        
// Присвоить значение очередному элементу массива $this->variables
        
$this->variables[$file_id][] = $value;        

    endwhile;            

}

// Функция: file_parser()
// Назначение: замена всех зарегистрированных переменных
// в     файле с идентификатором $file_id

function file_parser($file_id) {

    
// Сколько переменных зарегистрировано для данного файла?
    
$varcount = count($this->variables[$file_id]);

    
// Сколько файлов зарегистрировано?
    
$keys = array_keys($this->files);

    
// Если файл $file_id существует в массиве $this->files
    // и с ним связаны зарегистрированные переменные
    
if ( (in_array($file_id, $keys)) && ($varcount > 0) ) :

        
// Сбросить $x
        
$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;

            
// Выполнить замену.
            
$this->files[$file_id] = str_replace(
                                        
$needle,
                                        $
$string,
                                        
$this->files[$file_id]);
            
// Увеличить $x
            
$x++;
        endwhile;
    endif;
}

// Функция: print_file()
// Назначение: вывод содержимого файла,
// определяемого параметром $file_Id

function print_file($file_id) {
    
// Вывести содержимое файла с идентификатором $file_id
    
print $this->files[$file_id];
}

}

File:12-8.txt


<html>

<head>
<title>:::::{page_title}:::::</title>
</head>
<body bgcolor="white">

<table cellpadding=2 cellspacing=2 width=600>
<h1>Address Book: {letter}</h1>
<tr><td>
<a href="index.php?letter=a">A</a> | <a href="index.php?letter=b">B</a> |
<a href="index.php?letter=c">C</a> | <a href="index.php?letter=d">D</a> |
<a href="index.php?letter=e">E</a> | <a href="index.php?letter=f">F</a> |
<a href="index.php?letter=g">G</a> | <a href="index.php?letter=h">H</a> |
<a href="index.php?letter=i">I</a> | <a href="index.php?letter=j">J</a> |
<a href="index.php?letter=k">K</a> | <a href="index.php?letter=l">L</a> |
<a href="index.php?letter=m">M</a> | <a href="index.php?letter=n">N</a> |
<a href="index.php?letter=o">O</a> | <a href="index.php?letter=p">P</a> |
<a href="index.php?letter=q">Q</a> | <a href="index.php?letter=r">R</a> |
<a href="index.php?letter=s">S</a> | <a href="index.php?letter=t">T</a> |
<a href="index.php?letter=u">U</a> | <a href="index.php?letter=v">V</a> |
<a href="index.php?letter=w">W</a> | <a href="index.php?letter=x">X</a> |
<a href="index.php?letter=y">Y</a> | <a href="index.php?letter=z">Z</a>
</td></tr>

{rows.addresses}
</table>
</body>
</html>

File:12-9.txt


<tr><td bgcolor="#c0c0c0">

<b>{last_name},{first_name}</b>
</td></tr>
<tr><td>
<b>{telephone}</b>
</td></tr>
<tr><td>
<b><a href = "mailto:{email}">{email}</a></b>
</td></tr>

File:12-10.txt


<html>

<head>
<title>:::::Address Book:::::</title>
</head>
<body bgcolor="white">

<table cellpadding=2 cellspacing=2 width=600>
<h1>Address Book: f</h1>
<tr><td>
<a href="index.php?letter=a">A</a> | <a href="index.php?letter=b">B</a> |
<a href="index.php?letter=c">C</a> | <a href="index.php?letter=d">D</a> |
<a href="index.php?letter=e">E</a> | <a href="index.php?letter=f">F</a> |
<a href="index.php?letter=g">G</a> | <a href="index.php?letter=h">H</a> |
<a href="index.php?letter=i">I</a> | <a href="index.php?letter=j">J</a> |
<a href="index.php?letter=k">K</a> | <a href="index.php?letter=l">L</a> |
<a href="index.php?letter=m">M</a> | <a href="index.php?letter=n">N</a> |
<a href="index.php?letter=o">O</a> | <a href="index.php?letter=p">P</a> |
<a href="index.php?letter=q">Q</a> | <a href="index.php?letter=r">R</a> |
<a href="index.php?letter=s">S</a> | <a href="index.php?letter=t">T</a> |
<a href="index.php?letter=u">U</a> | <a href="index.php?letter=v">V</a> |
<a href="index.php?letter=w">W</a> | <a href="index.php?letter=x">X</a> |
<a href="index.php?letter=y">Y</a> | <a href="index.php?letter=z">Z</a>
</td></tr>

<tr><td bgcolor="#c0c0c0">
<b>Fries,Bobby</b>
</td></tr>
<tr><td>
<b>(212) 563-5678</b>
</td></tr>
<tr><td>
<b><a href = "mailto:bobby@fries.com">bobby@fries.com</a></b>
</td></tr>
<tr><td bgcolor="#c0c0c0">
<b>Frenchy,Pierre</b>
</td></tr>
<tr><td>
<b>002-(30)-09-7654321</b>
</td></tr>
<tr><td>
<b><a href = "mailto:frenchy@frenchtv.com">frenchy@frenchtv.com</a></b>
</td></tr>
</table>
</body>
</html>

File:12-11.txt


class template {


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

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

    VAR $address_table = "addressbook";
. . .

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

    // Подключиться к серверу MySQL и выбрать базу данных
    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);

    // Открыть файл "rows.addresses"
    // и прочитать его содержимое в переменную
    $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;

    // Включить ключ в массив variables для последующего поиска
        $this->variables[$file_id][] = $variable_name;        

    // Закрыть файловый манипулятор
    fclose($fh);

    }
. . .

}

File:12-12.txt


<?


include("Listing12-11.php");

$page_title = "Address Book";

// По умолчанию загружается страница с фамилиями,
// начинающимися с буквы 'a'
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:13-1.txt


<?

// Если переменная $bgcolor существует
if (isset($bgcolor)) :
     
setcookie("bgcolor", $bgcolor, time()+3600);
?>

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

<?
// Значение $bgcolor не задано, отобразить форму
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:13-2.txt


<?

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:13-3.txt


<?


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!");

// Объявить запрос
$query = "SELECT * FROM users13 WHERE user_id = '$userid'";

// Выполнить запрос
$result = mysql_query($query);

// Если совпадение будет найдено, вывести данные пользователя.
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:13-4.txt


<?

// Построить форму
$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>
"
;
// Если форма еще не отображалась
// и для данного пользователя еще не существует cookie...
if ((! isset ($seenform)) && (! isset ($userid))) :

    print
$form;

// Если форма отображалась,
// но данные пользователя еще не были обработаны...
elseif (isset ($seenform) && (! isset ($userid))) :

    
srand ((double) microtime() * 1000000);
    
$uniq_id = uniqid(rand());
    
// Подключиться к серверу MySQL и выбрать базу данных users
    
@mysql_pconnect("localhost", "root", "") or die("Could not connect to MySQL server!");
    @
mysql_select_db("book") or die("Could not select user database!");
    
    
// Объявить и выполнить запрос
    
$query = "INSERT INTO users13 VALUES('$uniq_id', '$fname', '$email')";
    
$result = mysql_query($query) or die("Could not insert user information!");

    
// Создать cookie "userid" со сроком действия в один месяц.
    
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.";
// ... иначе, если cookie существует - использовать идентификатор
// пользователя для выборки данных из базы данных users
elseif (isset($userid)) :
    
// Подключиться к серверу MySQL и выбрать базу данных users
    
@mysql_pconnect("localhost", "root", "") or die("Could not connect to MySQL server!");
    @
mysql_select_db("book") or die("Could not select user database!");
    
    
// Объявить и выполнить запрос
    
$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:13-5.txt


<?

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

?>

File:13-6.txt


<?

// Инициировать сеанс и создать сеансовые переменные
session_register('bgcolor');
session_register('fontcolor');

// Предполагается, что переменная $usr_id (с уникальным
// идентификатором пользователя) хранится в cookie
// на компьютере пользователя.

// При помощи функции session_id() присвоить идентификатору
// сеанса уникальный идентификатор пользователя (UID),
// хранящийся в cookie.
$id = session_id($usr_id);

// Значения следующих переменных могут задаваться пользователем
// на форме HTML
$bgcolor = "white";
$fontcolor = "blue";

// Преобразовать все сеансовые данные в одну строку
$usr_data = session_encode();

// Подключиться к серверу MySQL и выбрать базу данных users
@mysql_pconnect("localhost", "web", "4tf9zzzf")
                or die(
"Could not connect to MySQL server!");
@
mysql_select_db("users")
                or die(
"Could not select user database!");

// Обновить пользовательские параметры страницы
$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:13-7.txt


<?

// Предполагается, что переменная $usr_id (с уникальным
// идентификатором пользователя) хранится в cookie
// на компьютере пользователя.

$id = session_id($usr_id);

// Подключиться к серверу MySQL и выбрать базу данных users
@mysql_pconnect("localhost", "web", "4tf9zzzf")
                or die(
"Could not connect to MySQL server!");
@
mysql_select_db("users")
                or die(
"Could not select company database!");

// Выбрать данные из таблицы MySQL
$query = "SELECT page_data FROM user_info WHERE user_id= '$id'";
$result = mysql_query($query);
$user_data = mysql_result($result, 0, "page_data");

// Восстановить данные
session_decode($user_data);

// Вывести одну из восстановленных сеансовых переменных
print "BGCOLOR: $bgcolor";

?>

File:13-8.txt


<?

// Реализация сеансовых функций на базе MySQL

// Хост, имя пользвателя и пароль
$host = "localhost";
$user = "web";
$pswd = "4tf9zzzf";

// Имена таблицы и базы данных
$db = "users";
$session_table = "user_session_data";

// Прочитать значение sess.gc_lifetime из файла php.ini
$sess_life = get_cfg_var("sess.gc_lifetime");

// Функция : mysql_sess_open()
// Назначение: подключение к серверу MySQL
// и выбор базы данных.

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!");

}

// Функция: mysql_sess_close()
// Назначение: в реализации на базе MySQL эта функция не используется.
// Тем не менее, она *обязательно* должна быть определена.

function mysql_sess_close() {

    return
true;

}


// Функция: mysql_sess_read()
// Назначение: загрузка информации из базы данных MySQL.

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;

}

// Функция: mysql_sess_write()
// Назначение: запись информации в базу данных MySQL.

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);

    
// Если запрос на вставку данных завершился неудачей
    // из-за присутствия первичного ключа в поле sess_key,
    // выполнить обновление.

    
if (! $result) :

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

        
$result = mysql_query($result);

    endif;

}


// Функция: mysql_sess_destroy()
// Назначение: удаление из таблицы всех записей с ключом, равным $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;

}


// Функция: mysql_sess_gc()
// Назначение: удаление всех записей, у которых
// срок жизни < текущее время - 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();

}

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

?>

File:13-9.txt


<?

// Файл: init.inc
// Назначение: инициализационный файл журнала посещений сайта


// Параметры соединения с сервером MySQL

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

// Имя базы данных
$database = "myTracker";

// Имя таблицы
$visitors_table = "visitors";

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

// Выбрать базу данных
@mysql_select_db($database) or die("Couldn't select $database database!");


// Максимальное количество посещений, отображаемое в таблице
$maxNumVisitors = "5";

// Имя cookie
$cookieName = "visitorLog";

// Значение cookie

$cookieValue="1";

// Срок, который должен пройти с момента последнего посещения сайта,
// чтобы информация о текущем посещении была сохранена в базе данных.
// Если переменная $timeLimit равна 0, сохраняются все посещения
// независимо от их частоты.
// Остальные целочисленные значения интерпретируются как интервал
// времени в секундах.

$timeLimit = 3600;

// Формат отображения данных в броузере

$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:13-10.txt


<?

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

    
// Создать cookie
    
setcookie($cookieName, $cookieValue, time()+$timeLimit);

    
// Сохранить информацию о посетителе
    
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:14-1.txt


<?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:14-2.txt


<?xml version="1.0"?>

<!DOCTYPE cookbook [
<!ELEMENT cookbook (recipe+)>
<!ELEMENT recipe (title, description, ingredients, process)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT description (#PCDATA)>
<!ELEMENT ingredients (ingredient+)>
<!ELEMENT ingredient (#PCDATA)>
<!ELEMENT process (step+)>
<!ELEMENT step (#PCDATA)>
    <!ATTLIST recipe category CDATA  #REQUIRED>
] >

File:14-3.txt


<?


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");

    }

// Функция отвечает за обработку всех открывающих тегов.

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

// Функция отвечает за обработку всех символьных данных.

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

// Функция отвечает за обработку всех закрывающих тегов.

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);

    // Обработать файл XML
    
while ( $line = fread($fp, 4096) ) :
         
        
// При возникновении ошибки прервать обработку
        // и вывести сообщение об ошибке.

         
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;

}

}

// Открыть файл XML для обработки
$xml_file = "bookmarks.xml";
$fp = fopen($xml_file, "r");

// Создать новый объект
$xml_parser = new XMLHTML;

// Обработать $xml_file
$xml_parser->parse($fp);

?>

File:15-1.txt


<?

// Получить информацию о броузере
$browser = get_browser();

// Преобразовать $browser в массив
$browser = (array) $browser;

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

    
// Присвоить нули пустым элементам массива
    
if ($value == "") :
        
$value = 0;
    endif;

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

endwhile;
?>

File:15-2.txt


<?

$browser
= get_browser();

// Преобразовать $browser в массив
$browser = (array) $browser;

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

File:15-3.txt


<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>

<?
    
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;
?>
</body>
</html>

File:15-4.txt


<html>

<head>
<title>Listing 15-4</title>
<SCRIPT language="Javascript">
<!--
    // Объявить переменную Javascript
    var popWindow;
    // Объявить функцию newWindow
    function newWindow(winID) {
        // Объявить переменную winURL. Присвоить ей
        // имя файла PHP с последующими данными.
        var  winURL = "Listing15-5.php?winID=" + winID;
        // Если временное окно не существует или закрыто,
        // открыть его.
        if (! popWindow || popWindow.closed) {
            // Открыть новое окно шириной 200 пикселов и высотой
            // 300 пикселов, расположенное на расстоянии 150 пикселов
            // от левого края и на 100 пикселов от верхнего края
            // основного окна.
            popWindow = window.open(winURL, 'popWindow',
                'dependent,width=200,height=300,left=150,top=100');
            }
            // Если временное окно уже открыто,
            // активизировать его и обновить содержимое
            // в соответствии с 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:15-5.txt


<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("$winID.inc");
            
?>
            </td>
        </tr>
        <tr>
            <td>
            <a href="#" onClick="parent.self.close();">close window</a>
            </td>
        </tr>
    </table>

</body>
</html>

File:15-6.txt


<?

// Создать экземпляр объекта для приложения MS Word
$word=new COM("word.application") or die("Couldn't start Word!");

// Активизировать окно MS Word
$word->visible =1;

// Создать новый документ
$word->Documents->Add();

// Вставить в документ фрагмент текста
$word->Selection->Typetext("php's com functionality is cool\n");

// Выбрать текстовый режим сохранения
$ok = com_set($word->Application, DefaultSaveFormat, "Text");

// Запросить у пользователя имя и сохранить документ.
// Обратите внимание: по умолчанию документ сохраняется
// в текстовом формате!
$word->Documents[1]->Save;

// Выйти из MS Word
$word->Quit();
?>

File:15-7.txt


<?

// Создать соединение с сервером MySQL
$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 = "SELECT * FROM $address_table ORDER BY last_name";
$result = mysql_query($query);

// Создать новый объект COM для приложения MS Word
$word=new COM("word.application") or die("Couldn't start Word!");

// Активизировать окно MS Word
$word->visible =1;

// Открыть пустой документ.
$word->Documents->Add();

// Перебрать записи из таблицы адресов
while($row = mysql_fetch_array($result)) :
    
$last_name = $row["last_name"];
    
$first_name = $row["first_name"];
    
$tel = $row["tel"];
    
$email = $row["email"];

    
// Вывести данные таблицы в открытый документ Word.

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

endwhile;

// Запросить у пользователя имя документа.
$word->Documents[1]->Save;

// Выйти из MS Word
$word->Quit();
?>

File:16-1.txt


<?

$user_pass
= "123456";

// Выделить первые два символа $user_pass
// и использовать их в качестве детерминанта.
$salt = substr($user_pass, 0, 2);

// Зашифровать и сохранить пароль.
$crypt1 = crypt($user_pass, $salt);
// $crypt1 = "12tir.zIbWQ3c"

// . . . пользователь вводит пароль
$entered_pass = "123456";

// Получить первые два символа хранящегося пароля
$salt1 = substr($crypt, 0, 2);

// Зашифровать $entered_pass, используя $salt1 в качестве детерминанта.
$crypt2 = crypt($entered_pass, $salt1);
// $crypt2 = "12tir.zIbWQ3c";

// Следовательно, $crypt1 = $crypt2

?>

File:16-3.txt


<?


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:16-4.txt


<?


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:16-6.txt


<?


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

$authorized = 0;

// Сохранить строки файла в виде элементов массива
$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;

}

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:16-7.txt


<?

if (!isset($PHP_AUTH_USER)) :

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

else :

    
// Создать содинение с базой данных MySQL
    
mysql_connect ("host", "user", "password")
                or die (
"Can't connect to database!");
    
mysql_select_db ("user_info")
                or die (
"Can't select database!");
    
    
// Обратиться к таблице user_authenticate
    // для поиска совпадающей строки
    
$query = "select userid from user_authenticate where
                                     username = '$PHP_AUTH_USER' and
                                     password = '$PHP_AUTH_PW'"
;

    
$result = mysql_query ($query);

    
// Если совпадение не найдено, вывести окно аутентификации
    
if (mysql_numrows($result) != 1) :

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

    
// Если проверка пройдена, получить идентификатор пользователя
    
else :
        
$userid = mysql_result (user_authenticate, 0, $result);
    endif;

endif;

?>