Вы находитесь на странице: 1из 672

WEB-

MySQL

1 DiaSoft
-
2003

and MySQL
Web Development
Luke Welling and Laura Thomson

SAMS
201 West 103rd Street, Indianapolis, Indiana 46290


Web-
PHP MySQL

*-1*.

DiaSoft
-
2003

32.973.2
681.3.06(075)
77

77 Web- MySQL: . ./ , . 2- ., . : , 2003. 672 .
ISBN 5-93772-090-3
Web- MySQL MySQL
Web- .
-,
, .
,
, PDF-,
Web, Web-. -, , -
Web.
CD-ROM , ,
, Web-.
, , , ,
Internet.
32.973.2

,
WEB- MYSQL
..
..
..
.

/
, 196105, -, . ., . 1, . 108.
000328 9 1999 .
10.03.2003. 16.04.2003. 70x100/16.
. . . .. 42.
. 3000 . 216

,
198005, -, ., 29.
Authorized translation from the English language edition, entitled PHP and MySQL Web Development, published
by Sams, Copyright 2000
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording or by any information storage retrieval system, without permission
from the Publisher,
Russian language edition published by DiaSoft Publishing.
Copyright 2003
Sams Corporation, Macmillan Computer Publishing.
, .
ISBN 5-93772-090-3 (.)
ISBN 0-672-31784-2 (.)

. , 2003
Sams Corporation, 2000
. , 2003
77.99.6.953..438.2.99 04.02.1999


1.

25

1.
2.
3.
4.
5.
6. -

26
59
75
95
115
139

2. MySQL
7. Web-
8. Web-
9. MySQL
10. MySQL Web
11. MySQL

157
158
168
187
203
216

3. .. 232

12.
13.
14.
15.



MySQL
MySQL

4.

233
245
265
283

301

16.
302
17. ..316
18.
333
19.
340
20.
361
21.
374

5.
MySQL
22. MySQL

23.
24.
25.
26.
27. , Web
28.
29. Web-
30.
(PDF)

6.
. 4 MySQL
. Internet

380
381
396
411
441
477
500
529
571
596

626
627
645
648

1.

25

1.

26


: Bob's Auto Parts

27
27
27

HTML
PHP-

29

29
30

PHP-

30

PHP-

31

31

32

... 33

33
date()
33

34

34

35

35

36
, .. 36

36

36

37

37

37

38

:.... 38

39

39

39

40

40

43

44

44

45

:

46
:

47

48
48

49

50

50


50
if
50

51
:

51
else
51
elseif
52
switch
52
. 54
:
54
while

55

for

56

do..while

57

2.

58

59
60
60
61
61
61

fopenf)

61

FTP
....

63


fwrite()

83

64

sortf)

83

65

asort() ksort()

83

65

65

83

66
67

84

: fopenQ

68

: feof()

68

:
fgets(), fgetss() fgetcsvf)

68

:
readfileO, fpassthruf), file()
: fgetc()

69
70

:
fread()

70

70

: file_exists() 70
: filesizeQ
71

84
85
86

shuffle()

86

array_reverse()

87

88

90

:
each, current!), reset)),
end(), next(), pos() prev()

90

unlinkQ

71

:
rewindf), fseek ftellQ


: array_walk()

91

71

:
count(), sizeoff) array_count_values()

92


: extract!)

93

72

73

73

74

3. .. 75

76

76

76

77

78

4.

95
: Smart Form Mail

95

97

:
chop(), ltrim() trim()

... 98
:
AddSlashesQ StripSlashes()

78


explode)), implodef) join()

78

strtok()



() list()

78

79
80

97

substr()

: strcmp(),
strcasecmp() strnatcmpQ

100
101
102
102
103
104
104


strlen()

104



: strstr)),
strchr(), strrchrf), stristr()
:
strposf), strrposf)
; str_replace(),
substrjeplace()

107

108
108
110
110
110

105
105
106

110
111
111

.111

Smart Form
111

112

113

113

114

5.

115

?

116
116

116
'.


require)) include))
required

require))
PHP- required

116
116
117
118
118

require))
Web-

118


auto_prependjile auto_append_file
include))

122
123
125

125
126
127

127

128

128

129

131

133

134

135

136
137

6. -

139
-

142
142
142
143

143

139
140
141
141

145

146

146
148
148
149

10

2. MySQL.. 157


Web
root
...

176
176
176
177

7.
Web-

158

159

178

159

178

159

159


SHOW DESCRIBE

180

160

160

161

161


Web-
162
,

162
163
. 164

164
,

165


165

165
Web-
166

166

8.
Web-

168


MySQL

169

MySQL

170

171

171

171


MySQL

171


172
: GRANT. 172

REVOKE...

173
..175

MySQL

9.
MySQL

181
182
182

187

SQL?
'... 187

188

189

191
.. 192
:

196

197

10.
MySQL Web

198
199

200
200
202
202
202

203

Web- . 204

Web
206
,

207

207

209

209

210




PHP-MySQL....


PHP-

211
214
214
214
214

11.
MySQL

216


user
db host
tables_priv columns_priv
: MySQL

:
?

MySQL
,
MySQL


Web


SHOW

DESCRIBE
EXPLAIN







,



211

11
231

3.

232
12.

233

221
222
222
223


233
Web-
234

234

237
240

241

241

242

242
. 243

243
,
,
243

243

244
. 244


,
244

223
223

13.

245

216
217
218
219
220
221
221

225
225
229
229
229
229
229
230
230
230
230
230

246
246

247
248
249
250
251
252


, ,




253
254
254
255
256

12





Web-

257
258
258
259
260
262
262
263
263


MySQL
263

264

14.
MySQL

265


265

266

268

270

271

272


273

.htaccess Apache .. 274

IIS
277

mod_auth_mysql
279
mod_auth_mysql
?

279
280

mod_auth_mysql

281

281

15.
MySQL
283


Internet

283
284
285
... 286

.287
, .. 290

.291
? 292

292
GPG
293
GPG
295

4.

301
16.
...302

302
HTML-
303
PHP- 304

307


307

307

... 309




,


:
getenv() putenv()

309

310
310
312
312
313
314

17.

316


Web-
NTTP

FTP

316
317
317
320
323

FTP

323


329
-
329
RP
329

cURL
330

18.



date()
UNIX
getdatef)


MySQL

333
333
333
335
335
336
336
338
338

19. .340
. 340

341
JPEG
341
PNG
341
WBMP
342
GIF

342


343

344


344

346

347


347


347

350

350

352

353

353

13

353
359

20.

361


361


362
cookie-?
362
cookie-
363
cookie- .. 363

364
364

364

365

365


365

366

368


368

21.


,
, - eval()
: die exit

374
374
375
376
376
377
377
378
378
378
378
379

14

5.
MySQL... 380
22. MySQL
. 381


Web-
382

Web-

382

383

384
384
387
387
387

388

389

390

391

392


392

392
Zend... 393

394
395

395

23.

396

396
397
398
402

404

405

406

408

408

410

24.

411

411

412

413
415

416

418

412
413
413

418
423

426
427
428
432
432
434
434

436

440

25.

441

442
442
442
442
443

443
443

447

449
451
453
454


show_cart.php


455

456
458
460

505

509

511

462
462
463
467

469

475

.... 476

26.

15

477

503


513
515

515

516


516
... 518

521

523

524

525

525
527

477

528

478



FTP


478
478
478

28.

529

530

530

479
479

480

480

481

483
484

486
486
488
495
498
499

27.
, Web

500
500
'.. 501
502

530

531

531

531

533

535

542
542
544
547
547
551
553
554
555
555
557

16


557

558
.. 559
... 562


565

566

570

29. Web- 571






.

treenode



572
573
575
577
579
581
582
588
589
595
595

30.


(PDF).... 596



ASCII
HTML


PostScript




596
597
597
598
598
598
599
600
600
601
601
602


604

605

606
RTF-
608
PDF- ... 611
PDF-
PDFlib
614
Hello World PDFlib
614
PDFlib 618
,
624

625

6.

626

.
4 MySQL

627


CGI
628
Apache, PHP MySQL UNIX. 629
Apache mod_SSL
632
httpd.conf
634
?
635
SSL?
635
Apache, PHP MySQL
Windows
636
MySQL Windows
637
Apache Windows
638
Apache
Windows UNIX
640
Windows
641
Microsoft IIS . 643
Microsoft PWS . 644

644

. Internet ...645
,
, MySQL SQI
, Apache
Web

645
647
647
647

648

17


(Laura Thomson) Web
RMIT , . Web-
Tangled Web Design. Telstra (Boston Consulting Group).
( ) ( ), Web-. . :
laura@tangledweb.com.au.
(Luke Welling) RMIT
, . Tangled Web Design.
( )
" ". . : Iuke@tangledweb.com.au.


-. (Israel Denis Jr.) , .
, SAP Lawson,
Web. 1998 . ,
, . . Linux, Apache,
PHP MySQL; : idenis@ureach.com.
(Chris Newman) -,
Internet.
MySQL ,
.
--, , Lightwood
Consultancy Ltd. Lightwood Consultancy Ltd.
Web- http://www.lightwood.net,
: chris@lightwood.net.

Web- MySQL

Sams . ,
(Shelley Jonston Markandy),
. -.
.
, MySQL.
,
.
(Adrian Close) , 1998 . : "
", (James Woods) Law Parners,
.
, , ,
. , : , , ,
, , , , .

1J7

" Web- MySQL".


, MySQL
Web-.
:

MySQL

, .


Web-, . , , , (Open Source).
, , ,
HTML , , , Internet . ,
.
, . ,
, MySQL Web-. Web-.
, , . ,
. , . Web- , .

,
, , Web-.
Web- HTML, . ,
HTML, Web- . , . .

2\J

Web- MySQL

, , , MySQL, : , .
, , . , MySQL.
Web- , MySQL.

,
:



Web

Web-

. ,
Web-, . ,
.

?
( ), Web. HTML- , . Web-
HTML , .
1994 . ,
(Rasmus Lerdorf).
,
, . 2001 . . , ,
http://www.php.net/usage.php.
(Open Source).
. , .
Personal Home Page (
), GNU (GNU = Gnu's Not Unix) Hypertext Preprocessor ( ).

2,1

. , .
http://www.php.net
Zend http://www.zend.com.

4?
, 4 :

4 ,
Zend Engine.
, http://www.zend.com Zend
Optimizer, Zend Cache Zend Compiler.

PHP Apache.
ISAPI
Internet Information Server Microsoft.

.

PHPLib.

MySQL?
MySQL ( ---) , (). , , . MySQL
, , . , MySQL , . SQL (Structured Query Language
),
. MySQL 1996 ., 1979 . , ,
Linux Journal.
MySQL ,
.

MySQL?
,
.
Web-, , Web-,
.
. , ,
..

2.2,

Web- PHP MySQL

, Web-. .
, Microsoft Windows,
UNIX Web-.
MySQL .
,
:

Linux Web- Apache

Microsoft Windows 2000 Microsoft Internet Information


Server (IIS)
, Web-
, , MySQL.


Perl, Active Server Pages (ASP) Microsoft,
Java Server Pages (JSP) Allaire Cold Fusion.
PHP , :

, Web

. ,
. ,
Zend Technologies (http://www.zend.com), .


. MySQL, PostgreSQL, mSQL, Oracle, dbm, Hyperware, Informix, InterBase Sybase.
Open Database Connectivity Standard (
, ODBC), , ODBC-. Microsoft
.


Web,
,

Web, . " " GIF-, , ,


cookie- PDF- .

.
http://www.php.net.


, Perl. , Perl - ,
C++ Java, .


. Unix- , Linux FreeBSD, Unix Solaris IRIX
Microsoft Windows.
, -
.


. , -
, .
, - (). ,
.

MySQL
MySQL, , PostgreSQL, Microsoft SQL
Server Oracle.
MySQL , , , , .
.

MySQL . , -,
http://web.mysql.com/benchmark.html. ,
MySQL .


MySQL
, ,
.

2J\

Web- MySQL


SQL.
, - .
MySQL , .

MySQL UNIX,
Microsoft Windows.


, MySQL .


.
I, " ",
. "" , , .
1, " ".
, .
, ,
.
II, " MySQL",
,
MySQL, SQL, MySQL MySQL,
.
III, " ", ,
. . , MySQL , .
IV, " ". .
,
. ,
, , .
V, " MySQL", , ; , MySQL.

,
MySQL, , .
. Web-, ,
, Web-.

3
4

. .
, ASP ,
.
, .
, .
.
. ,
- , ,
.

CD-ROM, ,
.
, ,
, . . ,
, .

, .

if, else, switch ?:.

1.

27

, PHP-
HTML-, .
:

HTML

if, else switch

: while, do for


, , Web- .
. ,
.
,
. , " 4 MySQL". , UNIX Windows NT, CD-ROM.

: Bob's Auto Parts



HTML-. Bob's Auto Parts ( ),
. , ,
chapterl CD-ROM.


HTML Bob's Auto Parts . .
1.1. , ,
Web. , , , ,
.

28

1. PHP

Bob's Auto Parts -- Microsoft Internet Explore


HTML-
1.1.
- [is] htip //
.
J
-, ,
Bob's Auto Parts
, PHP-, .
Order Form
( Item
Quantify
.)
Tires
ACTION URL-, Oil

Spark Plugs
|
(submit). ,
Submit Order I
, J
URL-
1.1

,
METHOD: GET ( - .
URL-), POST (
).
-, tireqty, oilqly
sparkqty. PHP-.
, . HTML-
field23. .
, .
, ,
. , ,
.
:

1.1 orderform.html HTML- .


<form action="processorder .php" method=post>
<table border=0>
<tr bgcolor=#cccccc>
<td width=150>Item</td>
<td width=15>Quantity</td>
</tr>
<tr>
<td>Tires</td>
<td align=centerXinput type="text" name="tireqty" size=3 maxlength=3X/td>
</tr>
<tr>
<tdX)il</td>
<td align=centerXinput type="text" name="oilqty" size=3 maxlength=3X/td>
</tr>
<tr>
<td>Spark Plugs</td>
<td align=centerXinput type="text" name="sparkqty" size=3 maxlength=3x/td>
</tr>
<tr>
<td colspan=2 align=centerXinput type=submit value="Submit Order"x/td>
</tr>
</table>
</form>

29

1.


,
ACTION FORM processorder.php. . :
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<hl>Bob's Auto Parts</hl>
<h2>Order Results</h2>
</body>
</html>

,
HTML-. -.

HTML
<h2> :
echo "<p>Order processed.";

,
Submit (). - , . 1.2.
, PHP- HTML-.
. :
<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<hl>Bob's Auto Parts</hl>
<h2X3rder Results</h2>
<p>Order processed.</pX/body>
i l . b t a Edit 'tfM ..fltafiim
</html>

lools

Help;!...

[Address |ahl!p7/vebser.w/rtiopler!/piocessoiderphp

PHP-
. ,
.
,
HTML,
,

.

-

Bob's Auto Parts

:
:

D
_tj i*0o

Order Results
Order processed.

jy
1.2 , PHP echo, .

1. PHP

. PHP- Web-, JavaScript


,
Web- .
:
HTML





HTML-.

-
PHP- <?
?>. HTML-,
"" (<) "" (>). PHP-, Web-,
, PHP-. , , PHP-.
HTML-. -
HTML.
.
. - , . .

-
-. .

<? echo "<pX>rder processed."; ?>

.
.
SGML (Standard Generalized Markup Language ).
( ),

.
.
XML-
<?php echo "<pX3rder processed."; ?>

XML (Extensible
Markup Language ). -

1. PHP

XML-, .

SCRIPT-
<SCRIPT LANGUAGE='php'> echo "<pX)rder processed."; </SCRIPT>

,
JavaScript VBScript. HTML-,
.

ASP-
<% echo "<pX)rder processed."; %>

Active Server Pages (ASP).


, asp_tags.

, ASP, ASP.

PHP-
, PHP-, -, . :
echo "<pX)rder processed.";

, echo ;
( ) . . 1.2 ,
"Order processed.".
, echo . PHP- , . ,
Java, .
, . , .

, ( ), .
HTML.
, , HTML-.
. HTML:
<hl>Welcome to Bob's Auto Parts!</hlXp>What would you like to order
today?

32

1. PHP

<hl>Welcome
Auto Parts!</hl>
<p>What would you like
to order today?

to Bob's

HTML- ,
. HTML- , HTML-.
. PHP- ,
. ,
echo "hello";
echo "world";

echo "hello";echo "world";

, .

, :
, . , , , ,
.. , , .
PHP- , .
, , .
, C++
, -:
/* :
: 10
.
*/

/*
*/. , .
C++:
echo "<pX)rder processed."; //

:
echo "<p>Order processed."; #

, (#
//) .
, , .

1.

33


- ,
HTML.
. , ,
,
. .
. PHP-
processorder.php :
echo "<pX>rder processed at
echo date("H:i, jS F") ;
echo "<br>" ;

PHP- date() .
. ,
, . 1.3.


date(). . , Web. -
- .
:
date("H:i, jS F " )

, ( ) . , , . ,
- s Auto Parts - Order Results - Microsoft Internet Explo .. * !
.
;

Rle

dateQ
,
date(), , .

. 12 , i
, , j , S
( "th"),
a F - - ,
.
2 . 216

di) View

Favorit

Too^s

Help

1 Aidless jj} http7/webserver/chapter1/processQrder.php

Bob's Auto Parts


Order Results
Order processed at 04:11, 31st January

1.3 PHP- date()


.

34

1. PHP

( , datc(),

18.)



. , , .
PHP-
, , . .
-:
echo
echo
echo
echo
echo

"<p>Your order is as follows:";


"<br>";
$tireqty." tires<br>";
$oilqty." bottles of oil<br>";
$sparkqty." spark plugs<br>";

. 1.4. , ,
.

.


PHP-. , ($).
( .)
.

. HTML-. .
,
, . , ,
, , Stireqty,

*
_
lr,iieas.!Ej hltp.//web*erver/chapler1/p[ot8ssorder.php
'.'
J

Bob's
Auto
Parts
,
$HTTP_POST_VARS

Order Results
$HTTP_GET_VARS. Order processed at 21:09, 9th April
. Your order is as follows:
2 tires

1 bottles of oil
: POST GET.
2 spark plugs

, tireqty
,
$HTTP_POST_VARS [" tireqty" ]

1.4 ,
,
processorder.php.

1, PHP

jJ

"On" register_globals php.ini.


php.ini.
, register_globals
1
"Off , .
"On" track_vars.

, . ,
; , .
, , , Perl, .
, . , .
, , , .


echo , ,
. echo, ,
(.), :
echo $tireqty. " tires<br>";

,
( ).
echo.
echo.

echo "$tireqty tires<br>";

. .


, echo, . () .
.
, . $tireqty , .. , . , " tires" . , .
, .
? Stireqty , .
, . , , , . ,
, .

36 1. PHP

. ( ; 5 6.)
:
, , . .
" ".
.
. $tireqty STireQty
.
. PHP- .
.
, . ,
.

,
, HTML-,
.
,
, .
; .


=.

. . .
-:
$totalqty = ;
$totalamount = 0 . 0 0 ;

. ,
:
>
$totalqty = 0;
$totalamount = $totalqty;

1. PHP

J/

Integer ()

Double ( )
String ()

Array () (. 3)
Object () (. 6)
pdfdoc pdfinfo, PDF (Portable Document Format ). PDF 29.


. , , ,
. .
, Stotalqty Stotalamount
:
$totalqty = 0;
$totalamount = 0 . 0 0 ;

Stotalqty 0,
integer. , Stotalamount double.
, :
$totalamount = "Hello";

Stotalamount string. PHP


, .
" " . , "" ,
.
.


, ,
. , .
, ,
.
, .
$totalqty = 0;
$totalamount = (double)$totalqty;

" , Stotalqty, double Stotalamount". -

38

1. PHP

Stotalamount double. , Stotalqty integer.


.. . .
( ,
,
, .)
. ,
$varname = "tireqty";

Stireqty SSvarname, , :
$$varname = 5;

,
.
, . , , ,
for.

, , , .
, . ,
,
.

.
define:
define("TIREPRICE", 100);
define("OILPRICE", 10) ;
define("SPARKPRICE", 4) ;

.
, .
. , ,
, .
, .
, .
, . ,
:
echo TIREPRICE;

1. PHP

, ,
. ,
phpinfo():
phpinf();

PHP, a
.
.


(scope) ,
() . :

, , ,
.

, , .
, , , .
. ,
.


,
.
.
: (=) (.) .
, , . ,
, =, , . , ..
, .
i


.
. 1.1.
1.1

$ + $

$ - $

$ * $

$ / $

$ % $

1. PHP

,
:
$result = $ + $;

, .
, , , $
$.
(.. , , )
. ,
$ = -1;

. .
Sa $. :
$ = 27;
$ = 10;
$result = $%$;

, Sresult, 27 10, .. 7. , . ,
. "" ""
. . ;
, .


.

.
$ = "Bob's ";
$ = "Auto Parts";
$result = $a.$b;

Sresult "Bob's Auto Parts".


=, .
" ". ,
$totalqty = 0;

1.

41

" Stotalqty
".
.


,
.
$ + $

$ $. ,
$ = 0;

0.
:
$ = 6 + ($ = 5 ) ;

$ 11.
:
, .
, .
, .


. - .

$ += 5;

$ = $ + 5;


.
. 1.2.
1.2

-=

$ += $

$ = $ + $

-=

$ -= $

$ = $ - $

$ '= $

$ = $ ' $

/=

$ /= $

$ = $/$

%=

$ %= $

$ = $ % $

$ .= $

$ = $ . $

42

1. PHP


(++) () += -=, .
, . :
$=4 ;
echo ++4;
,
, ++ $. $ 1, . $ 5, 5 . 5. ( , ,
$, : $ + 1.)
, ++ $, , . :
$=4 ;
echo $a++ ;
. , $ , 1.
4. . $ 5.
, , $ 1, .

4 & (), . , , ,
- . ,
$ = 5;
$ = $;

$
$. $ , $ :
$ = 7; // $ - 5

, &, :
$ = 5;
$ = &$;
$ = 7; // $ $ 7

1.

43


. ,
, true () false ().


== ( )
. ,
$ == $

, $ $. true, , false,
.
.
, .
true, false. ,
:
$ = 5;
$ = 7;

$ = $, true. ?
$ = $ , , 7. ,
true. $ == $, false, ,
, .
.
, , ,
. !


,
. 1.3.
1.3

$ == $

==

$ === $

!=

$ != $

$ $

<

$ < $

>

$ > $

<=

$ <= $

>=

$ >= $

44

1. PHP

, 4,
true ,
.


. , , $ 0 100. $ >=0
$ <= 100, AND (), :
$ >= 0 && $ <=100

AND (), OR (), XOR (


) NOT (HE).
. 1.4.
1.4

&&

and

!$

true, $
false,

$ && $

true, $
$ true;
false

$||$

true,
$ $
true; false

$ and $

, &&,

$ or $

, ||,

and , && ||. .


.
, ,
, . 1.5.

1.

45

1.5

&

$ & $

,
$ $,

$ | $

~$

$ * $

,
$ $,


,
$,
,

,
$ $,
,

$ $

$
$

$ $

$
$


, .
(,) . .
new -> , ,
. 6.
[]
3.
, .


, ?:, , .
? , : ,
if-else, .
:
($grade > 50 ? "" : " ");
(Sgrade)
"" " ".

@ ,
.. , .

46

1. PHP

,
$ = @ ( 5 7 / 0 ) ;

@
( ). @
.

.
track_errors,
$php_errormsg.


("). , ~ ().
, ,
, .
.
, UNIX-
$out = 4s -la';
echo "<pre>".$out."</pre>";

Windows
$out = "dir : ' ;
echo "<pre>".$out."</pre>";

Sout.
.
. 16.

:
, , ,
.
:
$totalqty = $tireqty + $oilqty + $sparkqty;
$totalamount = $tireqty * TIREPRICE + $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE;
$totalamount = nuraber_format($totalamount, 2);
echo "<br>\n";
echo "Items ordered:
".$totalqty."<br>\n";
echo "Subtotal:
$".$totalamount."<br>\n";
$taxrate =0.10; // 10%
$totalamount = $totalamount * (1 + $taxrate);
$totalamount = number_format($totalamount, 2) ;
echo "Total including tax: $".$totalamount."<br>\n";

1.5.

1.

, . (+) (*)
, (.) .
,
number_format()
.
.
,
. , :
$totalamount = $tireqty * TIREPRICE
+ $oilqty * OILPRICE
+ $sparkqty * SPARKPRICE

47

Bob's Auto Parts


Order Results
Order processed at 07:47,10th April
Your order is as follows:
1 tires
1 bottles of oil
1 spark plugs
Items ordered: 3
Subtotal: SI 14.00
Total including tax: S125.40

1,5

.

, ?
, .. .

:
, .
, , . , , .
. 1.6.
1.6

or

and

prinf

= += -= = /= .= %= &= |= = ~= = =

II

&&

48

1. PHP

< <= > >=


* / %

! ~ +

[]

new

()

(int) (double) (string) (array) (object) @

, , , .
, ,
: . .
.
:
$totalamount = $totalamount *

(1 + $taxrate);


$totalamount = $totalamount * 1 -f $taxrate;

, , , .
, , 1 + Staxrate.

. , .


,
. ,
.


.
gettypeQ settype(). , .
string gettype(mixed var);
int settype(string var, string type);

gettypeQ . , "unknown type",


: integer, double, string,
array object.

1.

settype() ,
, ,
.
:
$ = 56;
echo gettype($)."<br>";
settype ($a, "double");
echo gettype($a)."<br>";

gettype() $ integer.
settype() double.
.
true false.
:
is_array()

is_double(), is_float(), is_real() ( )


is_long(), is_int(), is_integer() ( )
is_string()
is_object()


, .
issetQ, :
int asset(mixed v a r ) ;

true, , false .
, unset().
:
int unset(mixed v a r ) ;

true.
, empty().
, , , ,
true false. :
int empty(mixed v a r ) ;

.
:
echo
echo
echo
echo

isset($tireqty);
isset($nothere);
empty($tireqty);
empty($nothere);

, .

1. PHP

isset() Stireqty true , .


empty() .
Snothere , isset() false, emptyQ true.

.


, ,
. :
int intval(mixed var);
double doubleval(mixed var);
string strval(mixed var);

, .


,
. ( ) , . .


,
. ,
, .

if
if. , . true, . if
, , ,
, , Submit. "Order processed" (" "), .
, ,
"You did not order anything on previous page!" ("
!"). if:
if( $totalqty == 0 )
echo "You did not order anything on previous page!<br>";

Stotalqty == 0. , (==) , (=).


Stotalqty == 0 true,
Stotalqty . Stotalqty ,

1. PHP

J\

false. true, echo .


, if,
. if.
. :
if( $totalqty == 0 )
{
echo "<font oolor=red>";
echo "You did not order anything on the previous page!<br>";
echo "</font>";
}

, , . true, . false, .

:
, . . , ,
, ,
. ,
if, , , .

else
, .
else , , if false.
, .
, ,
.
else,
, .
if( $totalqty = 0 )

echo
>
else
{
echo
echo
echo
}

"You did not order anything on the previous page!<br>";

$tireqty." tires<br>";
$oilqty." bottles of oil<br>";
$sparkqty." spark plugs<br>";

if ,
. ,
Stotalqty == 0 true, .

52

1. PHP

if( $totalqty = 0)
{
echo "You did not order anything on the previous page!<br>";

}
else
{

if ( $tireqty>0 )
echo $tireqty." tires<br>";
if ( $oilqty>0 )
echo $oilqty." bottles of oil<br>";
if ( $sparkqty>0 )
echo $sparkqty." spark plugs<br>";

elseif
.
elseif, else if.
,
, true.
.
:

10

10-49 5%

50-99 10%

100 15%

if elseif. (&&).
if( $tireqty < 10 )
$discount = 0;
elseif ( $tireqty >= 10 &S $tireqty <= 49 )
$discount = 5;
elseif ( $tireqty >= 50 SS $tireqty <= 99 )
$discount = 10;
elseif( $tireqty > 100 )
$discount = 15;

, elseif, else if
.
elseif , . ,

. , ,
, .

switch
switch if, . if
true false. switch

53

1.

,
(integer, string double). , , case, ()

,
case.
,
.
.
HTML-,
, . 1.6:

fiettesb Home

3ea*t+t

Fa-

Bob's Auto Parts


Order Form
Quantity
Tire?
Oil

Spark Plugs
How did you find Bob's

1.6
,
Bob's Auto Parts.

<tr>
<td>How did you find Bob's</td>
<tdxselect name="find">
<option value = "a">I'm a regular customer
<option value = "b">TV advertising
<option value = "c">Phone directory
<option value = "d">Word of mouth
</select>
</td>
</tr>

HTML- ,
"", "", "" "d". if elseif:
if($find == "a")
echo "<P>Regular customer.";
elseif($find == "b")
echo "<P>Customer referred by TV advert.";
elseif($find == "c")
echo "<P>Customer referred by phone directory.";
elseif($find == "d")
echo "<P>Customer referred by word of mouth.";

switch:
switch($find)
case "a" :
echo "<P>Regular customer.";
break;
case "b" :
echo "<P>Customer referred by TV advert.";
break;
case "c" :
echo "<P>Customer referred by phone directory.";
break;
case "c" :
echo "<P>Customer referred by word of mouth.";
break;
default :
echo "<P>We do not know how this customer found us." ;
break;

54

I. PHP

switch , if
elseif. if
,

.
switch -.
case switch
, , break. switch
,
case,
. break
, switch.

M9j httpV/webserver/chapterl /freight php Microsoft Inlem. i'lBlxl


' Eite
:

Edit *

Bfck

FsyoriWs

lools

~:,*;tilfj ' '.'Swp'^'fp.

; Address |a]http/.
Distance Cost

50

100

10

150

15

200

20

250

25

Help

:'..;:.'
I

-eighlphp

':..':

i '''Search;-'. ' '''.*": .

"3'..:'<*00 'i

_J

1.7
.


, , "
?".
.
else, elseif switch , if. , . .

:
, . -
, .
, , .
.
. 1.7.
HTML-, , 1.3. ,
, .
1.3 freight.html HTML-
<html>
<body>
<table
<tr>
<td
<td
</tr>
<tr>
<td
<td
</tr>

border = 0 cellpadding = 3>


bgcolor = "flCCCCCC" align = center>Distance</td>
bgcolor = "" align = center>Cost</td>
align = right>50</td>
align = right>5</td>

1.
<tr>
<td align
<td align
</tr>
<tr>
<td align
<td align
</tr>
<tr>
<td align
<td align
</tr>
<tr>
<td align
<td align
</tr>
</table>
</body>
</html>

55

right>100</td>
right>10</td>
right>150</td>
right>15</td>
right>200</td>
right>20</td>
right>250</td>
right>25</td>

HTML- , , , , , .

.

while
while. if,
. while if
, true, if
. while
, true.
while , , . , for.
while
while( ) ;

while 1 5.
$ = 1;
while ($num <= 5 )
{
echo $num. "<BR>" ;
$num++;

. false,
. ,
.
while - , , .
1.7.
1.4 while .

56

1. PHP

1.4 freightphp

<bodyx
<table border = 0 cellpadding = 3>
<tr>
<td bgcolor = "#CCCCCC" align = oenter>Distance</td>
<td bgcolor = "#CCCCCC" align = center>Cost</td>
</tr>
<?
$distance = 50;
while ($distance <= 250 )
{
echo "<tr>\n <td align = right>$distance</td>\n";
echo " <td align = right>". $distance / 10 ."</td>\n</tr>\n";
$distance += 50;
)
?>
</table>
</body>
</html>

for
while . .
. .
for .
for
f o r ( !; ; ^)
:?;

! . .
. false, .
.
2 .
.
.
.
while, 1.4, for. PHP- :
<?
for ($distance = 50; $distance <= 250; $distance += 50)
{
echo "<tr>\n <td align = right>$distance</td>\n";
echo " <td align = right>". $distance / 10 ."</td>\n</tr>\n";

1. PHP

J /

while for . for .


-
. , .
, for
. ,
name I, nameZ, .. :
for ($i=l; $1 <= $numnames; $i++)
{
$temp= "name$i";
echo $$temp."<br>"; //
}

,
.

do..while
, , . do..while
do

;
while( );

do..while while , .
, do..while .
, false
true, , .
$num = 100;
do
<
echo $num."<BR>";
}
while ($num < 1 ) ;

58

1. PHP


, ,
.
,
break, , switch. break ,
, .
, continue.
PHP-,
exit. . ,
:
if( $totalqty = 0 >
{
echo "You did not order anything on the previous page!<br>";
exit;
}

exit PHP-.

:
, .
,
.



^, JL , HTML-, . ,
, ,
.
,
.
,
. , .
,
MySQL.

:








:

60 1. PHP

: () .
, (flat) .
,
.
, , .
, ,
. ,
,
.
.
UNIX,
.


, . -,
.
^
HTML- PHP- chapter!
CD-ROM.

, (. . 2.1).
, , address.
,
Saddress ,
. ,
$HTTP_GET_VARS["address"] $HTTP_POST_VARS["address"] (. 1).
. Web-, .

2.1


.

Bob's Auto Parts


Order Form
Item

Quantity

Tires

fi

Oil

fi

Spark Plugs

fi

Shipping Address |1 Smith Street Nowtieresville

2.

01


:
1. . , .
2. .
3. .
, :
1. . (, ),
.
2. .
3. .
,
.
.
.


fopen(). , .
.


,
. , , ,
. ,
, , .
:
1. , .
2. .
3. ,
, .
fopen() .

fopenQ
, .
:
$fp = fopen("$DOCHMENT_ROOT/../orders/orders.txt",

"w');

62

1. PHP

fopen .
, .
, .
, orders.txt orders.
$DOCUMENT_ROOT PHP. Web-. , "..", " $DOCUMENT_ROOT. . ,
Web . ,
$DOCUMENT_ROOT.

(/ UNIX , , :\ Windows). UNIX, , /home/book/orders. , , , , .
,
, " " .
,
, .
- CGI- .
UNIX ( ) (/). Windows
.
(.. ), fopen . , :
$fp = f o p e n ( " . . \ \ . . \ \ o r d e r s \ \ o r d e r s . t x t " , " w " ) ;

fopenQ , . , .
fopen() "w" .
. 2.1.
2,1 fopen

, .

, .

, .
, . ,
.

w+

, .
, .
,
.

2.

(),
, .
,
.

() ,
, .
,
.

.
,
. Windows ,
UNIX - .

, , , . "w"
.
. , , :
$fp = f o p e n ( " . . / . . / o r d e r s / o r d e r s . t x t " , " a " ) ;

fopen() . , include_path ( ; . ). , 1.
:
$fp = fopen("orders, txt" , " a " , 1 ) ;

fopen()
, $1. , .

FTP HTTP
fopen(),
, FTP HTTP.
ftp://, FTP-
.
http://, HTTP-
. HTTP , :
http://www.server.com/


http://www.server.com

( ) Web-,
, HTTP
( ). .

64

1. PHP

fopen() HTTP,
URL- (
),
.
, URL ,
.

Bob's Auto Parts


Order Results
Order processed a! 16:36, 20th April
order is as follows:
4 spark plugs
Total of order is 16.00
Address to ship to is ZOO Intercity Hwy, CounUryiown
Warning: fopen("../../orders/ordere.txt","a") - Permission denied
in /home^ook/pabHc_DtnuVc1iapter2/processor(ler.php on line 54

, , 2.2 PHP ,
.
. (. . 2.2).
,
, , ,
. , , Web- , .
Web-.
UNIX ~/public_html/chapter2/, ,
:
mkdir "/orders
chmod 777 -/orders

, , , . , Web. orders public_html.


13.
,
, .
, ,
.
fopen() ,
false. , :
@ $fp = fopen("$DOCUMENT_ROOT/. ./orders/orders.txt", "a", 1) ;
if

(!$fp)

echo "<pXstrong> Your order could not be processed at this time.


."Please try again later .</strongX/pX/bodyX/html>" ;
exit;

2.

65

@
fopen()
$3
,
.
Bob's Auto Parts
, - Order Results
, Order processed at 16:41, 20di April
.
Your order is as follows:
4 spark plugs
, @

Total of order is 16.00
.
Address to ship to is 200 Intercity Hwy, Countrytown
23.
Your order coolt) not be processed at this time. Please try again later.
if
$fp , fopen 2.3
, , - , ,
- .
. ,
</html>, HTML-.
, , . 2.3.


. fwrite() (file write ) fputs() (file put
string ); fputsQ fwrite().
fwriteQ :
fwrite($fp, $outputstring);

Soutputstring
, $fp. lwrite() , Soutputstring.

fwrite()
fwrite() ,
. fwrite()
int fputs(int

fp,

string str,

int

[length]);

length ,
. fwrite()
str , fp,
length , , .


, ,
. (, 3 . 216

66

1. PHP

, ,
.)
, .
:
$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
.$sparkqty." spark plugs\t\$".$total
."\t". $address."\n";
.
,
. , "\".
, . -, , "\t".
.
, , , ,
. 4. , .
HTML , .

.
3 4. .

, 2.1.
2.1 orders.txt
15:42, 20th April
4 tires
$434.00
22 Short St, Smalltown
15:43, 20th April
1 tires
$100.00
33 Main Rd, Newtown
15:43, 20th April
0 tires
$26.00
127 Acacia St, Springfield

1 oil

6 spark plugs

0 oil

0 spark plugs

1 oil

4 spark plugs



fclose(), :
fclose($fp);

true false,
. , , .

67

2.


Web,
,
.
Web-,
. 2.2.
2.2 vieworders.php
<html>
<head>
<title>Bob's Auto Parts - Customer Orders</title>
</head>
<body>
<hl>Bob's Auto Parts</hl>
<h2>Customer Orders</h2>
@

$fp = fopen("$DOCHMENT_ROOT/../orders/orders.txt", " r " ) ;


/

if

(!$fp)

echo "<pXstrong>No orders pending."


."Please try again later .</strongX/pX/bodyX/html>" ;
exit;
while (!feof($fp))
$order= fgets($fp, 100);
echo $order."<br>";
fclose($fp);
</body>
</html>
: , , . , 2.1, . 2.4.
loots Help

2.4
vieworders.php

,


orders.txt.

...

:: . .

..

. ; " . 1 ' . - - ' : ' : ' . r.

...-"."..'"- ^_" "E ":.a:vv.'^ j>;..a- ''


Gtofj

Refte&fi

Htmirt

i; AjlcHse U|l http://webserver/chBpter2/vieworcters php


,
f

Seerrh Favonle -.

Hi^o'''1

Mai!

"3J..^GO:;

Bob's Auto Parts


Customer Orders
15:42, 20th April 4 tires 1 oil 6 spark plugs S434.00 22 Short St, Smalltown
15:43, 20th April 1 tires 0 oil 0 sparkplugs $100.00 33 Main RiNewtown
15:43, 20th April 0 tires 1 oil 4 spark plugs $26.00 127 Acacia St, Springfield

68

1. PHP

, .

: fopen()
, fopen().
, "":
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", "");

: feof()
while ,
.
feof():
while

(!feof($fp))

feof() .
true, . , , feof File End Of File (: ).
( )
, EOF.

: fgets(), fgetss() fgetcsvQ


fgets():
$order= fgets($fp, 100);
.
, (\n), EOF 99 .
.
,
. fgetsQ , ,
.
fgets() fgetss(), :
string

fgetss(int

fp,

int

length,

string

[allowable_tags]) ;

fgetsQ ,
HTML, .
,
allowable_tags. fgetss() , - ,
. HTML-
.
PHP-
.
fgetcsv() fgets(). :
array fgetcsv(int fp,

int length,

string

[delimiter]);

2.

, , , . ,
, fgetcsv().
fgets(), , .
,
$order = fgetcsv($fp, 100 " \ t " ) ;


(\t). ( Sorder). 3.
length
, .

: readfile(), fpassthruQ, file()



. .
readffle(). :
readfile("$DOCUMENT_ROOT/../orders/orders.txt");

readfile() ,
( ), .
int

readfile (string

_,

int

[use_include_path]) ;

,
use_include_path, , fopen(). , .
-, fpassthruQ. ^
fopen().
fpassthru(), , , , . .
fpassthruQ
:
$fp = fopen("$DOCHMENT_ROOT/../orders/orders.txt", "r");
fpassthru($fp);

fpassthruQ true,
, false .
().
readfileQ ,
.
3. , , ,
:
$filearray = file($fp);

, Sfflearray. .

/U

1.

: fgetcQ
. fgetc().
.
while ,
fgetc():
while (!feo($p))
<
$char = getc($fp);
if <!feof<$fp))
echo ($char=="\n" ? "<br>": $char);
}

fgetc(),
Schar, . \ HTML- <>. .
, . (
, .) .
fgetcQ fgets() , EOF, fgets() .
feof(), EOF .
, - .

: freadQ
,
fread() . :
string read(int fp, int length);

length ,
, .


,
.

: file_exists()
,
file_exists(), :
if (file_exists("$DOCOMENT_ROOT/../orders/orders.txt"))
echo "There are orders waiting to be processed.";
else
echo "There are currently no orders.";

2.

71

: filesizeQ
fflesize().
, :
echo filesize("$DOCUMENT_ROOT/../orders/orders.txt");
fread() ( ). :
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", "r");
echo fread( $fp, filesize("$DOCUMENT_ROOT/../orders/orders.txt" )) ;
fclose( $fp ) ;

unlink()
,
un!ink(). ( delete.) :
unlink("$DOCOMENT_ROOT/../orders/orders.txt");
false, . ,
.

: rewind(), fseek ftell()



rewind(), fseekQ ftell().
rewind() .
ftellQ . ,
( fcloseQ)
:
echo "Final position of the file pointer is ". (ftell ($fp));
echo "<br>";
rewind($fp);
echo "After rewind, the position is ". (ftell($fp));
echo "<br>";
. 2.5.

2.5


, ,
234 .
rewind

.

Bob's Auto Parts


Customer Orders
15:42, 20th April 4 tires 1 oil 6 spark plugs S434.00 22 Short St. Smalltown
15:43, 20th April 1 tires 0 oil 0 sparkplugs $100.00 33 MainRd,Newtown
15:43, 20th April 0 tires 1 oil 4 sparkplugs $26.00 127 AcaciaSt, Springfield

Final position of the file pointer is 234


After rewind, the position is 0

72

1. PHP

fseek()
.
int

f seek(int

fp,

int

offset);

fseek() Jp
, offset .
rewindQ fseek() , . , fseek()
. ,
,
.


,
. ( , Web- .) ,
fopenQ , fopen() ?
? , , ? ? , ?
, .
. flock(). , .
flock() :
bool flock (int f p ,

int operation);

, . true, , false .
operation . 2.2.
2.2 operation flock()

operation

. ,
.

. .
.

+4

4 operation
.

2.

/J

flock(), ,
;
.

processorder.php :
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", "a", 1) ;
flock($p, 2); //
fwrite($fp, $outputstring);
flock($fp, 3); //
fclose($fp);

vieworders.php:
$fp = fopen("$DOCUMENT_ROOT/../orders/orders.txt", "r");
flock($fp, 1); //
//
flock($fp, 3); //
fclose($p);

, . , ? , , , , , , .
, .

:

.
MySQL . : "
?"

,
:

, .
.
,
- . , (, , ),
.

. ,
,
. , " " .
, .
, - .

74

1. PHP


..
. (..
), , , .
.
, , .


() :
, . A MySQL, , ,

.

, .

, .

.
. MySQL .

,
, (, , ) ,
, . ,
PHP-, ?
II, " MySQL", , , , MySQL Web-, .


16. , ; , .
, , , http://www.php.net.


, -.

. , , ,
. , , , . .
, , .
, ,
.
,
. ,
- , , ,
Perl, , ,
. , , .
.
, , , . ,

, .
:
?

76

1. PHP


1 . , ; ,
, , .
, , .
. 3.1 , , Sproducts, . ( .)
Tires

Oil

Spark Plugs

3.1 , , .

, ,
. , 1,
, .
. , . ,
.
PHP- sort().
.
( ), .
, , , .
.
, , Perl. , , ,
.
.



, . 3.1,
:
$products = array( "Tires", "Oil", "Spark Plugs" );

products, : "Tires",
"Oil" "Spark Plugs". , echo, arrayQ , .

3.

/ /

, , , .
, , =.
,
range().
numbers, , 1
10:
$numbers

range(1,10) ;

, . " " .
, . 10.

.
" " .


. ,
, . , , , . .
, products,
Sproducts[0], Sproductsfl] $products[2].
. , C++, Java , , .
,
=. "Tires"
"Fuses".
$products[0 ] = "Fuses";


echo "$products(0]

$products[1]

$products[2]

$products[3]" ;

, . .
{products:
$products[0] = "Tires";
$products[l] = "Oil";
$products[2] = "Spark Plugs";

{products ,
. .

78

1. PHP


,
for:
for ( $i = 0; $i<3; $i++ )
echo "$products[$i] ";

, ,
. . ,
.


, . , 0 , -- 1 ..
. , .

, , .
$prices = array( "Tires"=>100, "Oil"=>10,

"Spark Plugs"=>4 ) ;


, ,
, prices
$prices[ "Tires" ], $prices[ "Oil"] Spicesf "Spark Plugs" ].
, .
Sprices.
,
.
$prices = array( "Tires"=>100 );
$prices["Oil"] = 10;
$prices["Spark Plugs"] = 4 ;

, , . .
.
$prices["Tires"] = 100;
$prices["0il"] = 10;
$prices["Spark Plugs"] = 4 ;

79

3.


each() Hst()

rii!'w>ii'i'H'u<iifiaHiiHfB i-iiira'MiiiiifiTiiiiiiiiin[ijfijtegil

"

Fevo.tes

lools

I ... ii . ' ' . . %J

,
for. Sprices:

Back

.-..'..:.'

St.-.p

Help

-l

RVS*

tver/chnpter3/eodi ptip

i i

Tires - 100
Oil - 10
Spark Plugs - 4

while( $element = each( $prices ) )


echo
echo
echo
echo

$element[ "key" ];
" - ";
$element[ "value" ] ;
"<br>";

3.2 each

.

, , . 3.2.
1 while echo. each(), .
.
each() while,
.
Selement .
each() . key 0 , value 1 . , , .
Iist() . , each(), :
$list( $product, $price ) = each( $prices ) ;

each() Sprices, .
, list() 0 1 , each(), : Sproduct Sprice.
Sprises, , .
while ( list( $product, $price ) = each( $prices ) )
echo "$product - $price<br>";

, , ,
list() .
each() , .
, reset()
. prices :
reset($prices);
while ( list( $product, $price )
echo "$product - $price<br>";

each( $prices ) )

80

1. PHP

, .

Code

Description '-Price'"

TIR

Tires

100

OIL

Oil

10

SPK
Spark Plugs
4


. , 3.3
. ,
, ,
,
.
.
, ,
,
.
. 3.3 , ,
, , .
, . 3.3, -:

$products = array( array( "TIR", "Tires", 100 ),


array( "OIL", "Oil", 10 ),
array( "SPK", "Spark Plugs", 4 ) ) ;

, .
, .
, . ( 0, 0.)

:
echo " I " . $ p r o d u c t s [ 0 ] [ 0 ] . " | " . $ p r o d u c t s [ 0 ] [ 1 ] " I " . $ p r o d u c t s [ 0 ] [ 2 ] . " | < B R > " ;
echo " | " . $ p r o d u c t s [ 1 ] [ 0 ] . " | " . $ p r o d u c t s [ 1 ] [ 1 ] . " | " . $ p r o d u c t s [ 1 ] [ 2 ] . " | < B R > " ;
echo " | " . $ p r o d u c t s [ 2 ] [ 0 ] . " | " . $ p r o d u c t s [ 2 ] [ 1 ] . " | " . $ p r o d u c t s [ 2 ] [ 2 ] . " | < B R > " ;

for
for.
for ( $row = 0; $row < 3; $row++ )
for ( $column = 0; $column < 3; $column++ )

{
echo "|".$products[$row][$column];
echo

"|<BR>";

3.
l T I R | T i r e s | 100 |
|OIL|Oil|10|
|SPK| Spark Plugs|4|

,
.
, , . 33. .
, . 3.3,
:
$products = array ( array ( Code => "TIE",
Description => "Tires",
price => 100
),
array ( Code => "OIL" ,
Description => "Oil",
price => 10
),
array ( Code => "SPK",
Description => "Spark Plugs",
price ~>4

, . , Description (),
1. , , [][]. , .
for
. :
for ( $row = 0; $row < 3; $row++ )
{
echo " | " . $products [$row] ["Code"] . " | " . $products [$row] ["Description"] .
" | " . $products [$row] [ "Price" ] . " |<BR>" ;
}

for Sproducts. Sproducts . eachQ list() while, . , for while.


for
(

$row = 0;

$row <

3;

$row++

while ( list( $key, $value ) = each( $products[ $row ] ) )


{
echo " | $ value" ;
}

echo "|<BR>";
!

He , , , ,
.

82

1. PHP

, .
,
,
.
, .

, .
, , ,
. 3.4.
, ,
.
$categories = array( array

Truck Parts
Description

Price

m\ Parts :
Code

Price

Description
p Car Parts

Code

Description

Prlci

CAFLTIR

Tires

10C

CAFLOIL

Oil

10

CAR.SPK

Spark Plugs


3.4
.

(array( "TIR",
array( "OIL",
array( "SPK",

"Tires", 100 ),
"Oil", 10 ),
"Spark Plugs", 4

array

(array( "TIR", "Tires", 100 ),


array( "OIL", "Oil", 10 ),
array( "SPK", "Spark Plugs", 4

array

(array) "TIR", "Tires", 100 ),


array( "OIL", "Oil", 10 ),
array( "SPK", "Spark Plugs", 4

, for.
$layer = 0; $layer < 3; $layer++ )

for

echo "Layer $layer<BR>";


for ( $row = 0; $row < 3; $row++ )
{
for ( $column = 0; $column < 3; $column++ )
{
echo " | " . $categories[$layer][$row][$column] ;
}

echo "|<BR>";

-, -,
.
, ,
. .

3.


, . .

sort()
:
$products = arrayf
sort($products) ;

"Tires",

"Oil",

"Spark Plugs"

);

: Oil, Spark
Plugs, Tires.
. ,
, ,
:
$prices = array(100, 10, 4 ) ;
sort($prioes) ;

4, 10, 100.
, sort , .. . , '' 'Z', 'Z' ''.

asort() ksortQ


, ,
.
, , .
$prices = array{ "Tires"=>100, "Oil"=>10, "Spark Plugs"=>4 );
asort(Sprices);

asort() .
, . , ,
ksortQ, , .
Oil, Spark Plugs,
Tires.
$prices = array( "Tires"=>100, "Oil"=>10, "Spark Plugs"=>4 );
ksort(Sprices);


sort(), asort() ksort(). .
, .
rsort(), arsort() krsort().
, . rsort() -

84

1. PHP

. arsort() .
krsort() .


, , , , .
,
. ,
.
.


.
, , .
$products = array( array( "TIR", "Tires", 100 ),
array( "OIL", "Oil", 10 ),
array( "SPK", "Spark Plugs", 4 ) ) ;

, ? , , , , .
. ,
, usort() , . .

.
function compare($x, $y)
{
if ( $[1] == $[1] )
return 0;
else if ( $x[l] < $[1] )
return -1;
else
return 1;
}
usort($products, compare);

PHP-. .
5, .
function.
. , (). , . () : . .

3.

QJ

, .
Description , $[1], Description ,
. Description , , $[1] $[1].
,
. . return. , return 1;
1 , .
usort(), compare()
. 0, , , , . , , 1 -1.
usort() ,
(Sproducts) (compareO).
, ,
. :
function compare($x, $y)
{
if ( $[2] == $[2] )
return 0;
else if ( $x[2] < $[2] )
return -1;
else
return 1;
}

usort($products, compare) .
"" usortQ "user" (""),
. uasortQ
uksortQ asortQ ksort() .
asort(), uasortQ . asort ,
.
, ,
uasortQ.
ksort(), uksort()
. ksort , .
, ,
uksort().


sort(), asort() ksort()
, "".

86

1. PHP

, . , ,
.
, 1, , -1,
. ,
function reverseCompare($x,
{
if ( $[2] == $[2] )
return 0;
else if ( $[2] < $[2] )
return I;
else
return -1;
)

$y)

usort($products, reverseCompare)
.


. shuffleQ
. array_reverse() ,
.

shuffle()
, . , ,
. , ,
.
, . , 3.1, , , .
3.1 bobs_front_page.php
Bob's Auto Parts

<?
$pictures = array("tire.jpg", "oil.jpg", "spark_plug.jpg",
"door.jpg",
"steering_wheel.jpg",
"thermostat.jpg",
"wiper_blade.jpg",
"gasket.jpg",
"brake_pad.jpg") ;
shuffle($pictures);
?>
<html>
<head>
<title>Bob's
</head>
<body>
<center>

Auto

Parts</title>

<hl>Bob's Auto Parts</Hl>


<table width = 100%>
<tr>

3.

for

87

$i = 0; $i < 3; $i++ )

echo "<td align = centerXimg src=\"";


echo $pictures [ $i] ;
echo "\" width = 100 height = 100x/td>" ;
</tr>
</table>
</center>
</body>
</html>

,
, . 3.5.

arrayjeverseQ
array_reverse() , . , , ,
10 1.
range() ,
rsort().
, for:
$numbers = array ();
for($i=10; $i>0; $i)
array_push{ $numbers,$i );

for() ,
. ,
-- .
, array_push() . , array_push() _().
.
|!- Dob's Auto

file

Edit'

':--$*f ;&

&

-d

4 !

s Address ]e] http://gm7book/ctiapter3/bobs_franLpage.php

3.5
shuffle()


.

Bob s Auto Parts

jj

1. PHP

array_reverse()
, range().
$numbers = range(1,10);
$numbers = array_reverse($numbers);

, array_reverse()
. ,
.


2 . :
15:42, 20th April 4 tires 1 oil 6 spark plugs $434.00 22 Short St, Smalltown

. , 3.2, .

3.2

vieworders.php

$orders= file ( " . . / . . /orders/orders . txt" ) ;


$number_of_orders = count ($orders) ;
if ($number_of_orders = 0)
{
echo "<pXstrong>No orders pending.
Please try again later .</strongX/p>" ;
}
for ($i=0; $i<$number_of_orders; $i++)
<
echo $orders [$i] . "<br>" ;

, . 2.4, 2.2 . file(), . .


count()
.
, , . , 3.3.
3.3 vieworders2.php ,

_
<html>
<head>
<title>Bob's Auto Parts - Customer Orders</title>
</head>
<body>
<hl>Bob' s Auto Parts</hl>
<h2>Customer Orders</h2>

3.

89

//
//
$orders= file("../../orders/orders.txt") ;
//
$number_of_orders = count($orders);
if ($number_of_orders == 0)
{
echo "<pXstrong>No orders pending.
Please try again later .</strongX/p>"
echo "<table border=l>\n";
echo "<trxth bgcolor = V #CCCCFF\">Order Date</td>
<th bgcolor = \"#CCCCFF\">Tires</td>
<th bgcolor = \"#CCCCFF\">Oil</td>
<th bgcolor = \"#CCCCFF\">Spark Plugs</td>
<th bgcolor = \"#CCCCFF\">Total</td>
<th bgcolor = \"#CCCCFF\">Address</td>
<tr>";
for ($i=0; $i<$number of orders;

//
$line = explode( "\t", $orders[$i] );
//
$line[l] = intvalf $line[l] );
$line[2] = intval< $line[2]
$line[3] = intval( $line[3]
//
echo "<trxtd>$line[0]</td>
<td align = right>$line[l]</td>
<td align = right>$line[2]</td>
<td align = right>$line[3]</td>
<td align = right>$line[4]</td>
<td>$line[5]</td>

echo "</table>";
</body>
</html>

, 3.3, , , 3.2, explode()


, .
. 3.6.
3.6


explode




.

Bob's Auto Parts


Customer Orders
Totd

! Order Du

Addra

; j

:\ 5:41, 20th April

4; 11

6 !4|22 Short SI, Smalltown

:15:43, 20lh April

b|$10aoi) 33 Main Rd. NcvUown

;15:47201 April

O j. . . . . .l i

0:

4; it26.bo 127 Acacia St, SpringGeidi

1.

explode :
array explode(string , string )
,
explode( "\t", $orders[$i] )

. . ,
"15:42, 20th April\t4 tires\tl oil\t6 spark plugs\t$434.00\t22 Short St,
* Small town"

"15:42, 20th April", "4 tires", "1 oil", "6 spark plugs", "S434.00"
"22 Short St, Smalltown".
.
(, ), , , , .
.
intval(). 1,
string integer.
, ,
integer. .


.
.

:
each, currentQ, resetQ, end(), next(), pos() prev()
, , .
each(), .
, . current( $array_name ) .
next() each() .
each($array_name) , . nextQ
next($array_name) , .
, reset() . , end($array_name)
. reset() end() , ,
.

3,


end() prev(). prev() next(). , .
,
:
$value = end ($array) ;
while ($value)
{
echo "$value<br>";
$value = prev($array);
}

Sarray :
$array = array (1, 2, 3) ;

each(), current(), reset(), end(), next(), pos() prev()


.

: array_walk()

.
array_walk.
array_walk() :
int array_walk(array arr,

string func,

[mixed userdata])

usortQ, , array_walk()
, .
, array_walk() . , arr , . , func , .
, userdata, .
. , .
, .
,
myPrint() Sarray:
function myPrint($value)
{
echo "$value<BR>";

array_walk($array, m y P r i n t ) ;

.
array_walk , ,

92

1. PHP

, userdata,
, :
Yourfunction(,

userdata)


.
userdata.
. userdata,
MyPrint().
,
. ,
, ,
.
function myMultiply(S$value, $key, $factor)
{
$value *= $factor;
}
array_walk(S$array, "myMultiply", 3 ) ;

myMultiply(), . array_walk(),
rayMultipIyO . myMultiplyO , (Svalue), (Skey) (Sfactor). .
Svalue. (&)
myMultiplyO , $value
.
.
5. ,
.

: count(), sizeof() array_count_values()


count(). sizeof() . . 1
0 , , .
array_count_values() . array_count_values($array),
, Sarray. (To , .) , . Sarray.
, , $.

3.

yj

,
$array = array (4, 5, 1, 2, 3, 1, 2, 1) ;
$ = array_count_values($array);

$,

, 4, 5 3 $ , 1 , 2 .

: extractQ
, -, extract() .
:
extract (array var_array [,

int extraot_type]

[,

string prefix]

);

extract() ,
, . ,
, .
.
$array = array( "keyl" => "valuel", "key2" => "valueZ",
"key3" => "values") ;
extract($array);
echo "$keyl $key2 $key3";

:
valuel value2 value3

keyl, key2 key3.


extract() $keyl, $key2 $key3.
, Skeyl, $key2 $key3 , , "valuel", "valuel" "valueS".
extract() : extractjtype prefix. extract_type extractQ , .
. extract_type . 3.1.

1.

3.1 extractjype extractQ

EXTR_OVERWRITE
EXTR_SKIP

.
.

EXTR_PREFIX_SAME

$prefix_key.
prefix.

EXTR_PREFIX_ALL

prefix.
.



(EXTR_OVERWRITE) EXTR_PREFIX_ALL. , ,
, . EXTR_PREFIX_ALL . ,
_-.
$array = array( "keyl" => "valuel", "key2" => "value2",
"key3" => "value3">;
extract($array, EXTR_PREFIX_ALL, "myPrefix");
echo "$myPrefix_keyl $myPrefix_key2 $myPrefix_key3";

valuel value! valueS.


, , extract() ,
, .. , , .



PHP-. ,
http://www.php.net.


. , , , , .


.
( ) , .
. ,
. ,
.
:




: Smart Form Mail



Smart
Form Mail.
Bob's Auto Parts,
.
,

96

L PHP


-
!-.* '$if &: ' ^: vV . ,?;.-,,-
, . 4.1.
KfcVv.
'
.
.

- iift'o- "

ivt'/dieijteH/le^db'-.ckHin!
_*j' ^?

^j
, Customer Feedback
Web.
Please tell us what you think.
Yournanie:
feedback@bobsdomain.com,
Your email address:

Your feedback:
1
. ,
v:3ei&fofcrffcijt<-: 1
a
"advertising" (""), ' 4.1 ,
-
. - .

, .
, - 4.1, .
:

4.1 processfeedback.php

<>

$toaddress = "feedback@bobsdomain.com";
$subject = "Feedback from web site";
$mailcontent = "Customer name: ".$name."\n"
."Customer email: ".$email."\n"
."Customer comments: \n".$feedback."\n";
$fromaddress = "webserver@bobsdomain.com";
mail($toaddress, $subject, $mailcontent, $fromaddress);

">>

<html>
<head>
<title>Bob's Auto Parts - Feedback Submitted</title>
</head>
<body>
<hl>Feedback submitted</hl>
<p>Your feedback has been sent.</p>
</body>
</html>
, , , ,
isempty(). .
, , PHP- mail() feedback@bobsdomain.com.
mail() , ,
.

4.

, . :
bool mail(string , string ,
string [_]

string

, , , , .
.
RFC822, Internet. (RFC, Requests For Comment (
), Internet. 17.) "From:" (":").
, "Reply-To:" (":") ":". , (\), :
$additional_headers="From:
webserver@bobsdomain.com\n"
."Reply-To: bobdbobsdomain.com";

email(), .
, .
.


, ( , HTML-), , .

: chopQ, ItrimQ trim()


. , ,
.
.
trim() :
$name=trim($name);
$email=trim($email);
$ feedback=trim($ feedback);

trim() . (\),
(\), (\t) (\v),
(\0) .
ltrim() chop(). trim()
, . , trim()
, ltrim() ( ), a chop() ( ) .
4 216

98

1. PHP


, .
HTML-: n!2br()
n!2br()
<BR> HTML. . , :
<p>Your feedback (shown below) has been
<pX? echo n!2br ($mailcontent) ; ?> </p>

sent.</p>

, HTML . ,
!2(),
( , ). . 4.2.
i


echo
.
print(), , echo,
, (0 1,
).
" ". printf()
sprintfO, . ,
, printf()
, a sprintfO .
, , ,
-. , , , .
:
string sprintf (string format [, mixed args ...])
int printf (string format [, mixed args ...])

,
,
. ,
.
4.2

PHP- nl2br()


HTML.

Without nl2br:
Customer name: Jane Smith Customer email: iane^somewhere Customer
comments: Thank you for providing electronic ordering on your website.
With n!2br:
Customer name: Jane Smith
Customer email: jane@somewtiere
Customer comments:
Thank you for providing electronic ordering on your website.

4.

Js

, echo , , :
echo "Total amount of order is

$Total.";

printf()
printf ("Total amount of order is %s.", $total);
%s .
" ".
Stotal, .
, Stotal, 12.4,
12.4.
printf() ,
,
Stotal
, :
printf ("Total amount of order is %.2f", $total);
.
. , . :
printf ("Total amount of order is % . 2 f
$total_shipping);

(with shipping % . 2 f )

",

$total,

Stotal, Stotal_shipping.

%['_][-][][.]
%. %, %%.
_ . .
, .
"-" . , , , .
printfQ, ( ) .
. .
. . 4.1.
, ,
\. . , \ . , , \t, , \s,
.

100

1. PHP

4.1


a-f .


A-F .


.
, , , .
, Ssubject,
, . . 4.2.
4.2


$subject

Feedback from web site

strtouppperQ

strtouppper($subjecf)

FEEDBACK FROM WEB SITE

strtolower()

strtolower($subject)

feedback from web site

ucfirs+()

ucfirst($subject)

Feedback from web site

ucwordsQ



,
.

ucwords($subject)

Feedback From Web Site

: AddSlashesQ StripSlashesQ
,

.
II, .
, , ,
. ( ), (\) NUL.

4.

1U1

, ,
, MySQL, , , . ,
. , " ( ) \", \ \\.
( ,
\\ \\\\.)
,
. , AddSlashesQ. :
$feedback

AddSlashes($feedback);

, AddSlashesQ
.
AddSlashesQ
.
. StripSlashes():
$feedback = StripSlashes($feedback);

. 4.3.
, .
. 21.

. , (, )
. ( ),
.
,
bigcustomer.com , , , , ,
.

/..' . gjii
4.3

AddSlashes()

.
Strip SlashesQ
.

Customer feedback before AddSlashes:


Your customer service representative told me, "We don't give any guarantees."
What kind of service is ?
Customer feedback after AddSlashes:
Your customer service representative told , V'We donVr give any guaraateesA"
What kind of service is that?
Customer feedback after StripSlashes:
Your customer service representative told me, "We don't give any guarantees."
What kind of service is that?

102.

1. PHP

explode(), implodef) join()


, explode(), ,
:
array explode(string separator, string input);
input separator. .
:
$email_array = explode("@", $email);
explode() : , $email_array[0], , $email_array[l].
:
if

($email_array[1]=="bigcustomer.com")
$toaddress = "bob@bobsdomain.com";
else
$toaddress = "feedback@bobsdomain.com";
, , . ,
, :
$email_array[1]

strtoupper

($email_array[1]);

, explodeQ, , iinplodeO join(), . :


$new_email

implode("@",

$email_array);

Semail_array
, .
explode(), .

strtok()
explode(), ,
strtokQ ( ) . explode()
.
strtok() :
srting strtok(string input, string separator);
separator , , , (
explode).
strtok() , , .
strtokQ , , . -

4.

1U 3

.
. , .
, srtok() :
Stoken = strtok($feedback,
echo $token."<br>" ;
while ($token!="")
{
$token = strtok(" ");
echo $token."<br>";
};

"

");

, , , emty(), - .
.

. , strtok() , .
( ) strtok() . , . ,
0, . - strtok() , . explode().

substrQ
substr() . ,
, .
substr() :
string substr(string ,

int ,

int []

);

.
:
$test = "Your customer service is excellent" ;

(), , . ,
substr($test,

1);

"our customer service is excellent". , 0, .


substrQ ,
, , . ,
substr($test,

-9);

"excellent".

104

1. PHP

,
( ),
( ). ,
substr($test,

0,

4) ;

, "Your". :
echo

substr ($test,

4,

-13);

, , .. "customer service".


=
.
. :
. , , Smart Form.

: strcmp(), strcasecmp() strnatcmpQ


,
.
strcmp()
int strcmp(string strl, string str2) ;

, . ,
0. strl
str2 ( ), strcmpQ . strl strl, strcmp() . .
strcasecmpO ,
.
strnatcmpO srtnatcasecmpO 4. "
", . , strcmp() "2" "12", . strnatcm() . http://www.linuxcare.com.au/projects/natsort/

strlenQ
strlenQ.
, . , strlen("hello")
5.
.
,
Semail. ,
email . ,

4.

105

- , ,
a@a.to. , , :
if
<

(strlen($email)
echo
exit;

<

6)

"That email address is not valid";


// PHP

, .
.

.
, .
Smart Form . ,
, , ,
"shop" ( ).
, explode() strtok() ,
, == strcmp().
, .
.
.

: strstrQ, strchrQ, strrchrQ, stristrQ



strstrQ, strchr(), strrchrO stristrQ.
strstr() . ,
strchrQ strstr(),
, , -.
, , .
strstr() :
string strstr(string haystack, string needle);

haystack, , needle, . needle haystack, needle; false.


needle , needle.

106

1. PHP

, Smart Form :
$toaddress

"feedback@bobsdomain.com";

//

//
if

$toaddress
(strstr($feedback, "shop"))
$toaddress = "retail@bobsdomain.com";
else if (strstr($feedback, "delivery"))
$toaddress = "fulfilment@bobsdomain.com";
else if (strstr($feedback, "bill"))
$toaddress = "accounts@bobsdomain.com";

. ,
, "I still haven't received delivery of my last order",
"delivery",
fulfilment@bobsdomain.com.
strstr(). stristrQ, , .
, "delivery", "Delivery" "DELIVERY".
strrchr(),
strstr(), haystack, needle.

: strpos(), strrpos()
strposQ strrpos() strstr() , needle
haystack.
strposO :
string strpos(string haystack,

string needle,

int

[offset]

);

needle
haystack. , .
, 4 :
$test = "Hello world";
echo strpos($test, "o");

needle ,
.
offset
haystack, . ,
echo strpos ($test, " " , 5) ;

7 ,
5 , , 4.
strrpos() , needle haystack. strposQ,
- needle. , needle, .
, needle , strpos()
strrposQ false. ,

4.

1U /

false 0, ..,
.
=== :
$result = strpos($test, "H");
if ($result === false)
echo "Not found"
else
echo "Found at position 0";

, 4 , ,
(.., false).

: strjeplaceQ, substr_replace()

.
, , ,
, a address . , , Smart Form.
.
, str_replace().
:
string str_replace(string needle, string new_needle, string haystack);

needle haystack
new_needle.
, Smart Form
,
. , :
$feedback = str_replace($offcolor, "%!@*", $feedback);

substr_replace() . :
string substr_replace(string needle, string replacement,
int start, int [length] ) ;

string replacement. start length.


start , . 0 , , . , $test "X":
$test

substr_replace($test,

"X",

-1) ;

length , . , , start, .

108

1. PHP

length ,
.
length , .
length , , .


: POSIX Perl.
POSIX , Perl
, PCRE (Perl-compatible
regular expression Perl- ).
POSIX, Perl ,
PCRE, http://php.net.

.
. , , "shop" "delivery".
strstrO, , , - . (
, .) ,
"shop" "shop". "h", "ho" ..

.
, ,
, . . .


.

, .
, "."
, (\). ,
.at

, , "cat", "sat" "mat".



.
, , , , , . -

4.

1U J/

"mat" "cat", "#at".


, :
[a-z]

, [ ], , . , .
. ,
[aeiou]

.
, , :
[a-zA-Z]
.
,
. ,
[-a-z]

, a-z.
, "".
, .
,
. 4.3.
4.3 , POSIX

[[:alnum:]]

[[:alpha:]]

[[:lower:]]

[[:upper:]]

[[.digit:]]

[[:xdigit:]]

[[:punct:]]
[[::]]
[[:space:]]
[[:cntrl:]]
[[:print:]]
[[.graph:]]

no

1. PHP


.
. * ,
, + 1 . , . ,
[[:alnum:]]+
" - ".

, , ,
" ,
". , . ,
(very )*large

"large", "very large", "very very large" ..


-
, ({}).
({3} 3 ),
({2, 4} 2 4 ) ({2,} ).
,
(very ) { 1 , 3}
"very", "very very" "very very very".


, , . , , .
( )
, , $
, .
, bob :

com :
$

, , z,
:

[- 2 ]$

4.

(|). , com, edu net,


:
(com) I (edu) | (net)

, , ., { $, (\).
,
, .. \\.


. 4.4 4.5. . 4.4
, . 4.5 .
4.4 ,
POSIX


, (\)

4.5 ,
POSIX

Smart Form

Smart Form ,
, . - -

112

1. PHP

.
. "shop", "customer service" "retail" .
:
shop I customer

service|retail


. - , @, -
, , - , , , ; :
A

[a-zA-ZO-9_]+@[a-zA-ZO-9\-]+\.[a-zA-ZO-9\-\.]+$

A[a-zA-ZO-9_]+ "
, , - ".
@ @.
[a-zA-ZO-9\-]+ , - . , , .
\. ".".
[a-zA-ZO-9\-\.]+$ ,
, , , ,
.
, , . ,
- .
, , PHP-, .


. , : ereg() eregi().
ereg() :
int ereg(string pattern,

string search,

array

[matches]);

search,
, pattern. pattern , matches, .
eregi() , , .

4.
Smart Form :
if
(!eregi(11A[a-zA-ZO-9_]+@[a-zA-ZO-9\-]+\.[a-zA-ZO-9\-\.]+$",
$email) )
{

echo "That is not a valid email address.


. " previous page and try again." ;
exit;

Please return to the"

$toaddress = "feedback@bobsdomain.com";
//
if (eregi("shop|customer service|retail", $feedback))
$toaddress = "retail@bobsdomain.com";
else if (eregi("deliver.*|fulfil.*", $feedback))
$toaddress = "fulfilment@bobsdomain.com";
else if (eregi("bill{account", $feedback))
$toaddress = "accounts@bobsdomain.com";
if

(eregi("bigcustomer\.com", $email))
$toaddress = "bob@bobsdomain.com";



, str_replace(). : ereg_replace() eregi_replace(). ereg_replace()
:
string ereg_replace(string pattern, string replacement, string search);
pattern search
replacement.
eregi_replace() , .


split(),
:
array split(string pattern, string search, int [max]);
search
pattern . max
, .
. ,
$domain = " y a l l a r a . c s . r m i t . e d u . a u " ;
$arr = split ( " \ . " , $domain);
while (list($key, $value) = each ( $ a r r ) )
echo "<br>".$value;

114 1. PHP

, . , , .


.
UNIX,
, regexp. ,
devshed.com phpbuilder.com.
Web- Zend , , . MailVal()
http://www.zend.com/codex.php?id=88&single=l.

, .



, , .

,
, , .
, requireQ include() .
,
.
.
, ,
.
:
?
requireQ include()

?





116

1. PHP

?
, , .
, . , .
.

- , , , .
,
.
.
. , , . . ,
, , . .

, ,
. ,
-,

. , , , , "".

, , . , ,
. , , .
,
, , . , .

require)) include))
PHP , , . require() include(),
PHP-. , -

5.

\ /

, PHP-, , HTML-, - -.
(Server Side
Includes), Web-, include
C++.

require()
reusable.php:
echo "Here is a very simple PHP statement.<BR>";
main.php:
echo "This is the main file.<BR>";
require( "reusable.php" ) ;
echo"The script will end now.<BR>";

, , reusable.php
"Here is a very simple PHP statement."
main.php - . .
5.1.
I fX http://web server/chapters/ma in php - Mirrnsnft Internet
Edit View
I-

5.1
,
main.php,


requireQ.

Fevoites

lools

pWsrJvr:/ 1 .

(Bhp;//'webseiver/ctiap(arB/main.php

This is the main file.


Here is a very simple PHP statement.
The script will end now.

require(). reusable.php. require()


require ( "reusable.php" ) ;

, .
, main.php , :
<?

echo "This is the main ile.<BR>";


echo "Here is a very simple PHP statement. <BR>" ;
echo"The script will end now.<BR>";

require()
-.

118

1. PHP

require()
. , , . requireQ ,
PHP- .
PHP- , , , , page.html. , , .php.
page.html requireQ, PHP-
. , , .inc.
, , .inc
- , Web,
,
, .
,
.

PHP- requireQ
(reusable.php) :
echo "Here is a very simple PHP statement.<BR>";
PHP- PHP-. ,
, PHP-
PHP-. PHP-,
HTML .


require))
Web-
Web- ,


require().
, Web- TLA Consulting , . 5.2.
, ,
,
.

-.^ ''>'; :
Beck

,_(,_/
<<-:';

1 !i-t'f si-

i-tc nw

,t,-;jK'ii

cliap'etS/hDma.hlml

TLA Consulting
Home

Contact

IOServices 1OSite Map

Welcome to the home of TLA Consulting. Please take some


time to get to know us.
We specialize in serving your business needs and hope to
hear from you soon.

5.2 Web-
TLA Consulting
.

5.

: Web- , , , , .
- ,
, . , ?
HTML, , ,
, . (home.html),
. 5.2, 5.1.
5.1 home.html - HTML-,

TLA
Consulting

<html>
<head>
<title>TIA Consulting Pty Ltd</title>
<style>
hi (color: white; font-size :24pt; text-align : center ;
font-family : arial , sans-serif)
.menu {color: white; font-size: 12pt; text-align : center ;
font-family : arial , sans-serif; font-weight : bold)
td {background: black)
p {color :black; font-size: 12pt; text-align: justify;
font-family: arial , sans-serif)
p. foot {color: white; font-size :9pt; text-align: center;
font-family : arial , sans-serif ; font-weight : bold)
a : link , a : visited, a : active {color : white )
</style>
</head>
<body>
<! page header >
<table width="100%" cellpadding = 12 cellspacing =0
<tr bgcolor = black>
<td align = leftximg src = "logo.gif "X/td>
<td>
<hl>TLA Consulting</hl>
</td>
<td align = rightximg ere = "logo.gif "X/td>
</tr>
</table>

border

0>

<! menu -->


<table width = "100%" bgcolor = white cellpadding = 4 cellspacing = 4>
<tr >
<td width = "25%">
<img src = "s-logo.gif "> <span class=menu>Home</spanx/td>
<td width = "25%">
<img src = "s-logo.gif "> <span class=menu>Contact</spanX/td>
<td width = "25%">
<img src = "s-logo.gif "> <span class=menu>Services</spanx/td>
<td width = "25%">
<img src = "s-logo.gif "> <span class=menu>Site Map</spanX/td>
</tr>
</table>

1.ZU

1. PHP

<!-- page content >


<p>Welcome to the home of TLA Consulting.
Please take some time to get to know us . </p>
<p>We specialize in serving your business needs
and hope to hear from you soon.</p>
<!-- page footer >
<table width = "100%" bgcolor = black cellpadding = 12 border =
0>

<tr>
<td>
<p class=foot>ficopy; TLA Consulting Pty Ltd.</p>
<p class=foot>Please see our <a href ="">
legal information page</aX/p>
</td>
</tr>
</table>
</body>
</html>
5.1, .
HTML- CSS- (Cascading Style Sheet, CSS), . , "page header" (" "),
, "menu" ("")
, a "page content" (" ") ,
. . header.inc, home.php footer.inc.
header.inc footer.inc ,
.
home.php home.html require(), 5.2.
5.2 home.php PHP-,
TLA Consulting

<?
?>

require ("header .inc") ;


<!-- page content >
<p>Welcome to the home of TLA Consulting.
Please take some time to get to know us.</p>
<p>We specialize in serving your business needs
and hope to hear from you soon.</p>

<?

require ("footer . inc") ;

requireQ home.php header.inc footer.inc.


, , ,
requireQ. , , ,
, something.mc ( inc include ()).
, ,
, -

5.

\_2, J.

Web-. , ) - , .php, , )
.
header.inc CSS-, , , , (.

5.3).
5.3 header.inc
Web- TLA
<htrol>
<head>
<title>TLA Consulting Pty Ltd</title>
<style>
hi {color:white; font-size:24pt; text-align:center;
font-family:arial,sans-serif}
.menu {color:white; font-size:12pt; text-align:center;
font-family:arial,sans-serif; font-weight:bold}
td {background:black}
p {color:black; font-size:12pt; text-align:justify;
font-family:arial,sans-serif)
p.foot {color:white; font-size:9pt; text-align:center;
font-family:arial,sans-serif; font-weight:bold)
a:link,a:visited,a:active {color:white}
</style>
</head>
<body>
<!-- page header >
<table width="100%" cellpadding = 12 cellspacing =0 border = 0>
<tr bgcolor = black>
<td align = leftximg src = "logo.gif "></td>
<td>
<hl>TLA Consulting</hl>
</td>
<td align = rightximg src = "logo. gif "X/td>
</tr>
</table>
<! menu -->
<table width =
= 4>
<tr >
<td width =
<img src
<td width =
<img src
<td width =
<img src
<td width =
<img src
</tr>
</table>

"100%" bgcolor = white cellpadding = 4 cellspacing


"25%">
= "s-logo.gif"> <span class=menu>Home</spanX/td>
"25%">
= "s-logo.gif"> <span class=menu>Contact</span></td>
"25%">
= "s-logo.gif"> <span class=menu>Services</spanX/td>
"25%">
= "s-logo.gif"> <span class=menu>Site Map</spanX/td>

footer.inc , . 5.4.

122

1. PHP

5.4 footer.inc -
Web- TLA
<! page
<table
<tr>
<td>
<p
<p

footer >
width = "100%" bgcolor = black cellpadding = 12 border = 0>

class=foot>&copy; TLA Consulting Pty Ltd.</p>


class=foot>Please see our
<a href =" legal .php3">legal information page</aX/p>
</td>
</tr>
</table>
</body>
</html>
Web-,
, - :
<? require("header.inc"); ?>
Here is the content for this page
<? require("footer.inc"); ?>
, , ,
, . , , ,
. , .
, HTML-. .
PHP- .

auto_prepend_file auto_append_file
require() , .
php.ini : auto_prepend_file auto_append_file. , , , .
Windows - :
auto_prepend_file = ":/inetpub/include/header.inc"
auto_append_file = ":/inetpub/include/footer.inc"
UNIX :
auto_prepend_file * "/home/username/include/header.inc"
auto_append_file = "/home/username/include/footer.inc"
recuireQ,

.
Web- Apache , , .
() . -

5.

123

, , .htaccess.
:
php_value
auto_prepend_file
"/home/username/include/header.inc"
php_value auto_append_file "/home/username/include/footer.inc"

, php.ini: php_value .
php.ini .
3. .htaccess :
php3_auto_prepend_ile "/home/username/include/header.inc"
php3_auto_append_file "/home/username/include/footer.inc"

.htaccess, php.ini Web- .


, . Web-
. .htaccess
,
, ,
.

includeQ
require() include() , .
include() , . require()
, , .
, , , , require() , .
if(variable == true)
{
require("filel.inc");
}
else
<

require("file2.inc") ;

,
,
Svariable. , include(),
, :
if($variable == true)
{
include("filel.inc") ;

124

1. PHP

else
{

include ( " f ilea . inc" ) ;

>

, require(), , include(), . , , .
, , ,
. "openfile.inc" :
<?

@ $ = fopen($name, $mode) ;
if (!$fp)
{

echo "<pXstrong> Oh No! I could not open the file.</etrongX/p>" ;


return 0 ;

>

else
{
return 1 ;

Sname. ,
Smode. 0. 1 - .
:
$name = "file.txt";
$mode = "r" ;
$result = include ("openfile .php" ) ;
if( $result == 1 )
{
//
// $fp,
}
, ,
, .
require(), include() .
require() , , . , .
,
. .
: require(), include()? , require() .

5.

125


.
, , .
.
, , , , .
.
, . ,
. .


:
function_name();
functionjnaine, .
, .
. phpinfoQ
, ,
, Web- . ,
; phpinfoQ
:
phpinf() ;

, . , , .
:
function_name("parameter");

,
parameter, :
function_name(2) ;
function_naroe(7.993);
function_name($variable) ;

Svariable PHP-
, .
, , .
,
, .
; PHP- http://www.php.net.

126

1. PHP

, , fopenQ:
int

fopen(

string

filename,

etring

mode,

[int

use_includ_path]

);

. int ,
. . .
filename (_) mode () ,
use_include_path .
i
use_include_path , . , '
.
, fopen():
$name = "myf ile. tact" ;
$openmode = "r";
$p = fopen($name, $openmode)

fopen().
Sfp. Sname, , , Sopenmode, , . .


, ,
, . 5.3.
, . , ,
, .
.
:
1. ?
2. ?

5.3


,
.

nttp.//web8eiver/cneptef5/undefined.php

Fatal error: Call to unsupported or undefined function function_name()


in /home/book/publlc html/chapter5/undeflned.php on line

^; 0

-~^>*.

?s*--

-'

^^ WO.

>

>

0tio

a-Hed"

'

HP*' ^ -

5.

\ 2;/

, .

, .

.
. . , ,
.
, PHP- , ,
. ,
, , .
:
name ()
name2()
name_three()()
name four ()

:
5name()
name-six ()
fopen()

( , .)

,
.
. , . .
function create_table($data)
{
echo "<table border = 1>" ;
r e s e t ( $ d a t a ) ; //
$value = current($data);
while ($value)
{
echo "<trXtd>$value</tdX/tr>\n" ;
$value = next($data);
}
echo "</table>";
}

create_table() :
$my_array = array("Line
create_table($my_array);

one.","Line

two.","Line

, . 5.4.
5 . 216

three.");

1 3U

1.
nhln.php - Microsoft Internet Lxplor . ^

1 31 h"P //wi'br,

5.4
HTML-

create_table().

j Address Q hltp://WBbseiver/chept9r5/crsete_te

jjLine one. (I
||Lmetwo. j|
IJLlne three.

,
, $data.
,
. create_table() , .
. ,
, .
$data,

function create_table2(
$cellspacing=4 )

$border=l,

echo

$cellpadding=4,

"<table border = $border cellpadding =


." cellspacing
$cellspacing>" ;
reset($data) ;
$value = current($data);
while ($value)

$cellpadding"

echo "<trxtd>$value</td></tr>\n" ;
$value = next($data);
echo

"</table>";

create_table2() - .
, . , . 5.4, create_table2().
create_table2($my_array);

, , :
create_table2($my_array,

3,

8,

8);

,
. .
, -
, . , cellspacing,
cellpadding. .

5,

J. J 1

.
:
create_table2($my_array,

3) ;

, Sborder 3, Scellpadding Scellspacing .


, ,
require() include(),
. , , , .
, .
, . :
, , , .
, .
, , , , . , 1 .
require() include() . ,
. ,
.
global , , ,
.

\msKt($variable_name). , .
.
. Svar
fh(). ,
.
Svar , $var.
. , ,
Svar echo, .

1 J Z.

1. PHP

function
fn()
{
$var = "contents";
}
echo $var ;

. , .
function fn()

echo "inside the function,


$var = "contents2";
echo "inside the function,

$var = "contents
fn();

echo

\$var = ".$var."<br>";
\$var = ".$var."<br>";

1";

"outside the function,

\$var =

".$var."<br>";

:
inside the function, $var =
inside the function, $var = contents 2
outside the function, $var = contents 1

, , Svar = "contents 1";


$var, "contents 1".
fh(). . $var.
, Svar, , ,
. .
$var
"contents 2". ,
Svar, .
.
,
. echo , .
, , , ,
global, :
function

fn ( )

global $var;
$var = "contents";
echo "inside the function,

}
fn () ;
echo "outside

the

function,

\$var

\$var

".$var."<br>";
".$var."<br>";

Svar , .. . :
inside the function, $var = contents
outside the function, $var = contents

5.

133

, , , global $var;.
, . ( ,
!). , , , .
global
, . , global.
,
. ,
, , , ,
.


increment(). ,
:
function increment($value, $amount = 1)
{
$value = $value +$amount;
}

.
"10".
$value = 10;
increment ($value);
echo $value;

, Svalue .
. Svalue,
10. increment(). Svalue . 1, Svalue 11 ,
. ' Svalue , ,
.
Svalue , ,
, , Svalue.
.
.
,
. .
, .
.
, , -

1.34

1. PHP

. , , , . , ,
, . , , .
(&) .
.
increment() ,
, .
function increment(S$value,
{

$amount = 1)

$value = $value + $amount;

>

, . ,
, .
10 increment()
11 .
$ = 10;
echo $
increment ( $ a ) ;
echo $;


return . , , return, , .
echo.
function test_return()
{

echo "This statement will be executed";


return;
echo "This statement will never be executed";

, return.
.
return . ,
, ,
.
function larger( $,
{

$ )

if (! isset <$) | | ! isset ( $ y ) )


{

echo "this
return;

function requires

two numbers";

5.

135

if

($>=$)
echo $ ;
else
echo $;
}

isset() ,
.
, .
!isset(), " isset()", , if " ". , .
return , . , . , .
:
$ = 1;
$ = 2.5;
$ = 1.9;
larger($, $) ;
larger($c, $) ;
larger($d, $a) ;

:
2.5
1.9
this function requires two numbers


return.
return
. ,
largerQ .
, . ()
.
larger() :
function larger ( $ x , $y)
{

if

(!isset($x) | | ! i s s e t ( $ y ) )
return -1.7E+308;
else if ($x>=$y)
return $x;
else
return $y;

>

. . , -1.710308.
. ()
, ,
, .

136

1. PHP

^
308

-1.7x10 ? . , 308
. -1.710
, 4.0, , ,
. , .
:

$ = 1; $ = 2.5; $ = 1.9;
echo larger($a, $)."<br>";
echo larger($c, $a)."<br>";
echo larger($d, $a)."<br>";

:
2.5
1.9
-1.7E+308

, , , true false
. true false 1 0.


.
,
, .
.


for($i = 0; $i < 3; $i++ )
echo "Line Kbr>" ;
echo "Line 2<br>";


for($i = 0; $i < 3; $i++ )
<
echo "Line Kbr>" ;
echo "Line 2<br>";
}

for . , ,
for. , , :
Line 1
Line I
Line 1
Line 2

. , for . ,
, :

5.
Line
Line
Line
Line
Line
Line

13/

1
2
1
2
1
2

, , . , for.
, .
,
.

. , .
, .
Web- ,
. ,
. , ,
.
, 5.5.
5.5 recursion.php
( )
function
{

reverse_r ($str)

if

(strlen($str)>0)
reverse_r (substr ($str, 1));
echo substr($str, 0, 1} ;
return;

function reverse_i($str)
{
for ($i=l; $i<=strlen($str) ; $i++)

echo substr($str, -$i, 1) ;

return;

.
. reverse_r() , a reverse_i() .
reverse_r() .
, .
,
reverse_r ("Hello") ;
:

138

1.

reverse_r("ello");
reverse_r ( " " ) ;
reverse_r("lo");
reverse_r("");
raverse_r("");

, . ,
. .
.
(strlen()==0).
(reverse_r("")) ,
, .
, , reverse_r("o"). -
, "", .
, ,
.
.
, .
5.5. ,
(
) .
, , ,
, .
, , .
, . , , , , .


includeQ, require(), function return . , ,
/ , , .


,
, , - .
, , , .

PHP


.

-
,

- .
- ()
,
.

1. PHP


- ,
, ,
, .
, , .
-
, , . , . , ,
- .
-
, . , , .
, ,
. ,
, .
-
, -
. , Web
,
- .
. Web- .
, ; Web, . ,
, .
Web , , . , HTML-, .
, , , .
-
,
. , , .
"", 60 20 ,
. , ( ) .

6. -

141

. ,
, . , ,
,
.
"" , , ,
, ,
, , .
, .
, , , , . , , , ,
.

- .. . , .
.
. , ,
, .
, .
- . - . , , , .
, ,
. ( .)
, , , . ,
, .


. . , .
, ,
, , .
, .
. -

142

1. PHP

,
- .
,

. . "" , , . " " ,
" " , . , .

,
.
class.


:
class classname

, . var. classname : Sattributel


Sattributel.
class classname
{
var $attributel ;
var $attribute2 ;
}

. classname , . operation 1() ,


operation2() .
class classname
{
function operationl ()
{
}

function operation2 ($paraml,

$param2)

, .
,
, .

6. -

143

, ,
, . , , .
:
class classname
{
function classname ($param)
{

echo "Constructor called with parameter $param <br>;

, .. ; . ( - .)


, , .
. new. , ,
, .
classname ,
classname:
class classname
{
function classname ($param)
{

echo "Constructor called with parameter $param <br>";

$a = new classname ("First") ;


$b = new classname ("Second") ;
$c = new classname ( ) ;
,
:
Constructor called with parameter First
Constructor called with parameter Second
Constructor called with parameter


Sthis. Sattribute,

Sthis-Attribute.

144

1. PHP

:
class classname
{
var $attribute;

function operation ($param)


<
$this->attribute = $param
echo $this->attribute;


.
, (..
).
,
:
class classname
{
var $attribute;
}
$a = new classname ( ) ;
$a->attribute = "value" ;
echo $a->attribute;

.
- , . , .
,
, .
:
class classname
{
var $attr ibute ;
function get_attribute()
<
return $this->attribute;
}
function set_attribute ($new_value)
{

$this->attribute = $new_value;

Sattribute.
get_attribute(),
Sattribute, set_attribute(),
{attribute.
. ,
, , , :
.

6. -

14 J

,
. ,
Sattribute 0 100,
,
. set_attribute() :
function set_attribute($new_value)
{
i f ( $new_value >= 0 && $newvalue <= 100 )
$this->attribute = $new_value;
}

, ,
Sattribute .
, . - Sattribute, ,
.
, Sattribute
, , , ,
. , .
, , .


.
, :
class classname
{
function operationl()
{
}
function opera tion2 ($paraml,

$param2)

classname $ :
$ = new classname ()

, : .
, , , . , :
$a->operationl ( ) ;
$a->operation2(12,

"test") ;

-,
:

146

I. PHP

$ = $a->operationl () ;
$ = $a->operation2 (12, "test");


, extends. , .
class extends A
{
var $attribute2 ;
function operation2()

:
class A
{

var $attributel ;
function operationl()

:
$ = new B() ;
$b->operationl () ;
$b->attributel = 10;
$b->operation2 () ;
$b->attribute2 = 10;

, , operationl() Sattribute ,
. , . ,
.
, . ,
, , , .
, :
$ = new A() ;
$a->operationl () ;
$a->attributel = 10;
$a->operation2 ( ) ;
$a->attribute2 = 10;

operation! attribute!.

, .. .
, -

6. -

147

,
, . .
, :
class A

<

var $attribute = "default value";


function operation ( )

echo "Something<br>" ;
echo "The value of \$attribute is $this->attribute<br>" ;

Sattribnte opera tion().


, Sattribute operation():
class extends A
{
var $attribute = "different value";
function operation ()

<

echo "Something else<br>" ;


echo "The value of \$attribute is $this->attribute<br>" ;

. :
$ = new ( ) ;

$ -> operation ( ) ;

operation().

Some thing
The value of $attribute is default value

, . ,
.

$ = new () ;

$ -> operation () ;


Something else
The value of $attribute is different value

, , .
,
. , .

148

1. PHP

- , , , .
. , , , .
, .


- , . ,
. ,
, .
. . 6.1 , .

6.1

, , ,
, . , , .
, . , , .
, .
, , .


, , , , .

. , , , Web-, , , , , .

6. -


, , ,
. ' . , , , -'
.
Web- TLA
Consulting. ,
,
.
TLA, . , .
Page.
HTML-, .
, ,
, .
,
.
,
HTML, ,
, :

. ,
.


, , ,
.

, , , , , .

. ,
,
.


, , ?
.
, - -.
. ,
Page. Page
class Page

150

1. PHP

. , , , , . , HTML-
, Scontent. :
var

$content;

. ,
, . ,
:
var $title = "TLA Consulting Pty Ltd" ;

Web- , . , , , .
:
var

$keywords

"TLA Consulting, Three Letter Abbreviation,


some of my best friends are search engines";

, . 5.2 (. ), , , ; , ,
. ,
, Web-, .
var $buttons = array( "Home"

=> "home.php",
"Contact" => "contact.php",
"Services" => "services.php",
"site Map" => "map.php"

);

,
.
.
:
function
{

SetContent($newcontent)

$this->content = $newcontent;

,
, GET.
HTML-,
. DisplayQ :
function Display()
{
echo "<html>\n<head>\n";
$this -> DisplayTitleO ;
$this -> DisplayKeywords();
$this -> DisplayStyles() ;
echo "</head>\n<body>\n";
$this -> DisplayHeader() ;

6. -

151

$this -> DisplayMenu($this->buttons);


echo $this->content;
$this -> DisplayFooter();
echo "</body>\n</html>\n";
}

echo
HTML-, . , , , .
. .
.
. ,
. ,
.
, .
DisplayQ, . , .
Display DisplayTitle(), DisplayKeywords(), DisplayStylesQ,
DisplayHeader(), DisplayNenu() DispIayFooterQ. ,
. 4 3 ,
. 3
, .
HTML- , , .
, page.inc
, 6.1.
6.1 page.inc Page
TLA

<?

class Page
{
// Page
var $content;

var $title = "TLA Consulting Pty Ltd";


var $keywords = "TLA Consulting, Three Letter Abbreviation,
some of my best friends are search engines";

var $buttons = array(

"Home"
"Contact"

=>
=>

"home.php",
"contact.php",

"Services"
"Site Map"

=>
=>

"services.php",
"map.php"

);
// Page
function SetContent($newcontent)
{
$this->content = $newcontent;
}
function SetTitle($newtitle)
<
$this->title = $newtitle;

152

1. PHP

function SetKeywords ( $newkey words )


{
$this->keyWords = $newkeywords ;
(
function SetButtons ($newbuttons)
(
$this->buttons = $newbuttons ;
>
function Display ()

echo "<html>\n<head>\n" ;
$this -> DisplayTitle () ;
$this -> DisplayKeywordsf) ;
$this -> DisplayStyles () ;
echo "</head>\n<body>\n" ;
$this -> DisplayHeaderO;
$this -> DisplayMenu($this->buttons) ;
echo $ this->content ;
$this -> DisplayFooter() ;
echo "</body>\n</html>\n" ;

}
function DisplayTitle ()
<
echo "<title> $this->title </title>";
>
function DisplayKeywordsO
<
echo "<META name=\"keywords\" content=\"$this->keywords\">"
)

function DisplayStyles ()
<style>
hi (color: white; font-size :24pt; text-align: center;
font-family : arial , sans-serif)
.menu { color : white ; font-size :12pt; text-align : center;
font-family : arial , sans-serif ; font-weight : bold)
td (background: black)
p (color: black; font-size :12pt; text-align: justify ;
font-family : arial , sans-serif)
p. foot (color: white; font-size :9pt; text-align : center ,
f ont- family: arial, sans-serif ; font-weight: bold)
a: link, a: visited, a: active (color: white)
</style>

function DisplayHeaderO
<table width="100%" cellpadding = 12 cellspacing =0 border = 0>
<tr bgcolor = black>
<td align = leftximg src = "logo.gif"X/td>
<td>
<hl>TLA Consulting Pty Lt6X/hl>
</td>
<td align = rightximg src = "logo.gif"X/td>
</tr>
</table>
function DisplayMenu ($buttons)
(
echo "<table width = \"100%\" bgcolor = white"
." cellpadding = 4 cellspacing = 4>\n";
echo " <tr>\n";
//
$width = 100/count($buttons) ;

6. -
while (list($name, $url) = each (Sbuttons) )
{
$this -> DisplayButton($width, $name, $url,
!$this->IsORLCurrentPage($url) ) ;
)
echo " </tr>\n" ;
echo "</table>\n" ;
1
function IsURLCurrentPage ($url)
{
if (strpos ( $GLOBALS [ " SCRIPTJMME" ] , $url ) =f alse)
{
return false ;
)
else
{
return true;
}
}
function DisplayButton($width, $name, $url, $active = true)
(
if ($active)
{
echo "<td width = \"$width%\">
<a href = \"$url\">
<irag src = \"s-logo.gif\" alt = \"$name\" border = OX/a>
<a href = \"$url\"Xspan class4tienu>$name</spanX/aX/td>";

else

echo "<td width = \"$width%\">


<irag src = \"side-logo.gif\">
<span class=menu>$narae</spanX/td>" ;

}
}
function Display Footer ()
{

<table width = "100%" bgcolor = black cellpadding = 12 border = 0>


<tr>
<td>
<p class=foot>scopy; TLA Consulting Pty Ltd.</p>
<p class=foot>Please see our
<a href ="">legal information page</aX/p>
</td>
</tr>
</table>

, DisplayStylesQ,
DisplayHeaderQ DisplayFooter()
HTML- - PHP-. - (?>), HTML-,
- (<?) .
. DisplayButtonQ . , ,
.
.
IsURLCurrentPage() ,
Internet- . .

154

1. PHP

strposQ ,
Internet- , .
strpos( $GLOBALS["SCRIPT_NAME"], $url ) , , $url,
SCRIPT_NAME, false, .
, page.inc Display ().
, 6.2, TLA Consulting , . 5.2.
6.2 home.php
,

<?

require ( " . inc" ) ;


$homepage = new Page ( ) ;
$homepage -> SetContent ("<p>Welcome to the home of TLA Consulting.
Please take some time to get to know us.</p>
<pXWe specialize in serving your business needs
and hope to hear from you soon.</p>"

$homepage -> Display () ;

);

6.2 :
1. require page.inc, Page.
2. Page Shomepage.
3. Shomepage SetContentQ
HTML-, .
4. Shomepage DisplayQ, .
6.2, Page . .
, , page.inc pagel.inc
.
page.inc pageZ.inc.

,
Page, , .
TLA ,
.
, 6.3, ,
ServicesPage, Page. Srowlbuttons, , .
, -

6. - PHP
,
Display().

I JJ

6.3 services.php Page,


Display()

<?

require

("page.inc") ;

class ServicesPage extends Page


{
var $row2buttons = array ( "Re-engineering" => "reengineering.php" ,
"Standards Compliance" => "standards .php" ,
"Buzzword Compliance" => "buzzword. php" ,
"Mission Statements" => "mission. php"
function Display ()
{

);

echo "<html>\n<head>\n" ;
$this -> DisplayTitle() ;
$this -> DisplayKeywords () ;
$this -> DisplayStyles () ;
echo "</head>\n<body>\n";
$this -> DisplayHeaderO ;
$this -> DisplayMenu($this->buttons) ;
$this -> DisplayMenu($this->row2buttons) ;
echo $this->content;
$this -> DisplayFooterf) ;
echo "</body>\n</html>\n" ;

$services = new ServicesPage ();


$content ="<p>At TLA Consulting, we offer a number of services.
Perhaps the productivity of your employees would
improve if we re-engineered your business .
Maybe all your business needs is a fresh mission
statement, or a new batch of buzzwords.";
$services -> SetContent ($content) ;
$services -> DisplayO;
DisplayO ,

$this -> DisplayMenu($this->row2buttons) ;

DisplayMenu() .
ServicesPage,
, , Display().
. 6.2, .
.
PHP- . , , . , . ,
, ..
, , .

156

1. PHP

file Edit
Sack

6.2

^tew

FgvoWs

* '?;:>

louls fcjeip

Refresh

Home

Cieatch FBVOIMS

Histtiy

TLA Consulting Pty Ltd


0 Contact
Standards
ORe^ngineenng ComE|iance

0 Services

0 Site Map

1 0 Buzzword
Compliance

|U Mission
Statements

7^

At TLA Consulting, we offer a number of services. Perhaps the productivity of your


employees would improve if we re-engineered your business. Maybe all your business
needs is a fresh mission statement, or a new batch of buzzwords.

,
HTML- .
,
HTML-, ,
.


MySQL.
MySQL,
Web.


MySQL

7
8

9
10
11

Web-
Web-
MySQL
MySQL Web

MySQL


Web-

, ,

. , , 2

. :
, .

, .
, ,
, .
.
.
, , : "
?", "
?" " ?"
,
, . MySQL. ,
( ), :
.
Web- .
Web- .

7. Web-

:
8 ,
MySQL Web.
9 , , , .
10 MySQL, Web-.
11 MySQL, Web-.


, ,
.
. (
!), ,
.

,
. , .
- , ,
.
.
. 7.1 .
"Book-O-Rama".
7.1

"Book--Rama"
.

CUSTOMERS
Customer! D
1
2
3

Address
Name
25 Oak Street
Julie Smith
1/47 Haines Avenue
Alan Wong
Michelle Arthur 357 North Road

City
Airport West
Box Hill
Yarraville

Customers (), ,
, , .

. . ,
Customers . 7.1 , (CustomerlD) , .
.

.
.
.

160

2. MySQL

, . , .

. , , , . , Julie Smith Customers. , .


Julie . , , ,
Julie Smith, "25, Oak Street, Airport West".
.
.
(, ) Customer!D ( ).
, , , ,
. , .
, ,
.
.
. , , Julie "Julie Smith, of 25 Oak Street, Airport West", :
Name (), Address (), City (),
.
,
. . 7.2 . , . Orders () , . , ,
CustomerlD ( ). , , OrderlD 2 , CustomerlD 1.
, Customers, , CustomerlD 1 Julie Smith.
CUSTOMERS

7.2

Orders

Customers.

CustomerlD
1
2
3

Name
Julie Smith
Alan Wong
Michelle Arthur

Address

CustomerlD

Amount

City

25 Oak Street
Airport West
1/47 Haines Avenue Box Hill
357 North Road
Yarraville

ORDERS
OrderlD
1
2
3

3
1
2
4

Date
27.50
12.99
74.00
6.99

02-Apr-2000
1 5-Apr-2000
1 9-Apr-2000
01-May-2000

7. Web-

101

. CustomerlD Customers, , , Orders, .


, Julie Orders? .

.
- . , , . , , , , , ,
. , , "-" ( ) , :
Customers(CustomerID. Name, Address, City)
OrdersfOrderlD. CustomerlD, Amount, Date)
,
. , , , - .

. , Orders Customers Orders


Customers.
. . " ", " ", " ".
" " ,
. , Customers, - , " ".
Addresses Customers (
).
" " . Customer () Orders (). , , .
, CustomerlD Orders.
" ", ,
. ,
Books () Authors ().
, ,
. , , , Books,
Authors, Books_Authors.
6 . 216

162

2. MySQL

, , .

Web-
, , , . , , , "-" .
. , . "Book-O-Rama".

,
, ,
.
, ,
. :
, "",
, .
"Book-O-Rama" , . : ISBN, , .
, , , ,
: Customers (), Orders () Books (). . 7.3.
, , , . .
CUSTOMERS
CustomerlD

Name
1 Julie Smith
2 Alan Wong
3 Michelle Arthur

7.3

Customers,
Orders Books.

Address

City

25 Oak Street
1/47 Haines Avenue
357 North Road

Airport West
Box Hill
Yarraville

ORDERS
OrderlD

CustomerlD
1
2
3
4

Amount
3

2
4

Date
27.50
12.99
74.00
6.99

02-Apr-2000
15-Apr-2000
19-Apr-2000
01 -May-2000

BOOKS
ISBN
0-672-31687-8
0-672-31745-1
0-672-31509-2

Author

Title
Michael Morgan Java 2 for Professional Developers
Thomas Down Installing Debian GNU/Linux
Pruitt, et al.
Teach Yourself GIMP in 24 Hours

Price
34.99
24.99
24.99

7. Web-

163


: " Julie Smith Orders?"
Julie "Book-O-Rama" (
), . Orders
, . 7.4.
ORDERS
Customer! D Name
OrderlD Amount Date
Address
199.50 25-Apr-2000
1 Julie Smith 28 Oak Street
12
1 Julie Smith ' 28 Oak Street
43.00 29-Apr-2000
13
1 Julie Smith 28 Oak Street
14
15.99
30-Apr-2000
23.75 01-May-2000
1 Julie Smith 28 Oak Street
15

City
Airport West
Airport West
Airport West
Airport West

7,4 , ,
.

.
-, . Julie , ?
-, , .. ,
, . , , , . , .
: , .
Julie, , ,
, , .
, ,
.
,
.
, Julie , ; , , . ,
Julie. ,
, Julie Airport West, Airport. , .
, (, !!!) . ,
. ,
Julie , Orders. ,
Julie. - , , - ,
.
, ,
.

164

2. MySQL


, . , , . .
Orders ,
, . 7.5.
ORDERS
Books Ordered
OrderlD CustomerlD Amount Date
27.50 02-Apr-2000 0-672-31697-8
1
3
1
12.99
2
15-Apr-2000 0-672-31745-1, 0-672-31509-2
2
74.00
3
19-Apr-2000 0-672-31697-8
4
3
6.99 01-May-2000 0-672-31745-1, 0-672-31509-2, 0-672-31697-8
7,5 Books Ordered ( )
.

. ,
. , :
" 4. ?" , . , .
, ,
, . Orderjtems ( ) . 7.6.
ORDER ITEMS
7.6


OrderlD ISBN
1 0-672-31697-8
2 0-672-31745-1
2 0-672-31509-2
3 0-672-31697-8
4 0-672-31745-1
4 0-672-31509-2
4 0-672-31697-8

Quantity

1
2
1
1
1
2
1

Orders Books. ,
" " -- .. , - .


, .
(CustomerlD) (OrderlD), ,
. ,
ISBN. Order_Item , , ,
Order_Item ISBN

7. Web-

165

,
. Order_Items
Quantity ().

,
, ,
. (, . ,
"Book-O-Rama" ?) , , .


, ,
, , . . 7.7.
BOOKS
7.7

,

Books Review
(),

.

ISBN
0-672-31687-8
0-672-31745-1
0-672-31509-2

Author
Michael Morgan
Thomas Down
Pruitt, et al.

Title
Java 2 for Professional Developers
Installing Debian GNU/Linux
Teach Yourself GIMP in 24 Hours

Price
34.99
24.99
24.99

Review

BOOK_REVIEWS
ISBN

Review

Review Books.
. , (, , ).
. , .
, , : , , .
,
. , . 7.7.
Book_Reviews ( )
( ).
, . .
Book_Reviews CustomerlD.


, , , ,
:
, .
, " -

166

2. MySQL

" " ". ,


, . ,
.
, " " , , Orders Books. .

Web-
, ,
Web-
.

Web- . 7.8. : Web- Web-.


. Web- , .
, , .
, , .

7.8
/
Web-
Web-
.

Web- ,
, Web- , . 7.9. .

>

Web-
* 6

>

>

MySQL

7.9 Web- Web-, Web-cepeep,


.

Web- ,
. 7.9. "Book-O-Rama".
1. Web- HTTP- Web-.
, "Book-O-Rama" , (Laura Thomson), HTML-. results.php.
2. Web- results.php, .

7. Web-

10

3. . ( ). MySQL .
4. MySQL , , ,
.
5. , HTML, HTML- Web.
6. Web- HTML ,
.
, , ,
.
Web-, . , .
, .
, , .



. , (, (. J. Date)).
, , ,
Web-. .


MySQL. MySQL Web , -.

Web-


MySQL Web-.
:
.
.
MySQL.
.
MySQL.

"Book-O-Rama".
"Book-O-Rama":
CustomersfCustomerlD. Name, Address, City)
Orders(OrderID. CustomerlD, Amount, Date)
BooksdSBN. Author, Title, Price)
Order_Items(OrderID. ISBN. Quantity)
Book_Reviews(ISBN, Reviews)
He ,
, .
, MySQL. , :
1. MySQL Web-,
:

MySQL

mysql_install_db,

8. Web-

root

(anonymous)

MySQL .

\\

, ,
.
- , MySQL. , , .
2. MySQL , (, , Web-,
..).
,
, , ,
.
, , , , ,
. .
, ,
MySQL 3.22.27. MySQL .
.,
MySQL http://mysql.com.

MySQL
, MySQL (;), MySQL ,
. .
.
, , .
, . , MySQL . :
mysql> grant select
->

, MySQL . ,
, Enter.
, SQL- ,
. .

170 2. MySQL
MySQL
MySQL
:
> mysql -h hostname -u user-name -p

-,
.
mysql MySQL. , MySQL.
-h , MySQL.
, MySQL, ,
hostname, . , hostname
, MySQL.
- ,
. , , .
MySQL ,
root ,
. , root
, .
MySQL , ,
, .
- ,
. , , , .
root ,
. root .
. MySQL . . ,
.
:
Enter password:

****

( , , MySQL- - .
mysql.)
. , :
Welcome to the MySQL monitor.
Commands end with ; or \g.
Your MySQL connection id is 9 to server version: 3.22.34-shareware-debug
Type ' help' for help.
mysql>

, , mysql_install_db ( ),
root.

8. Web-

1/1

, .
MySQL , ..
.
, .
, . "
". , . ( ,
!)


MySQL . . "Book-O-Rama" books.


. MySQL:
mysql>

create

database

dbname;

dbname , .
"Book-0-Rama" books.
. :
Query OK, I row affected (0.06 sec)
, . ,
, .
MySQL, .


MySQL . root .
, , . , MySQL (, , UNIX NT). To
root. ,
MySQL, , root.
, .
Web- Web-.
: " ?" -- .

MySQL
MySQL
.
. .

1 /L

2. MySQL

MySQL, , , , .



.
, , .
:
( ) ,
.
MySQL , . ,
Web, , root. ,
, .

: GRANT
GRANT REVOKE , MySQL . :

, .
GRANT
. GRANT :
GRANT privileges [columns]
ON item
TO user_name [IDENTIFIED BY 'password' ]
[WITH GRANT OPTION]

, , .
.
, privileges (), , MySQL. .
columns () . ,
.
, .
item () , .
*.*, .
.
*.
dbname. *
(__.*), dbname.tablename (__._) dbname.tablename columns. -

8. Web-

\. / J

: , , .
- , tablename
" ".
userjiame ,
MySQL. , , . MySQL merjiame , , , , laura ( laura@localhost) laura@somewhere.com.
,
. , , , .
password , . .
, , . .

.
WITH GRANT OPTION, ,
.
,
mysql. : mysql.user, mysql.db,
mysql.tables_priv mysql.columns_priv;
. GRANT, . 11.


MySQL : , ; , , .
, , -
, .
, . mysql ,
, ,
.. ( 11.)

SQL . SQL . , .
. 8.1. Applies To ( ) , .
. ALTER
, , ,
. .
ALTER, , .

174

2. MySQL

8.1

SELECT

()
.

INSERT

UPDATE

DELETE

INDEX

ALTER


, ,

.

CREATE


. GRANT
,
(CREATE)
,
.

DROP

, . 8.1,
REFERENCES, , ,
GRANT, WITH GRANT OPTION.
. 8.2 , .
8.2

RELOAD


, , .

SHUTDOWN

MySQL.

PROCESS

FILE

).

,
, .
RELOAD, SHUTDOWN PROCESS.
FILE . , , ,
. , , MySQL ,
. .
, . 8.3.

8. Web-

1 /J

8.3

ALL

, . 8.1 8.2.
ALL ALL PRIVILEGES.

USAGE

He .
, ,
- . ,
- .

REVOKE
GRANT REVOKE.
GRANT:
REVOKE privileges
ON item
FROM user_name

[(columns)]

WITH GRANT OPTION, :


REVOKE GRANT OPTION
ON item
FROM user_name

GRANT REVOKE
:
mysql> grant all
-> on *
-> to fred identified by 'mnbl23'
-> with grant option;

Fred mnbl23
.
, :
mysql> revoke all
-> on *
-> from fred;

:
mysql> grant usage
-> on books.*
-> to sally identified by

'magic!23';

(Sally), -
:
mysql> grant select, insert, update, delete, index, alter, create, drop
-> on books.*
-> to sally;

, Sally.
, - ,
:

176

2. MySQL

mysql> revoke alter,

-> on books. *
-> from sally;

create,

drop

, ,
:
mysql> revoke all
-> on books. *
-> from sally;

Web
PHP- MySQL .
: ?

: SELECT, INSERT, DELETE UPDATE.
:
mysql> grant select, insert, delete, update
-> on books.*
-> to bookorama identified by 'bookorama!23';
He ! , , .
Web-, ,
, . _
( ..) Web-
MySQL ( ). . :
mysql> grant select, insert, update, delete, index, alter, create, drop
-> on books.*
-> to bookorama identified by 'bookoramal23';
.

root
MySQL , quit.
Web , .


, MySQL
, Web-.
, . , :
mysql> use dbname;
dbname .
use,
:
mysql dbname -h hostname -u username -p

8. Web-

ill

books:
mysql> use books;

MySQL :
Database changed

, MySQL :
ERROR 1046: No Database Selected


. SQL- CREATE TABLE. CREATE TABLE :
CREATE TABLE

tablename(columns)

tablename , , a columns .
, .
"Book-O-Rama":
CustomersCCustomerlD. Name, Address, City)
Orders(OrderID. CustomerlD, Amount, Date)
Books(ISBN, Author, Title, Price)
Order Items(OrderID. ISBN. Quantity)
Book_Reviews(ISBN, Reviews)
8.1 SQL- , , books .
CD-ROM chapterS/bookorama.sql.
SQL- :
>

mysql -h host -u bookorama books -p < bookorama.sql

,
, SQL- .
8.1 bookorama.sql - SQL- "Book-0-Rama"
create table customers
( customerid int unsigned not null auto_increment primary key,
name char (30) not null,
address char(40) not null,
city char(20) not null
);
create table orders
( orderid int unsigned not null auto_increment primary key,
customerid int unsigned not null,
amount float(6,2),
date date not null

178

2. MySQL

create table books


( isbn char(13) not null primary key,
author char(30),
title char(60),
price float(4,2)
>;
create table order_items
( orderid int unsigned not null,
isbn char (13) not null,
quantity tinyint unsigned,
primary key (orderid, isbn)
);
create table book_reviews
(
isbn char (13) not null primary key,
review text

CREATE TABLE. , , ,
. . .


NOT NULL , . NOT NULL , (NULL).
AUTO_INCREMENT MySQL, .
, MySQL .
,
. .
AUTO_INCREMENT .
PRIMARY KEY , . . MySQL
. , ,
customerid customers, AUTO_INCREMENT . , AUTOJNCREMENT.
PRIMARY KEY ,
. PRIMARY KEY order_items.
.
UNSIGNED ,
, .


:
create table customers
( customerid int unsigned not null auto_increment primary key,
name char(30) not null,
address char(40) not null,
city char(20) not null

8. Web-

1/9

.
customers, , . ,
customerid, , .
, ( int),
unsigned. , autojncrement, MySQL
.
.
char. . ,
, , 30 .
30 ,
. MySQL
.
varchar, ( ). , varchar ,
char .
, ,
.
, NOT NULL. , .
11.
CREATE .
orders:
create table orders
( orderid int unsigned not null auto_increment primary key,
customerid int unsigned not null,
amount float(6,2),
date date not null
);

amount ( float).

. ,
(6) .
date date.
, NOT NULL,
amount. ? , orders, orderjtems
. , NULL.
books :
create table books
(
isbn char(13) not null primary key,
author c h a r ( 3 0 ) ,
title c h a r ( 6 0 ) ,
price float(4,2)
);

, ISBN
. NULL,

10 U

2. MySQL

ISBN, , .
order_items :
create table order_items
( orderid int unsigned not null,
isbn char (13) not null,
quantity tinyint unsigned,
primary key

(orderid,

isbn)

);

TINYINT UNSIGNED;
0 255.
,
,
.
, book_reviews:
create table book_reviews
(
isbn char (13) not null primary key,
review text
>;

, . , , . , .
,
, . .

SHOW DESCRIBE
MySQL books.
, :
mysql> show tables;

MySQL :
I Tables in books

book_reviews
books
customers
order_i terns
orders
------------------- +
+
5 rows in set ( 0 . 0 6 sec)

show :
mysql>

show

databases ;

DESCRIBE
, , books:
mysql>

describe

books;

8. Web-

1 1

MySQL , :
+

I Field |

I
|
I
I
+
4

isbn
|
author |
title |
price |
+
rows in

| Null | Key | Default | Extra

char (13) |
I PRI |
char (30) | YES |
| NULL
char(60) | YES |
| NOLL
float(4,2) | YES |
| NULL
+
+
+
+
set (0.05 sec)

|
|
|
|

|
|
|
|
+

, , , .

MySQL
MySQL , , ( ) ( ).
MySQL , . , () ,
(, , UNIX), (Windows).
,
SQL- .
, , , , .
mysqladmin:
mysqladmin

variables

. 8.4.
ASCII(O)
ASCII(255) ( , , ).
8.4 MySQL
.

64

,
, /

64

,
, / .

64

255

.
MySQL 3.23.6
; , (
(~) ).
:
create

database

'create

database" ;

182

2. MySQL

MySQL ( 3.23.6) , .
,
. , 'create database', ,
. , ,
.


MySQL : , . . , 11.
. ,
, .
.
. , . / 255.
.


, . . D. ,
D 30, -2 (..

), .
UNSIGNED, 8.1.
ZEROFILL.
.
. 8.5. , , ( ).
8.5

()

TINYINT [ () ]

-127.. 128
0..255

SMALLINT [ () ]

-32768..32767
0..65535

MEDIUMINT [ () ]

-8388608..8388607
0.. 16777215

INT [ () ]

-23'..23
0..232-1

INTEGER [ () ]
BIGINT [ () ]

INT
3

-2..2* -1
0..2" - 1

8. Web-

183

. 8.6.
8.6

()
FLOAT (precision)

precision
()

FLOAT [ (, D) ]

1.175494351-38
3.402823466+38

DOUBLE [ (M, D) ]

+1.7976931348623157
+308
2.2250738585072014
-308




.

.
FLOAT(4),


.


.
FLOAT(8),


.

DOUBLE
PRECISION [ (, D) ]

DOUBLE [ (M, D) ].

REAL [ (, D) ]

DOUBLE [ (M, D) ].

DECIMAL [ (M[ , D])

M+2

,
char.
,
.
DECIMAL.

NUMERIC [ (M, D) ]


MySQL ,
. 8.7. ,
.
TIMESTAMP ,
, . .
8.7

DATE

1000-01-01
9999-12-31

. YYYY-MM-DD (--).

TIME

-838:59:59
838:59:59

. HH:MM:SS (::).
, ,
- .

DATETIME

1000-01-01
00:00:00
9999-12-31
23:59:59

.
YYYY-MM-DDHH:MM:SS (--::).

10 4

2. MySQL

TIMESTAMP [()]

1970-01-01
00:00:00

, .

(. . 8.8).
UNIX.

2037
YEAR [ (2|4) ]

70-69
(1970-2069)
1901-2155

. -
. , ,
.

8.8 TIMESTAMP.
8.8 TIMESTAMP

TIMESTAMP
TIMESTAMP (14)


YYYYMMDDHHMMSS
YYYYMMDDHHMMSS

TIMESTAMP (12)

YYMMDDHHMMSS

TIMESTAMP (10)

YYMMDDHHMM

TIMESTAMP (8)

YYYYMMDD

TIMESTAMP (6)

YYMMDD

TIMESTAMP (4)

YYMM

TIMESTAMP (2)

YY


. , . CHAR (
) VARCHAR ( ).
. CHAR , ,
VARCHAR . ( ,
MySQL CHAR
VARCHAR .) ,
, 11.
TEXT BLOB. . ,
. BLOB binary large object ( ) , .
TEXT BLOB , , TEXT
, a BLOB . , ,
11.
SET ENUM. SET , ,
. . 64 .

8. Web-

1 5

ENUM . SET,
NULL, 65535.
. 8.9, 8.10 8.11 . 8.9 .
8.9

[NATIONAL]
CHAR (M)
[BINARY]

1 255

[NATIONAL]
VARCHAR ()
[BINARY]

1 255

,
1 255. NATIONAL
,
, . MySQL
,
,
ANSI- SQL. BINARY
,
. (

.)
, ,
VARCHAR .

8.10 TEXT BLOB. TEXT


,
.
8.10 TEXT BLOB


( )

TINYBLOB

2M (.. 255)

BLOB

TINYTEXT

2M (.. 255)

TEXT

BLOB

2"-1 (.. 65535)

BLOB

TEXT

2"-1 (.. 65535)

MEDIUMBLOB

224-1 (.. 16777215)

BLOB

MEDIUMTEXT

22"-1 (.. 16777215)

TEXT

32

TEXT

LONGBLOB

2 -1 (.. 4294967295)

BLOB

LONGTEXT

232-1 (.. 4294967295)

TEXT

8.11 ENUM SET.

186

2. MySQL

8.11 ENUM SET

ENUM ('valuel', Value2',...)

65535



NULL.

SET ('value!', 'value2',...)

64



NULL.


MySQL, http://www.mysql.com/.


, , , , , , .
, , , .


MySQL

(SQL)
. Book-O-Rama
, , ,
.
, :
SQL?







, SQL
.
Book-O-Rama,
,
. 8.

SQL?
SQL Structured Query Language
( ). (). SQL
.
MySQL,
Oracle, PostgreSQL, Sybase, Microsoft SQL Server.

188

2. MySQL

SQL ANSI, MySQL


. , , - . MySQL .
(Data Definition Languages,
DDL), , (Data Manipulation Languages, DML), . SQL , . 8 , SQL ( DDL), . DDL
.
DML SQL ,
.


, - .
SQL INSERT.
, , , , , . - ,
. INSERT .
INSERT :
INSERT [INTO] table [(columnl, column.?, !, ...)] VALUES
(value!, value2, valued, . . .) ;

, Customers Book-O-Rama,
:
insert into customers values
(NULL, "Julie Smith", "25 Oak Street", "Airport West");

, table , , a values . . MySQL


. (
.) .
INSERT .
, . ,
, . :
insert into customers (name, city) values
("Melissa Jones", "Nar Nar Goon North");

, - .
, :
insert into customers
set name="Michael Archer",
address="12 Adderley Avenue",
city="Leeton";

9. MySQL

, , , , Julie Smith,
customerid (NULL),
. , customerid
Customers, .
, AUTOINCREMENT. , , MySQL
.
.
.
, .
, .
INSERT . , ,
CD-ROM, \chapter9\book_insert.sql.
9.1.
9.1. bookjnsert.sql SQL- Book-0-Rama
use books;
insert into customers values
(NULL, "Julie Smith", "25 Oak Street", "Airport West"),
(NULL, "Alan Wong", "1/47 Haines Avenue", "Box Hill"),
(NULL, "Michelle Arthur", "357 North Road", "Yarraville");
insert into
(NULL, 3,
(NULL, I,
(NULL, 2,
(NULL, 3,

orders
69.98,
49.99,
74.98,
24.99,

values
"02-Apr-2000"),
"15-Apr-2000"),
"19-Apr-2000"),
"Ol-May-2000");

insert into books values


("0-672-31697-8", "Michael Morgan", "Java 2 for Professional Developers",
34.99) ,
("0-672-31745-1", "Thomas Down", "Installing Debian GNU/Linux", 24.99),
("0-672-31509-2", "Pruitt, et al.", "Sams Teach Yourself GIMP in
24 Hours", 24.99),
("0-672-31769-9", "Thomas Schenk", "Caldera OpenLinux System
Administration Unleashed",
49.99);
insert
(1,
(2,
(3,
(3,
(4,

into order_items
"0-672-31697-8",
"0-672-31769-9",
"0-672-31769-9",
"0-672-31509-2",
"0-672-31745-1",

values
2)
1)
1)
1)
3)

insert into book_reviews values


("0-672-31697-8", "Morgan's book is clearly written and goes well beyond
most of the basic Java books out there.");

, MySQL :
>mysql -h host -u bookorama -p < book_insert. sql


MySQL SELECT.
, , . SELECT .

190

2. MySQL

:
SELECT items
FROM tables
[ WHERE condition ]
[ GROUP BY g-roup_type ]
[ HAVING wnere_dex"inition ]
[ ORDER BY order_type ]
[ LIMIT Iimit_criteria ] ;

.
, , . . ( , MySQL. .) name ()
city () Customers:
select name, city
from customers ;

9.1, :
| name

city

Julie Smith
Alan Nong
Michelle Arthur
Melissa Jones
Michael Archer
i. .

Airport West
Box Hill
Yarraville
Nar Nar Goon North
Lee ton

, name city Customers.


Customers.
, , select. , . *,
(
). , orderjtems,
:
select *
from order_iterns;

:
I orderid
t

isbn

| quantity

._ _>-

1
2
3
3
4

0-672-31697-8
0-672-31769-9
0-672-31769-9
0-672-31509-2
0-672-31745-1

2
1
1
1
3

9. MySQL

1,7 1


,
. where. ,
select *
from orders
where customerid = 3 ;

, customerid, 3.
:
I orderid | customerid | amount | date

4|

69.98
24.99

0000-00-00
0000-00-00

where .
customerid, 3. ,
, , , .
, MySQL . where . 9.1.
, , -, , MySQL.
9.1 WHERE

( )

customerid=3

amount>60.00

amount<60.00

amount>=60.00 ,

amount<=60.00

!=

quantity !=0

IS NOT NULL

IS NULL

BETWEEN

0 60.00

IN


("Carlton", "")

NOT IN


("Carlton", "")

192

2. MySQL

( )

LIKE

name like
("Fred %")

,
,
SQL

NOT LIKE

name not like


("Fred %")

REGEXP

name regexp

LIKE REGEXP. .
LIKE SQL.
% ( ) _ ( ) . MySQL . , 'Fred %' , 'fred '.
REGEXP .
MySQL POSIX. REGEXP
RLIKE, . POSIX
. 4.
, AND
OR. ,
select *
from orders
where customerid = 3 or customer = 4 ;


. , ,
, Customers Orders.
, ,
Order_Items.
,
. , 7.
SQL , . ,
. , , ,
Julie Smith,
Customers CustomerlD Julie, Orders
, CustomerlD.
,
SQL. MySQL
, .

9. MySQL

193


Julie Smith, :
select orders.orderid, orders.amount, orders.date
from customers, orders
where customers.name = 'Julie Smith'
and customers.customerid = orders.customerid;

:
I orderid | amount | date
|
+
+
+
+
I
2 | 49.99
10000-00-00 |

.
-, ,
.
, .
INNER JOIN CROSS JOIN.
.
: " .
, , ". ,
, Customers
Orders , .
. , ,
, .. , .
WHERE .
, , . :
customers.customerid = orders.customerid

MySQL
Customerid Customers CustomerlD Orders.
, (equi-join).
, . , customers.customerid
customerid Customers, a orders.customerid customerid
Orders.
, , , .

. table.column (.).
database.table.column (_..), ,
books.orders.customerid = other_db.orders.customerid
7 . 216

194

2. MySQL

,
. ,
. MySQL , . , ,
customers. name = 'Julie Smith'

name customers, , , -, .

. , .
, .
, , Java (,
, Java),
.
, , , ,
orderjtems Java. Customers
Orders, customerid, .
Orders Order_Items, orderid. Order_Items Books
, ISBN. , Java
, - .
, :
select customers . name
from customers, orders, order_i terns, books
where customers. customerid = orders .customerid
and orders . orderid = order_i terns .orderid
and order_i terns . isbn = books. isbn
and books. title like '% Java% ' ;

:
I name

I Michelle Arthur

, ,
,
. ,
, . ,
. ,
, , ,
.

MySQL .
, . ,

9. MySQL

II/J

, ,
, , .
MySQL , . , , .
:
select customers.customerid, customers.name, orders.orderid
from customers left join orders
on customers.customerid = orders.customerid;

SQL Customers
Orders. ;
ON SQL.
:
I customerid | name

Julie Smith
Alan Hong
Michelle Arthur
Michelle Arthur
Melissa Jones
Michael Archer

3
3

4
5

orderid

2
3
1

4
NOLL
NULL

, Melissa Jones Michael Archer orderid, orderid NULL.


, , , NULL
( , orderid),
NULL:
select customers.customerid/ customers.name
from customers left join orders
using (customerid)
where orders.orderid is null;

:
I customerid

| name
| Melissa Jones |
| Michael Archer |

, , . ON, , USING, . USING ,


, , .

196

2. MySQL

:
, . (aliase). , .
, , . , , ,
:
select .name
from customers as , orders as , order_iterns as oi, books as b
where .customerid = .customerid
and .orderid = oi.orderid
and oi.isbn = b.isbn
and b.title like '%Java%' ;

, , as, . , , , .
.
, .
, . , , ,
,
(Customers) :
select cl.name, cZ.name, cl.city
from customers as cl, customers as c2
where cl.city = c2.city
and cl. name ! = c2 . name

, Customers , cl 2, City. , cl.name !=


cZ.name, , .

. 9.2 .
, .
9.2 MySQL

.

WHERE.

.
CROSS JOIN
.

.
INNER JOIN. WHERE
.
WHERE.

9. MySQL

\ /

=
. SQL
WHERE.


NULL. SQL
LEFT JOIN.
.
RIGHT JOIN.


, , , ORDER BY SELECT. .
ORDER BY ,
SELECT. ,
select name, address
from customers
order by name ;

address

Alan Hong
Julie Smith
Melissa Jones
Michael Archer
Michelle Arthur

1/47 Haines Avenue


25 Oak Street

i
1

12 Adderley Avenue
357 North Road

!
1

( , , , .
( ), , .)
( z ). ASC ( ,
ascending):
select name, address
from customers
order by name asc;


DESC ( , descending):
select name, address
from customers
order by name desc;

. , (, 3
).

198

2. MySQL


, ,
- ,
. MySQL ,
.
,
.
. 9.3.
9.3 MySQL

AVG ()

COUNT ()

()
.
DISTINCT,
. COUNT I*)
.

MIN ()

()

STD ()

STDDEV ()
SUM ()

.
.

, . :
select avg (amount)
from orders;

:
avg (amount)
54.985002

, GROUP BY. , , , , :
select customerid, avg (amount)
from orders
group by customerid;

GROUP BY .
,
( , customerid)

9. MySQL
I

I
!
I

customerid |

I
2
3

I
|
|

avg(amount) |

_+

49.990002 |
74.980003 |
47.485002 |
+

, : GROUP BY
ANSI SQL, SELECT , GROUP BY. GROUP BY,
SELECT.
MySQL , ,
SELECT.
HAVING.
GROUP BY WHERE, .
, , ,
$50, :
select customerid, avg (amount)
from orders
group by customerid
having avg (amount) > 50;

, HAVING . :
I customerid | avg(amount) |
.+
+
+
2 |
74.980003 |


SELECT,
Web- LIMIT. , . : ,
, .
LIMIT:
select name
from customers
limit 2, 3;

: " , , 2". ,
.

.ZUU

2. MySQL

Web-. ,
,
10 .


, , . , . , UPDATE.
:
UPDATE tablename
SET columnl=expressionl, column2=expression2,
[WHERE condition]
[LIMIT number]

tablename,
column expression. WHERE UPDATE , LIMIT , .
.
10%, UPDATE WHERE:
update books
set price=price*l. 1;

, , , :
update customers
set address = '250 Olsens Road'
where customerid = 4;


, . ALTER
TABLE. :
ALTER TABLE tablename alteration

[,

alteration

...]

ANSI SQL ALTER TABLE , MySQL . .


, ALTER TABLE,
. 9.4.

9. MySQL

2\J\

9.4 ALTER TABLE

ADD [COLUMN] column_description


[FIRST | AFTER column ]

(
, ).
, column_description
, ,
CREATE.

ADD [COLUMN] (column_description,


column^description, ...)

ADD INDEX [index] (column, ...)

()
.

ADD PRIMARY KEY (column, ...)

()
.

ADD UNIQUE [index] (column, ...)


() .

ALTER [COLUMN] column


{SET DEFAULT value \ DROP DEFAULT}

CHANGE [COLUMN]
column new_column_description

column ,
.
,
column_description .

MODIFY [COLUMN] column_description

CHANGE.
, .

DROP [COLUMN] column

DROP PRIMARY KEY

( !).

DROP INDEX index

RENAME[AS] new_table_name

ALTER TABLE.
, : - "
", . ,
Customers 30 . , . , ,
45 .
alter table customers
modify name char(45) not null;

. , ,
Book-O-Rama , ,
. Orders :
alter table orders
add tax float(6,2) after amount;

- . ,
:
alter table
drop tax;

orders

2,02,

2. MySQL


. DELETE, :
DELETE FROM table
[WHERE condition] [LIMIT number]


DELETE FROM table;

, !
- WHERE. , - :
delete from customers
where customerid=5;

LIMIT .


.
DROP TABLE. :
DROP TABLE table;

,
.


!
- DROP DATABASE:
DROP DATABASE database;

, , . , , .


SQL,
MySQL. , MySQL , Web. , MySQL.
SQL, ,
ANSI SQL, :
http://www.ansi.org/

MySQL ANSI SQL Web MySQL:


http://www.mysql.com/


10 , Book-O-Rama Web.

10


MySQL
Web

.
2,
, ,
Web-. , MySQL
, Web-.
,
Book-O-Rama Web, . ,
, .
:
Web-

Web








PHP-MySQL
PHP-

204

2. MySQL

Web-
7 , Web- . :
1. Web- HTTP- Web-. , Book-O-Rama ,
, HTML-. results.php.
2. Web- results.php,
.
3. . ( ).
MySQL- .
4. MySQL ,
( ) .
5. ,
HTML.
HTML Web-.
6. Web- HTML ,
.
MySQL, , . . HTML. 10.1.
10.1 search.html Book-O-Rama
<html>
<head>
<title>Book-O-Rama Catalog Search</title>
</head>
<body>
<hl>Book-0-Rama Catalog Search</hl>
<form action="results.php" method="post">
Choose Search Type:<br>
<select name="searchtype">
<option value="author">Author
Coption value="title">Title
<option value="isbn">ISBN
</select>
<br>
Enter Search Term:<br>
<input name="searchterm" type=text>
<br>
<input type=submit value="Search">
</form>
</body>
</html>

, HTML-. . 10.1 .

10. MySQL Web

*:-.'

Foiwoni

'-Sig.;-.-R.,

2.0 J

; I 's, "Favor*
-3i":.:

wer/chapterl 0/seorch html

10.1

Book-O-Rama Catalog Search


,

,
ISBN.

Choose Search Type:


j Author jj]

Enter Search Term:

Search,
results.php. 10.2. ,
.
10.2 results.php - MySQL

<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<hl>Book-O-Rama Search Results</hl>
trim($searchterm);
if (!$searchtype ||

!$searchterm)

echo "You have not entered search details.


"try again. " ;
exit;

Please go back and

$searchtype = addslashes ($searchtype) ;


$searchterm = addslashes ($searchterm) ;
@ $db = mysql_pconnect("localhost" ,
if

"bookorama",

"bookorama");

(!$db)
echo "Error: Could not connect to database.
exit;

Please try again later.";

mysql_select_db( "books") ;
$query = "select * from books where " . $searchtype. " like
1
%" . $ search term. "% ' " ;
$result = mysql_query($query) ;
$num_results = mysql_num_rows ($result) ;
echo "<p>Number of books found:

".$num_results."</p>";

206

2. MySQL

for

($i=0;
$row
echo
echo
echo
echo
echo
echo
echo
echo
echo

$i

<$num_results;

$i++)

= mysql_fetch_array($result);
"<pXstrong>". ($i+l) ." . Title: " ;
htmlspecialchars( stripslashes($row["title"]));
"</strongXbr>Author: ";
htmlspecialchars (stripslashes($row["author"]));
"<br>ISBN: ";
htmlspecialchars (stripslashes($row["isbn" ] )) ;
"<br>Price: " ;
htmlspecialchars (stripslashes($row["price"] ));
"</p>";

</body>
</html>

10.2 .

10.2

Java

results.php
Web-.

Book-O-Rama Search Results


Number of books found: 1
1. Title: Java 2 for Professional Developers
Author: Michael Morgan
ISBN: 0-672-31697-8
Price: 34.99
4j


Web
, Web,
:
1. , .
2. .
3. .
4. .
5. .
results.php,
.

10. MySQL Web

20/

,
,
. trim(), Ssearchterm ( ).
trim($searchterm);

, . , , . , ,
, ,
, trim():
if
{

(!$searchtype
echo

| |

!$searchterm)

" Y o u have not entered


**try again. " ;

search details.

Please go back

and

exit;
}

, .
Ssearchtype ,
SELECT. , .
, . , Amazon , . , ,
.
, ,
. , , , 4 addslashesQ stripslashesQ. , , MySQL, addslashesQ, stripslashesQ.
addslashes():
$searchterm = addslashes

($searchterm);

, , stripslashesQ.
, . stripslashes()
. Web- ,
, , ,
. ,
addslashes(), ,
stripslashesQ. , .
htmlspecialcharsQ , HTML
. (&), "" (<), "" (>), ("), .
.


MySQL :
@ $db = mysql_pconnect("localhost", "bookorama", "bookorama");

2. MySQL

mysql_pconnect() :
int

mysql_pconnect (

[string host [.-port]


[:/socketpath]
[string user] , [string password] ) ;

(host), MySQL,
(user), , (password). , , , , .
( ), false.
,
. :
if

(!$db)
echo "Error: Could not connect to database. Please try again later.";
exit;

>

, , mysql_connect(). ,
mysql_connect() .
,
mysql_close().
, , mysql_close()
.
, . :
, .
mysql_pconnect(),
, , .
, . ,
.
CGI,
. ( , . , , .)
, MySQL, , . max_connections. (
Apache MaxClients)
, .
, . MaxClients Apache, httpd.conf.
max_connections MySQL my.conf.
,
, , , Apache. , , .

10. MySQL Web PHP


Apache 150 , a MySQL 100. . , Web- , ,
.


MySQL , , :
use

books ;

Web. - mysql_select_db():
mysql_select_db ("books")

:
int mysql_select_db (string database,

[int database_connection]

database.
, ( $db), , , . , , mysql_connect().


, mysql_query(). :
$query = "select * from books where ".$searchtype." like
'%".$searchterm."%'";
, (Ssearchterm),
, (Ssearchtype). , ,
, like, equal
.

, , MySQL,
, , MySQL.
:
$result = mysql_query

($query)

mysql_query() :
int

mysql_query(string

query,

[int

dataiase_connection]

);

, ; ( $db). ,
. , , mysql_connect().

2,1U

2. MySQL

, mysql_db_query().
:
int

mysql_db_query(string database,
[int database_connection]
)
;

string

query,

, , . - mysql_select_db()
mysql_query().
( ) false . ( , $result),
.


. , , , .
: mysql_numrows()
mysql_fetch_array().
mysql_numrows() , .
:
$num_results = mysql_num_rows($result)

, .
, :
for
{

($i=0;

$i <nuin_results;

$i++)

//

mysql_fetch_array().
, .
,
:
$row = mysql_fetch_array($result)

$row , :
echo "<br>ISBN: ";
echo stripslashes($row["isbn"] ) ;

, stripslashesQ , "" , .
. ,
mysql_fetch_row():
$row = mysql_fetch_row($result);

$row[0],
$row[l] ..

10. MySQL Web

2,1

mysql_fetch_object() :
$row

mysql_fetch_object($result);

$row->title,
$row->author ..
.
, mysql_result(). ( 0 1) , :
$row

mysql_result($result,

$i,

"title");

( "title"
"books.title") ( mysql_fetch_row()). He mysql_result()
.
- ,
mysql_result(), .


:
mysql_close( database_connection) ;

,
.


.
, .
SELECT INSERT.
, . . 10.3
HTML- .
HTML- 10.3.

http/Avebseiveiychapterl 0/newbook.html

10.3


,

Book- O-Rama.

Book-O-Rama - New Book


Entry
ISBN

0-672-31862-8

Author (Steve Litt


Title

ISamba Unleashed

Price $149.99

212

2. MySQL

10.3 newboolchtml HTML-


<html>
<head>
<title>Book-0-Rama - New Book Entry</title>
</head>
<body>
<hl>Book-O-Rama - New Book Entry</hl>
<form aotion="insert_book.php" method="post">
<table border=0>
<tr>
<td>ISBN</td>
<tdXinput type=text name=isbn maxlength=13 size=13xbrX/td>
</tr>
<tr>
<td>Author</td>
<td> <input type=text name=author maxlength=30 size=30Xbr></td>
</tr>
<tr>
<td>Title</td>
<td> <input type=text name=title maxlength=60 size=30Xbr></td>
</tr>
<tr>
<td>Price $</td>
<tdxinput type=text name=price maxlength=7 size=7XbrX/td>
</tr>
<tr>
<td colspan=2Xinput type=submit value="Register"X/td>
</tr>
</table>
</form>
</body>
</html>
insert_book.php, , ,
. 10.4.
10.4 insert_book.php
<html>
<head>
<title>Book-O-Rama Book Entry Results</title>
</head>
<body>
<hl>Book-O-Rama Book Entry Results</hl>
<?
if (!$isbn || !$author || !$title I I ! $price)
{
echo "You have not entered all the required details.<br>"
."Please go back and try again.";
exit;
}
$isbn
$author
$title
$price

= addslashes($isbn);
= addslashes($author);
= addslashes($title) ;
= doubleval($price);

@ $db = mysql_pconnect("localhost", "bookorama", "bookorama");

10. MySQL Web


if

2* 1 3

(!$db)

echo "Error:
later . " ;
exit;

Could not connect to database.

Please try again

mysql_select_db( "books") ;
$query = "insert into books values
( '" .$isbn." ' , ' " .$author.
' " .$title. " ' , ' " .$price. " ' )
$result = mysql_query ($query) ;
if ($result)
echo mysql_af f ected_rows ( ) . " book inserted into database.";
</body>
</html>

. 10.4.
insertjbook.php ,
. ,
addslashes ()
:
$isbn = addslashes ($isbn) ;
$author = addslashes ($author) ;
$title = addslashes ($title) ;
$price = doubleval ($price) ;

, .
doublevalQ, . doubleval() 1. , .
, mysql_pcoimect(), . INSERT.
$query = "insert into books values
(' ".$isbn." ', ' ".$author." ', ' ''.$title."
$result = mysql_query($query);

''.$price.

mysql_query().

!:AddreSB fa] hHD//wb':LT^r/i^ifiptef10/inEert_taDokphp

10.4


,
.

Book-O-Rama Book Entry


Results
1 book inserted into database,

2. MySQL

INSERT SELECT mysql_affected_rows():


echo mysql_affected_rows(). " book inserted into database.";

mysql_num_rows()
, SELECT. , , , INSERT, DELETE, UPDATE, mysql_affected_rows().
MySQL .
, .

PHP-MySQL
PHP-MySQL.


,
, mysql_free_result(). :
int mysql_free_result(int result);

:
mysql_free_result($result);

, . , .


MySQL PHP-
mysql_create_db(), mysql_drop_db().
:
int mysql_create_db(string database, [int database_connection] ) ;
int mysql_drop_db(string database, [int database_connection] ) ;

. ,
.
. true,
false.

PHP-
,
, Oracle, Microsoft SQL Server, mSQL
PostgreSQL.

. ,
, MySQL, .
, , , ODBC.

10. MySQL Web PHP

ODBC . ODBC , : ,
.
PHP-, ,
Metabase,
.


MySQL
MySQL.
ODBC :
http://www.whatis.com/odbc.htm

Metabase Web-:
http://phpclasses.upperdesign.com/browse.html/package/20



MySQL .

11

MySQL

MySQL: ,
.
, :

MySQL


, 8,
. GRANT. MySQL, , GRANT .
GRANT , mysql.
. ,
,
mysql.
, GRANT
MySQL 3.22.11.
mysql , :
use mysql;

11, MySQL

2,1 /

, :
show

tables;

.
:
Tables in mysql
columns_priv
db

host
tables_priv
user

.
. , , , . : , , , , ,
, .
user () , MySQL .
db host , . tablesjriv ,
a columns_priv .

user
,
: MySQL
- , .. , .
describe user; .
user . 11.1.
11.1 user mysql

Host

char(60)

User

char(16)

Password

char(16)

Select_priv

enumCN'/Y1)

lnsert_priv

enum('NYY')

Update_priv

enum('N','Y')

Delete_priv

enum('NYY')

Create_priv

enum('NYY')

Drop_priv

enum('NYY')

218

2. MySQL

Reload_priv

enum('N','Y')

Shutdown_priv

enum('N','Y')

Process_priv

enum('N','Y')

File_priv

enum('N','Y')

Grant_priv

enum('N','Y')

References_priv

enum('N','Y')

lndex_priv

enum('N','Y')

Alter_priv

enum('N','Y')

, . , , .
( ,
) ,
GRANT (. 8). , select_priv
SELECT.
,
Y. , , N.
, user, , ..
( mysql).
, Y, , N. ,
.

db host
db host.
db ,
.
.
host db. , , db
. ,
host, .
db host , , . 11.2 11.3.
11.2 db mysql

Hosf

char(60)

Db

char(64)

User

char(16)

11. MySQL

Select_priv

enum('N','Y')

lnsert_priv

enum('N','Y')

Update_priv

enum('N','Y')

Delete_priv

enumCN'.'Y')

Create_priv

enum('N','Y')

Drop_priv

enum('N','Y')

Grant_priv

enum('N','Y')

References_priv

enum('N','Y')

lndex_priv

enum('N','Y')

Alter_priv

enum('N','Y')

2,1 j/

11.3 host mysql

Host

char(60)

Db

char(64)

Select_priv

enum('N','Y')

lnsert_priv

enum('N','Y')

Update_priv

enum('N','Y')

Delete_priv

enum('N','Y')

Create_priv

enum('N','Y')

Drop_priv

enum('N','Y')

Gran+_priv

enum('N','Y')

References_priv

enum('NYY')

lndex_priv

enum('N','Y')

Alter_priv

enum ('N'.'Y')

tables_priv columns_priv
, ,
. db ,

.
user,
db host. tables_priv columns_priv . 11.4 11.5 .

2<2,\J

2, MySQL

11.4 tables_priv mysql

Host

char(60)

Db

char(64)

User

char(16)

Table_name

char(64)

Grantor

char(77)

Timestamp

timestamp(14)

Table_priv

set('Select', 'Insert', 'Update', 'Delete', 'Create', 'Drop', 'Grant',


'References', 'Index', 'Alter')

Column_priv

set('Select', 'Insert', 'Update', 'References')

11.5 columns_priv mysql

Host

char(60)

Db

char(60)

User

char(16)

Table_name

char(60)

Column_name

char(59)

Timestamp

timestamp(14)

Column_priv

set('Select', 'Insert', 'Update', 'References')

Grantor tables_priv ,
. Timestamp
.

: MySQL
MySQL ,
, .
1. . MySQL ,
, user, . , .
, , .
%. , .. %
" ". ,
, %.tangledweb.com. ,
.tangledweb.com.au. , , . , , , .
2. .
, MySQL ,
. -

11. MySQL

2,2,1

( user), , db host.
, MySQL priv_table ,
, columns_priv.

: ?
GRANT REVOKE MySQL .
, , ,
. ,
MySQL , .
, , . :
FLUSH

PRIVILEGES;

MySQL ( ). .
:
mysqladmin

flush-privileges

mysqladmin reload

.
;
use, .

MySQL
,
MySQL Web-. , .

MySQL
UNIX- , MySQL (mysqld) ,
MySQL . ; Web- Apache. (
, " " ,
.)
. , ( ) MySQL. mysql mysql.
, , MySQL .
,
3306. , MySQL .

222

2. MySQL

, (, )
, ,
. , ,
, . .
, , , , .
:
1. mysql.server UNIX. , ,
.
2. , . , , , dbconnect.php,
.
Web- .
, a.inc Web-, , Web-,
PHP-, Web-.
. MySQL , Web- Web- . () ,
MySQL- PASSWORDQ MD5(). ,
(INSERT) , SELECT (
), " , , .
,
.


. , MySQL
? , . , .
, PROCESS, FILE,
SHUTDOWN RELOAD , ,
. PROCESS , ,
, . FILE (, ,
/etc/password UNIX).
GRANT , .

, . jane@localhost, , jane , , jane,

11. MySQL

2,2.3

.
.
, host IP-
. , DNS. , MySQL skip-nameresolve, IP- .
mysqld secure.
IP-, . (
, 3.22.)
, ,
mysqladmin Web-.
, .

Web

MySQL Web ,
.
, Web-. ,
DROP, ALTER CREATE. SELECT , a INSERT . .
|
|
l
PHP- addslashesl) stripslashesl)
. . , - MySQL
. , doublevaK)
, . , addslashesl), .
, . HTML-, - URL, . ,
.
,
, ,
, SSL (Secure Sockets Layer ). SSL .


, ,
, SHOW DESCRIBE.

SHOW

SHOW

TABLES;

, .

.Z.ZT-

2. MySQL

show

databases;

. SHOW TABLES
:
show tables

from books;

SHOW TABLES , .
, :
show columns from orders from books;

, SHOW COLUMNS
. table.column:
show columns from books.orders ;

SHOW .
show grants for bookorama;

11.1 SHOW GRANTS.

GRANT
, , , .

SHOW GRANTS MySQL 3.23.4; , .

SHOW. . 11.6.
11.6 SHOW

SHOW DATABASES
[LIKE _ ]
SHOW TABLES
[FROM _ ]
[LIKE ]

,
_
,
,
_.
.

SHOW COLUMNS FROM


[FROM _ ]
, .
[LIKE ]
.
SHOW COLUMNS SHOW FIELDS.

11. MySQL

2,25

SHOW INDEX FROM


[FROM _ ]



, .
SHOW KEYS.

SHOW STATUS
[LIKE _]

,
, .
,
LIKE
, , Thread%'
'Threads_cached', 'Threads_connected', Threads_running'.

SHOW VARIABLES
[LIKE _]


MySQL, , . LIKE

, SHOW STATUS.

SHOW [FULL] PROCESSLIST

,
.. .
,
,
PROCESS, ,
,
.
. FULL
.

SHOW TABLE STATUS


[FROM 6_ ]
[LIKE _]

,
, , .

.
.

SHOW GRANTS
FOR

GRANT,

.

DESCRIBE
SHOW COLUMNS DESCRIBE, DESCRIBE Oracle. :
DESCRIBE [];

, . .

EXPLAIN
EXPLAIN . :
EXPLAIN ;

, DESCRIBE
SHOW COLUMNS FROM .
, EXPLAIN ,
, MySQL SELECT.
SELECT explain.
8 . 216

226

2. MySQL

EXPLAIN ,
, . , EXPLAIN , , ,
.
MySQL, , ,
. , EXPLAIN .
, Book-O-Rama. . 11.2.
explain
select customers.name
from customers, orders, order_iterns, books
where customers.customerid = orders.customerid
and orders.orderid = order_iterns.orderid
and order_iterns.isbn = books.isbn
and books.title like ' % J a v a % ' ;

| orders
| ALL
| ord*r_it.M 1 r.t

| PRIMARY
| PRIMARY

| HULL

NULL | NOLL

|rowi | Extra

11.2 EXPLAIN.

, . .
, table, ,
. ,
. orders, order_iteras, customers books. (
.)
type , .
, , . 11.7.
, .
, , .
11.7 , EXPLAIN

const system

. ,
. system ,
, const.

eq_ref

ref


. ,
, UNIQUE
.

. ,
,
,
UNIQUE .

11. MySQL

2,2* I

range


,
.

index

ALL

eq_ref (books),
ref (order_items), ALL, .. .
rows .
,
. , , . ,
(. 9). , , , .. , MySQL
, .
, , .
, , . .
possible_keys , , , , ,
MySQL .
.
key , MySQL, NULL,
. ,
orders customers, .
, .
key_len , .
, . , , . , (order_items books), .
ref ,
.
, extra ,
. . 11.8.
11.8 extra,
explain.

Not exists
( )

LEFT JOIN

Range checked for


each record
(
)
Using filesort
(
)


, .

( , ),

2,2,0

2. MySQL

Using index
,
( ) .. .
Using temporary
(
)
WHERE used

"
,
WHERE.

,
explain.
-, , , .
. ,
. .
-, , myisamchk
. :
>myisamchk

analyze ____81/

, ,
:
>myisamchk

--analyze

____1/*. MYI

(
. 11.3):
>myisamchk

--analyze

-____11/*/* .MYI

1
!
1
1

key_len
books

| ALL

PRIMARY

| NULL
1 PRIMARY
j

PRIMARY

HULL
17
4

ref

| NULL
| NOLL
| ord.r..cu.to..rid

rows

|
|

Extra

where used

11.3 EXPLAIN myisamchk.

, .
(all) (books), . , eq_ref, index. MySQL order_items (17 4 ).
, ,
. , . , , - . , MySQL
FROM .
-, . , . , , . ,
.

11. MySQL

2,2*7


, possible_keys EXPLAIN NULL, .
WHERE ,
, ALTER TABLES, :
ALTER TABLE ADD INDEX

();


, ,
MySQL.


, . - ,
. . , .
, (,
VARCHAR, TEXT, BLOB). , .


, EXPLAIN, , . , . , .


,
.
. :
OPTIMIZE TABLE _;

:
>myisamchk -r
.
myisamchk , , :
>myisamchk --sort-index sort-records! ____1/*/*.MYI

2. MySQL


. ;
, . ,
, EXPLAIN, .

,
, , ,
, .
INSERT.


Web- . , .


, . Web- MySQL
. :
http://www.mysql.com


, ,
. , :
CREATE TABLE TYPE=!Tiui . . .

:
MylSAM. .
ISAM, Indexed Sequential Access Method (- ), .
HEAP. , .
HEAP , .
HEAP . CREATE TABLE MAX_ROWS,
"" . BLOB, TEXT
AUTO INCREMENT.
BDB. , .. COMMIT
ROLLBACK. MylSAM
Berkely DB.
MySQL 3.23.21,
Web- MySQL.
,
.

11. MySQL


MySQL, , LOAD DATA INFILE.
. .
, :
LOAD DATA INFILE "newbooks.txt" INTO TABLE books;

newbooks.txt books.
,
(\). (\).
LOAD
MySQL.
LOAD DATA INFILE, FILE, .


MySQL
, Web MySQL .
, Web, MySQL, Web-
MySQL :
http://www.mysql.com


MySQL. 12 Web-,
.

12
13

14

MySQL

15


MySQL

12

, , , .
.
, :
,

Web-


Web-
,
, , .
,
Web-; ,
.

Internet.
.
, .
Web- . .

3.

Web-
Web- , , :

Web- .
.
, Web-:
.


90- Web-
.
Web-, Web
.
Web
. , .
Web- ,
, .
, , , . :


? ,
, , .
. ,
,
, .

12.

.235


" Internet , " '.
("") Internet , Web- .
Web- .
, ,
, . , , , . ; ,
.
,
, ; ,

.


Web, , ,
. , , , , Web-. ,
, ,
. , , .
, Web-,
, . , fred.smith@company.com ,
? , sales@company.com,
, .
, .


, ,
, . , .
, .
- , .
.

, Internet " " .


(Peter Steiner),
"-" 5 1993 .

236

3.


Web- .
. , ,
,
.
, ,

, ,
. Web- , .
:
. Web- . ,
, - . - , . ,
: Analog ( http://
www.statslab.cam.ac.uk/~sretl/analog) Webalizer (http://www.mrunix.net/webalizer).

Summary (http://www.summary.net).
.
.
. , , Web-. , .
. Web- ,
. , ,
- .
.
. ,
.
,
,
,
. , ,
.
, , . , .

12.

2,3 /

. , . , . , ,
.


,
, .
, .
, , .
, .
, . , , -!
Web . ,
, , , ,
. ,
, , , , , ,
.
, Internet , , ,
, , ,
.
, , . , .
,
; ,
, ,
, .
. ,
, ,
. . , CD- , .
.
: Internet. , -

Use of Internet by Householders, , 2000 . ( 8147.0), .

2, J

3.
2

. , Internet .
,
, , , . , Internet , .
.
, , .
, .
, ,
. ,
..
; , .
, :

,
, ,
, .
. , Web- , , , , , . ,
, , , .
Web , ,
. , . , . Web- . , , .
, ,
, .
Web- , . , , . , .

Web- , ? . ,
, . -

12.

23;/

, , , "".
, :
?
? ? ? ,
, . .
?
, ,
, ,
" ", Web- , , .
Web-.
, ?
? ?
, , , . .
, . ,
.
?
Web-,
, . ,
SSL
(Secure Sockets Layer ); . .


, ,
, . , Web- .
; , :
Web- , , . ,
, , .
. .
;
.
.
, -

240

3.

, , . 3
, , ,
1-Click.
Web-.
. , . ,
,
"" , .

Web-
.
- , , , .
,
. ,
Microsoft Windows Web-
Microsoft Internet Explorer Netscape Navigator,
Apple Mac Netscape Navigator, Linux Netscape Navigator.
Lynx.
, Web-.


Web, ,
.
, , ,
.
. , ;
.

, , , , CD-ROM.
Internet.

US Patent and Trademark Office Patent Number 5,960,411. Method and system for placing a
purchase order via communications network (
5,960,411. .)

12.

, Internet, Web-, ,
.
, Web-,
, .
,
Web . , . ,
,
.
, , . , ,
, ; Web , .
. .
, .


Web,
. , -
UPS (www.ups.com) Fedex (www.fedex.com) , , .
, .
. , ,
, . , ,

. ,
.


Internet , , , .
Web- . , , ,
Web-,
, , .
Web, , ( ) .. : .
. Egghead.com.

242

3.

.
,
,
70 . ,
: , , , Internet.
. , ,
, , . .


, , ,
. , , , :

. ,
.
. "" , , ,
.
:

,
.
, .

12.

, - ,
.
; , .


,
. .
, .
Amazon.com ( ,
) . 2000 . 99 . boo.com, 120 .
, , .


, ,
Web, . ,
, , .
.

, ,

Internet , , , , . ( )
, .

. ,
. .


, .
. , , . Internet .
.

.244

3.

, , . .

. , .
.
, ; - ; .


( ) .
, , . .
. .


. ,
.
,
, . , .
,
.


, Internet
. :
Internet.
.
, Web- .
. ,
. , Web,
.


:
, .

. , , ,
,
,
Web-,
, .
:
?


,







Web-



246

3.

?
, , . .
,
, . , ,
, .
, -, . , . ?
, - , . ,
, , ,
,
. .
, .
,
. , , ,
.
,
, .


? ?

12. .
Web-, :

13.

,
, . , , , .
, , , , .
, Web- , . Web-
.
, Web-
. Web- , ,
, .
,
. , , , , ,
, Web- .
, , ,
, , ,
, .

Web-. , , . , , . , , .
, ?1 ,
, ,
Linux Windows NT, , .
(authentication)
. , , , . ,
(digital
signatures). .
CD Universe
, . , 1999 .. , Maxus, CD Universe, , 300000
, . 100000 , . ,
, Maxus .
1

, , scp (secure copy ).

248

3.

13.1


Internet

Internet

.
TCP/IP , - Internet,
. TCP/IP , , . ,
, . 13.1.
.
,
, traceroute UNIX- tracert
Windows-. , . . ,
, 20 .
, , .

. Web- Socket Secure
Layer (SSL), Netscape,
, Web- .
,
,
, .


, .
,
, , ?
, .
, - . , -, , .

13.

24,7

, - . , ,
.
, . . , .
. , .
RAID . ,
.
, . . , , , , , . ,
, ,
. , . ,
- , .


, ,
. , -
?
, ?

. "" " " - . , , " "
.
, , (signature). ,
, , , .
,
.
, , . . ,
, .
, Windows 98 Windows 95
.
. - , , ,

2, J\J

3.

? , , , . . , . ,
,
, , "".
Tripwire
,
, . . - http://www.tripwire.com



(Denial of Service, DoS) , -
. , .
2000 .
(Distributed Denial of Service, DDoS) Web-.
Yahoo!, eBay, Amazon, E-Trade
Buycom. , . - DoS
.
, , .
, , DoS. ,
, (reverse spamming)
. (reverse
spamming) , -
(spam), . ,
, .
,
DoS .
, - .
, .
, ""
.
, DoS . , , , DDoS. , ,
, , ICMP. ,
, . , DDoS.

13.

2, J 1

, , ,
.


, , ,
, . , Web- , ,
.
.
,
, , .
,
. , , , .


,
, .
, , , , ,
, .
, ,
.

,
.
, , . - . , ,
. , , , ,
.
, . , , - , ,
. ,
.
, ,
, .

2*3 2,

3.


. , Web.
,

.
, , ,
. , .
, , .
,
. , . , . , ,
. , .


, -
(repudiation). . , Web-, .
, -
, , .

. , , ,

, . .
, .
, (digital certificate of authentication) .
. , , Corp Pty Ltd . , * ,
. , .
, , . ,
, , .
,
, VeriSign (http://www.verisign.com) Thawte (http://

13.

www.thawte.com), .
, ? ,
,
, .
1997 ., , VISA , (Secure
Electronic Transaction, SET). SET
, . ,
Internet-.
, SET
, SET-co . , SET- . ,
.
" " (digital wallet), - , -
, -
.

,
,
Web , . Web ,
. Web-, Internet,
.
,
, . - , , . , .
, ,
. ,
, ,
, . . , , , , , ,
. , , Web. , ,
.

254

3.

,
.
, .
, ,
.


, :

, ,

. ;
. .
, . . ,
, .


, -
, . , , , , .
, ,
, , , , (-). Web .
, , , .
, , Web.
, , . ,

.
. .
, , -

13.

, . , .
.
. , 50% , .
, , ,
. . ,
. ,
,
25% . , .
,
. ,
,
.
,
, , ": Fred : rover", .
,
, , , .
.
(sniffers),
-. .
, , . ,
, , ,
, .


Web- . Web- ,
.
,
, . 13.2.

13.2.
Web-




Web-cepeepe.

256

3.

Web- Apache Microsoft IIS . MySQL . MySQL ,


.
.
14.


, .
, , (plain) ,
, . , , , . . 13.3
- .
, Enigma .
. .

13.3.
, .

, . 13.2
, , Apache. (
.) . password.
aWDuA3X3hmc2. , .
. .
.
.
, . . . 13.4 .
4000 ,
.
, 70- , 90-
.
, , , , - Web.

13.

13.4.
, .
.

. , , DES, , . , , RSA,
.


(private key encryption) ,
.
. , . . 13.4,
( ) ( ) .
DES (Data Encryption
Standard). , IBM 70- ,
.
70- , DES 1998 .
RC2, RC4, RC5,
2
DES (triple DES) IDEA. DES- .
, DES, ,
. , , .
, -
. , ?
, , 1976 ., (Diffie) (Hellman)
.

, DES DES.
, DES, , DES .
9 . 216

2, J

3.


(public key encryption) . . 13.5, , .

>t

>f

13.5.
.

, , ,
. ,
, .
, .
RSA,
(Rivest), (Shamir) (Adelman)
(MIT) 1978 . RSA , 2000 .

, ,
. , . . ,
.
, .


(digital signature) ,
. . ,
, .
, ,
, , ,
.
. , , , .

13.

, , . ,
, .
,
, -.
- , -,
. , .
, , ..
, . ,
, .
- MD5 SHA.
- , .
, , , , .
, , - ,
. , .
.
.
- -, .
- , ,
.


, ,
.
- , .

. ,
. ,
, .
,
, , .
, , . , , .
(Certifying Authority, CA).
, . Verisign (http://www.verisign.com/)
Thawte (http://www.thawte.com/). VeriSign Thawte -

260

3.

, . , Equifax
Secure (www.equifaxsecure.com) .
, , . , .
, -, . , ,
, .
. , , ,
. , , , .
. 13.6 , Internet Explorer
. , www.equifaxsecure.com , Equifax Secure E-Business. , ,
, Thawte Server.

. ,
, Web-
SSL-
. Web-, SSL-, Web-.

Web-
Web- Secure Socket Layer Apache, Microsoft IIS Web-. Apache
Unix, , ,
, , IIS. , Apache Windows NT.

} Thawte SaveiCA
S'l EqufaH Secure E-6iisir>gss Cft

13.6.

WWY/. equifaxsecure. com

,

.
I Thi; certificate i; OK.

13.

SSL IIS, IIS,


. SSL
Apache : Apache, Mod_SSL OpenSSL.
, Stronghold. Stronghold
1000 . Apache
, SSL. , Unix .

Web- Apache IIS. SSL,
, ,
. SSL
.
, , ,
.
(Certificate Signing Request,
CSR). .
Web- . Stronghold IIS
, Apache .
, .
. CSR
:
----- BEGIN NEW CERTIFICATE REQUEST ----MIIBuwIBAAKBgQCLnlXX8faMHhtzStp9wY6BVTPuEU9bpMmhrb6vgaNZy4dTe6VS
84p7wGepq5CQjfOL4Hjda+gl2xzto8uxBkCD098Xg9q86CY45HZk+q6GyGOLZSOD
8cQHwhloUP65s5Tz018OFBzpI3bHxfO6aYelWYziDiFKplBrUdua+pK4SQIVAPLH
SV9FSz8Z7IHOglZr5H82oQOlAoGAWSPWyfVXPAF8h2GDb+cf97k44VkHZ+Rxpe8G
ghlfBn9L3ESWUZNOJMfDLlny7dStYU98VTVNekidYuaBsvyEkFrny7NCUmiuaSnX
4UjtFDkNhX9j5YbCRGLmsc865AT54KRu3102/dKHLo6NgFPirijHy99HJ4LRY9Z9
HkXVzswCgYBwBFH2QfK88C6JKW3ah+6cHQ4Deoiltxi627WN5HcQLwkPGn+WtYSZ
jG5tw4tqqogmJ+IP2F/5G6FI2DQP7QDvKNeAU8jXcuijuWo27S2sbhQtXgZRTZvO
jGn89BCOmIHgHQMkI7vz35mxlSkk3VNq3ehwhGCvJlvoeiv2J8X2lQIVAOTRp7zp
En7QlXnXwls7xXbbuKPO
----- END NEW CERTIFICATE REQUEST -----

CSR, , , , , , , .
, Web-, .
, CSR.

262

3.


.
: ,
, NT, a
, su ( Unix, , , root).
() .
, , . .

, , . , , "" .
.
. , ,
. Unix . , , , , .
Windows NT, .
,
, .

(firewall) ,
. ,
, .
. , . , .

. , ,
-
.
,
, , .
, . , . , ,
.

13.

2,\) J

, , ,
. ,
.


. , - , ,
.
Web-
, . ,
. ,
. ,
, , , , .

RAID (Redundant Array of Inexpensive Disks ), .
. , , - RAID-, .
,
. , , , .
.
, ,
MySQL.


,
HTML, PHP, , .
AMANDA (Advanced Maryland Automated Network Disk Archiver).
.
Unix Windows-
SAMBA. AMABDA http://www.amanda.org

MySQL
. - ,
.
MySQL
11.

264

3.


, , .
, ( , ), .
. ,
, . ,
, . - .
,
.
(halon). , , , .
http://epa.gov/ozone/
title6/snap.
. . ,
(, UPS, Uninterruptible Power Supply). ,
10 ,
300 .
. , , .
, , Internet, .
,
Internet-. , Internet , ,
.
, . , ,
, Internet ,
, .


14 . , , MySQL.

14


MySQL

, MySQL
.
:





.htaccess Apache
IIS

mod_auth_mysql


Web , , . , .
,
, . Web- , , .
, .
Internet
IP-. IP-
. , ,
.

266

3.

, . , Internet IP-. , Internet-, IP- . ,


,
, , , IP-.
Web, , , .
, .
Web- .
, New York Times (http://www.nj1imes.com) , ,
, . Slashdot (http://www.slashdot.org) ,
(nickname). .
,
.
, - . , , , ,
, cookie- . .
, -
. , , . , - , , .
13, . Web .
.
, , .

. , 14.1, .
, HTML-
(.
. 14.1).

Please Log In
This page is secret.
U sent aide j
i Password:.1

14.1. HTML-

.

14. MySQL

v :

.^;!
- <a m xJH :"!&
'Hem' Sozrt t,.,'.'-/ limit.* Ml '

Back

Home

'

Search

j~j lip.//webseiwr/ctiapterl 4/s.pml php

Go Away!
You are nc-t authorized to view this resource.

'

Here it is!
I bet you are gtad you can see this secret page.

Jii
14.2.
,
.
.

14.3.
,
.

, , (. . 14.2).
, . . 14.3.
, . 14.1, 14.2
14.3, 14.1
14.1 secret.php - HTML-

if(!isset($name)&&lisset($password))
//
<hl>Flease Log In</hl>
This page is secret.
<form method = post action = "secret.php">
<table border = 1>
<tr>
<th> Username </th>
<td> <input type = text name = name> </td>
</tr>
<tr>
<th> Password </th>
<td> -cinput type = password name = passwbrd> </td>
</tr>
<tr>
<td colspan =2 align = center>
<input type = submit value = "Log In">
</td>
</tr>
</table>
</form>
else if($name=="user"SS$password=="pass")

//
echo "<hl>Here it is!</hl>";
echo "I bet you are glad you can see this secret page.",

268

3.
else

//
echo "<h!X3o Away!</hl>";
echo "You are not authorized to view this resource.";

, 14.1, ,
, .
:




.


, ,
. . , , . ,
.
, .

, , .
, , , . :
100 ,
.

, . , .
14.2.
14.2. secretdb.php MySQL
.
_
<?

if ( "isset ($name) S&'isset ($password) )


{
//

?>
<hl>Please Log In</hl>
This page is secret.

14. MySQL
<form method = post action = "secretdb.php">
<table border = 1>
<tr>
<th> Username </th>
<td> <input type = text name = name> </td>
</tr>
<tr>
<th> Password </th>
<td> <input type = password name = password> </td>
</tr>
<tr>
<td colspan =2 align = center>
<input type = submit value = "Log In">
</td>
</tr>
</table>
</form>
else
{
// MySQL
$mysql = mysql_connect ( 'localhost', 'webauth' , 'webauth' )
if ( !$mysql)
{
echo 'Cannot connect to database. ' ;
exit;
}
//
$mysql = mysql_select_db ( ' auth ' ) ;
if (!$mysql)
(
echo 'Cannot select database.';
exit;
}
// , ,
//
$query = "select count (*) from auth where
name = ' $name ' and
pass = ' $password' " ;
$result = mysql_query ( $query ) ;
if (!$result)
{
echo 'Cannot run query.';
exit;
}
$count = mysql_result ( $result, 0, 0 );
if ( $count > 0 )
{
//
echo "<hl>Here it is !</hl>" ;
echo "I bet you are glad you can see this secret page.";
}
else
{
//
echo "<hl>Go Away ! </hl>" ;
echo "You are not authorized to view this resource.";

270

3.

, MySQL
root 14.3 .
14.3. createauthdb.php auth,
auth .
create database auth;
use auth;
create table auth (
name
pass
primary key
);

varchar(lO) not null,


varchar(30) not null,
(name)

insert into auth values


( 'user', 'pass');
insert into auth values
( 'testuser', password('test!23') );
grant select, insert, update, delete
on auth.*
to webauthglocalhost
identified by 'webauth';


, .
.
PHP- crypt()
-. :
string crypt (string str[, string salt])

str, .
, "pass" salt "",
cryptO "xxkTlmYjIikoII". "pass" ,
. , ,
.
str salt .
PHP-,
if( $username == "user" && $password == "pass" )
{
//
}


if( $username = 'user' && crypt($password,'') == 'xxkTlmYjIikoII' )
{
//

14. MySQL

Ll\

, "xxkTlmYjlikoII" crypt(). ,
, crypt().
, . .
MySQL,
PHP- crypt() MySQL- PASSWORDO.
, . crypt() PASSWORDO .
PASSWORDO 14.2 SQL
:
select count)*) from auth where
name = ' $name' and
pass = password('$password')

auth,
name Sname pass
PASSWORDO, Spassword
, ,
0 1.


.
HTTP- ,
. , .
Web-. .
, 14.1 , .
auto_prepend_file auto_appcnd_file
(prepend) (append) . 5.
, , ? , .

. , URL, urlencode(),
.
. Web-,
, , ,
. . , , .

272

3.

HTTP- .
, Web- . . HTTP-, 20 24.


,
, HTTP-.
Web- Web-. Web- - .
Web-
, Web- . ,
, .
HTTP- . Web-.
, PHP, Apache IIS.
. HTTP 1.1 , - (digest authentication). ( , MD5)
. - Web-,
. - Microsoft Internet Explorer 5.0. Netscape Navigator 6.0.
, . , - .
, , . . , , ,
.
() , ,
Telnet FTP.
. -
. SSL
Web.
15.
,
.

. ,
. , -

14. MySQL

2,1 J

. .


PHP-, , -, ,
. HTTP-
, Apache Apache ISAPI- IIS.
14.4 .
14.4 http.php HTTP-
.

// IIS,
// $PHP_AUTH_USER $PHP_AUTH_PW
if (substr ($SERVER_SOFTWARE, 0, 9) == "Microsoft" SS
!isset($PHP__AUTH_USER) &&
!isset($PHP~AUTH_PW) &&
substr ($HTTP AUTHORIZATION, 0, 6) == "Basic "
)
{
list($PHP_AUTH_DSER, $PHP_AUTH_PW) =
explode ( " : " , base64_decode (substr ($HTTP_AUTHORIZATION, 6) ) ) ;
}
// if -
if ($PHP_A0TH_USER != "user" I | $PHP_AUTH_PW != "pass")
{
//
//
header ( 'WWW-Authenticate: Basic realm="Realm-Name" ' ) ;
if (substr ($SERVER_SOFTWARE, 0, 9) == "Microsoft")
header ("Status : 401 Unauthorized");
else
header ("HTTP/1. 0 401 Unauthorized");
echo "<hl>Go Away !</hl>" ;
echo "You are not authorized to view this resource.";
}
else
{
//
echo "<hl>Here it is!</hl>";
echo "<p>I bet you are glad you can see this secret page.";

14.4 ,
. ,
. ,
. ,

274

3.

?i|>*--'-:
1:

T .--i" -?'' 1

Back .

-.,:

iJ

Stop

'_-J

flditnh

'""

Horns

jigj hHp:/ywebserver/chapfer14ypfotected

14.4.

HTTP-



.

'':--'sSA,;,.::.

I "
.

'

.-!J

-1'.

Seari-h rjnle

-xj

I!

MiM01

I .O'
'

Mail

^]: ii

r m*tname

Sfe:

webtwv

Rssto-Nem-

.
HTML- . . ,
. . 14.4 ,
Internet Explorer.
,

. Internet Explorer ,
, . Netscape
Navigator , "Authentication Failed. Retry?". Netscape , Cancel.
14.1 14.2, , . .


.htaccess Apache
, ,
PHP-. Apache
, .
mod_auth, - .
, HTML- . HTML-, HTML- <html>
<body>.

14. MySQL

2,1 J

14.5 HTML-, ,
. content.html. 14.6
HTML- .
rejection.html. , , , . , ,
, ,
, .
14.5. content.html .
<htmlxbody>
<hl>Here it is!</hl>
<p>I bet you are glad you can see this secret page.
</bodyX/html>
14.6. rejection.html 401.
<htmlxbody>
<hl>Go Away!</hl>
<p>You are not authorized to view this resource.
</bodyX/html>
.
14.7. .htaccess.
, .
14.7 .htaccess .htaccess
Apache, .
ErrorDocument 401 /chapter!4/rejection.html
AuthUserFile /home/book/.htpass
AuthGroupFile /dev/null
AuthName "Realm-Name"
AuthType Basic
require valid-user
14.7 .htaccess .
, .

ErrorDocument 401 /chapter!4/rejection.html
Apache, , . ErrorDocument
,
HTTP, , 404. :
ErrorDocument

URL

, 401 . -

276,

3.

, , .

AuthUserFile /home/book/.htpass
, .
.htpass, .
, . Web- .. ,
Web-. .htpass 14.8.
, , .

AuthGroupFile /dev/null

AuthGroupFile /dev/miU
UNIX-, .
, HTTP-
.
AuthName "Realm-Name"
, ,
. , , "Realm-Name" ("-").
, , .
AuthType

Basic

, . , , , , .

require

valid-user

, , .
14.8. .htpass
.
userl:OnRp9M80GS7zM
user2:nC13sOTOhp.ow
userS:yjQMCPWjXFTzU
user4:LOmlMEi/hAme2
.htpass , .
. ,
htpasswd. Apache.

14. MySQL

2,1 I

.
htpasswd [-cmdps] passwordfile username

htpasswd -b[cmdps] passwordfile username password

-. htpasswd,
.
.
, , htpasswd
.
m, d, , s
( ).
b , . htpasswd , htpasswd .
,
14.8.
htpasswd
htpasswd
htpasswd
htpasswd

-be /home/book/.htpass userl passl


-b /home/book/.htpass user2 pass2
-b /home/book/.htpass user4 pass3
-b /home/book/.htpass user4 pass4

, .
. , , .htaccess,
.htpass,
. .htaccess
httpd.conf Web-. htaccess , httpd.conf
.
, .
,
. , ,
, .

IIS
Apache, IIS HTTP-.
Apache , UNIX-
. , IIS .
Windows 2000 Internet Information Server 5 (IIS5) Internet Services Manager,
Administrative Tools ( ) .
Internet Services Manager ,
. 14.5. ,
windows-server . Default Web
Site Web-, .
protected, content.html.

278

3.

14.5.
Microsoft
Management Console

Internet Information
Server 5.

protected, Properties () .
Properties . Directory Security ( ) Custom Errors
( ). Anonymous Access (
) and Authentication Control ( ) Directory
Security. Edit , . 14.6.

. . 14.6,
, .
, ,
.
Custom Errors Authentication Methods.
Custom Errors, . 14.7,
. , .
rejection.html 14.6. IIS ,
Apache, , IIS
. 401,
, IIS . , , .
i s j CuitomEm

.
&gr

14.6.
//55

,

.

access and dube


authentication methods fa tits lesourcft.

d hi ^: acC*s*'

- i f fha fdowhj) auttwWica&wi fiiethu*, user new and p


mattecient
rwwd when '
.
'

Seteci a defauft domain;

i ~ hTtejiisrtKl Windows at

279

14. MySQL

4iSfo4fy\ BtTPMSKteB
-eitoiM^ae for HTTP Em.;---

Custom Emw |
.--

--:-

14.7.
Custom Errors



.

Apply

Help

, IIS5. Windows, IIS5


, UNIX,
. , IIS5 , .
IIS , ,
. "John"
"password",
. Web . , , Web-,
, Telnet.


mod_auth_mysql
,
mod_auth Apache. , mod_auth .
, mod_auth_mysql
mod_auth . mod_auth, ,
.
, ,
.

mod_auth_mysql
mod_auth_mysql Apache
MySQL, .

280

3.

. README USAGE
, .
1. .
CD-ROM.
http://www.zend.com

http://www,mysql.com.downloads/contrib.html

2. zip tar .
3. mod_auth_mysql configure. MySQL Apache.
, :
./configure with-mysql=/var/mysql --with-apache=/src/apache_l.3.12

.
4. make, make install. configure
Apache
activate-module=src/modules/auth_mysql/libauth_mysql.a


:
./configure --enable-module=ssl \
--activate-module=src/modules/php4/libphp4.a \
--enable-module=php4 prefix=/usr/local/apache enable-shared=ssl \
--activete-module=src/modules/auth_mysql/libauth_mysql.a

5. ,
, .
, , auth .
6. htpd.conf mod_auth_mysql.
,
:
Auth_MySQL_Info hostname user password

?
, , Apache. Apache :
/usr/local/apache/bin/apachectl startssl

Auth_MySQL_Info
httpd.conf, , mod_auth_mysql .

14. MySQL

mod_auth_mysql
mod_auth_mysql , mod_auth. 14.9 .htaccess,
,
.
14.9. .htaccess
MySQL
ErrorDocument 401 /chapter!4/rejection.html
AuthName "Realm Name"
AuthType Basic
Auth_MySQL_DB auth
Auth_MySQL_Encryption_Types MySQL
Auth_MySQL_Password_Table auth
Auth_MySQL_Username_Field name
Auth_MySQL_Password_Field pass
require valid-user

, ,
14.7. 401 (
). .
14.7, , . mod_auth_mysql
, 14.9
. Auth_MySQL_DB, Auth_MySQL_Password_Table,
Auth_MySQL_Username_Field, Auth_MySQL_Password_Field , , , .
Auth_MySQL_Encryption_Types, . MySQL.
Plaintext, Crypt_DES MySQL.
Crypt_DES UNIX
DES.
, mod_auth_mysql
, mod_auth. . ,
, .
Web- mod_auth_mysql
.
.
Web- MySQL.


,
, ,
.
, .

282

3.

20 ,
, , .
24 . , .


HTTP- RFC 2617,

http://www.ifc-editor.org/rfo/rfc2617.txt
mod_auth,
Apache,
http://www.apache.org/docs/mod/mod_auth.html
mod_auth_mysql
http://www.zend.com

http://www.express.ru/docs/mod_auth_mysql_base.html



, . SSL, .

lO

PHP MySQL

, ,
. , .
:



?


Internet , .
.
, . , ,
, .
. , MySQL,
. 15.1.

284

3.

MySQL

15.1
Web-.

, , ,
, .
. Web-
, Internet Web-.
PHP-, Web-
.
PHP- . - HTML- includeQ require()
SQL- MySQL, . MySQL,
.
:

Internet

, . ,
Internet .


Web- , .
, .
, ,
,
Internet-.
, .
,
,
HTML-, .

15. MySQL

.2 5

, , , , Java, cookie-
JavaScript. , ,
, , .
Web-, 40- . 2000 . , ( ,
) 128-
, .
,
, Web-, . SSL .
, , Web-
, . , "" , -,
cURL
.
cURL, , 17. , ,
.
, .
,
(), (JavaScript) .
, , , HTML-. , JavaScript, .
, , . JavaScript , , .
( )
(cookie-). cookie-
( ) 20.
Web- .
,
, . ,
, , ,
, .

Internet
, Internet , .
Internet ,
. -

286

3.

, .
13. , , .
, :

, , .
,
.

, ,
.

Internet . ,
, .
, ,
, , , . , 13.
,
Internet.
, , ,
Web- Internet:
SSL (Secure Sockets Layer, )

S-HTTP (Secure Hypertext Transfer Protocol, )

, , SSL , S-HTTP . SSL .


, ,
. . 15.1 .
, .
, Web . . ,
, .
.
, , . ,
. ,
.
, ( ) SAPI Web-, CGI.

15. MySQL

2. I

, ,
.

Internet? ? ,
, SSL.
SSL . ,
. , , , MySQL Web-.
MySQL TCP/IP, .
, , .
Internet, , ,
, ,
Internet.
SSL. fopenQ HTTP, HTTPS. SSL cURL. 17.
, , ,
.
( -
), SSL, ,
.
, ?
?
.


(SSL) ,
Netscape Web Web-.
.
SSL 2, 3.
Web- SSL,
. Internet Explorer Netscape Navigator SSL,
3.
, ,
.
. . 15.2.
HTTP,
Transmission Control Protocol (TCP, ), ,
, Internet Protocol (IP, ).
,
, .

288

3.
| FTP SMTP| ...
TCP/UDP
IP

15.2 , , , HTTP.

HTTP . FTP, SMTP telnet ( . 15.2), POP,


. TCP , TCP/IP. IP . () . TCP/IP
, .

. .
SSL .
SSL .
. 15.3. SSL ,
HTTP, .

HTTP

SSL

SSL

SSL

SSL
TCP


SSL

IP

15.3 SSL ,
.

SSL HTTP, HTTP. , SSL


, .. ,
. , , .
Web- Web- HTTP,
(), .
:
1. , SSL,
.
2. .

15. MySQL
3. ( ) .
4. . .
5. :
5.1. .
5.2. (
).
5.3.
-.
, , , . , , ,
, .
SSL- :
1. .
2. () .
3. (message authentication code,
MAC), -.
4. MAC .
5.
.
. 15.4.

<html><head><ttle><My </>...

TCP-
15.4 SSL , , .
. 216

290

3.

, TCP
. , . , , .
, SSL , ,
, .
. ,
, . , SSL, , .
SSL ,
,
.
SSL 3.0 , , TLS
1.0 (Transport Layer Security, ),
TLS ,
. TLS ,
, . SSL 3.0, .

,
Web- ,
.
, , , .
. .
addslashesQ . , . , stripslashes().

magic_quotes_gpc

magic_quotes_runtime php.ini.
, magic_quotes_gpc
GET, POST cookie-,
a magic_quote_runtime , .

escapeshellcmdQ , system() ().


, .

HTML- PHP-
strip_tags(). , .

htmlspecialchars() HTML-. , < &It;. .

15. MySQL

2,7 1


(HTML- PHP-, MySQL) , . 15.1 . , .
. Web- .
Web-. ,
htdocs Apache inetpub IIS. ,
.
Web-.
. , ,
Web-,
, Web-.
,
Web-.
,
Web-.
. .
.
.
, Web- creditcardnumbers.txt,
, ? ,
. , ,
, .
Web- , .
, , .
, . MySQL , . ,
MySQL. , MySQL,
.
: PHP-
MySQL. PHP-
. ,
. Web- ,
.
Web- .php
,
. , . .inc Web-,
. Web ,
, .php.

Web- , MySQL
. , , .
Web- ,
, Web- .
Web- ( , ,
),
.

?
,
. Internet . ,
, . , , .
?
,
, .
, , , .
Web-.
,
, , , .


, , , . - PGP
- Pretty Good Privacy ( ). .
(Philip R. Zimmermann) PGP , .
PGP, .
.
,
http: //web.mit.edu/network/pgp.html

PGP Network Associates.


http : / /www . pgp . com

PGP PGP:
http : / /www . pgpi . org

15. MySQL

2,7J

PGP . GPG Gnu


Privacy Guard ( GNU)
PGP.
- .
. , PGP , , , .
GPG
http://www.gnupg.org

, , , GPG , PGP
( ). GPG Web-. PGP
.
GPG. , GPG
. , :
, .

GPG
GPG Linux , www.gnupg.org, gunzip tar.
,
Linux:
configure ( ./configure )
make
make install

root, prefix:
./configure pref1=////

, root
GPG.
, GPG
/usr/local/bln/gpg . GPG.
Windows- . zip-,
gpg.exe ,
PATH. ( C:\Windows\ - .)
C:\gnupg, gpg.
, GPG PGP , .
Web- GPG
PGP, GPG, . , , PGP,
, .

294

3.

, . , (Public Key),
( PHP-) ,
(Private Key), .
, ,
Web-, .
GPG,
:
gpg gen-key

,
, . ,
. 'Luke Welling
<luke@tangledweb.com.au>'. .
:
gpg export > filename

, GPG-
PGP- . ,
ASCII- :
gpg export -a > filename

Web- FTP.
, UNIX. Windows
, .
Web- , :
chmod 644 filename

, , PHP-, GPG. ,
, . 'nobody', .
, Web-. root. Web-
nobody. . (
, .)
su root
su nobody

nobody GPG.
nobody.
/etc/passwd. Linux nobody /, nobody
. BSD- nobody /nonexistent. -

15. MySQL
, . nobody /tmp. , Web , .

cd ~
mkdir . gnupg

nobody .
:
gpg gen-key

nobody ,
. ,
.
:
gpg --import filename

GPG, ,

gpg --edit-key 'Luke Welling <luke@tangledweb. com.au>'

. , 'Luke Welling <luke@tangledweb.com.au>', , , .


help,
trust (), sign () save ().
trust GPG, , sign nobody, save .

GPG
GPG .
test.txt,
.

- recipient 'Luke Welling <l-uke@tangledweb.com.au>1 --encrypt test.txt
( )
gpg: Warning: using insecure memory!
test.txt.asc. ,
:
----- BEGIN PGP MESSAGE ----Version: GnuPG vl . 0 . 3 (GNU/Linux)
Comment: For info see http://www.gnupg.org
hQEOAODU7hVGgdtnEAQAhr4HgR7xpIBsK9CiELQw85+klQdQ-bp/FzqL8tICrO.+B3
OGJTEehPUDErwqUw/uQLTdsOrloPSrIAZ7c6GVkhOYEVBj2MskT81IIBvdo95OyH
K9PUCvg/rLxJlkxe4Vp8QFET5E3FdII/ly8VP5gSTE7gAgmOSbFf3S91PqwMyTkD
/2oJEvL6e3cP384sOi81rBbDbOUAAhCjjXt2DX/uX9q6P18QW56UICUOn4DPaWlG

296

3.

/gnNZCkcVDgLcKfBjbkB/TCTrohpA7o7kX4CIcIh7KlIMHY4RKdnCWQf271oE+8i9
cJRSCMsFIoI6MMNRCO.HY6p9bfxL2uE39IRJrQbe6xoEeOnkBOuTYxiLOTG+FrNrE
tvBVMSOnsttu7HJey+oY4Z833pk5+MeVwYumJwlvHjdZxZinV6wz46G02XGT17b28V
wSBnWOoBHSZsPvkQXHTOq65EixP8y+YJvBN3z4pzdHOXa+NpqbH7q3+xXmd30hDR
+u7 t6MxTLDbgC+NR
=gfQu
END

PGP MESSAGE

, , :
gpg -d test.txt.asc
.
, ,
-:
gpg -do test.out test.txt.asc

GPG , , , , .
- ,
GPG.
15.1 15.2 ,
, GPG.
15.1 privatejnail.php HTML-

<html>
<body>
<hl>Send Me Private Mail</hl>

<?
// ,
// ( 80 443 SSL)
if($HTTP_SERVER_VARS["SERVER_PORT"]!=443)
echo "<pXfont color = red>
WARNING: you have not connected to this page using SSL.
Your message could be read by others.</font></p>";
?>
<form method = post action
Your email address:<br>
<input type = text name =
Subject:<br>
<input type = text name =
Your message:<br>
<textarea name = body cols
</textareaXbr>
<input type = submit value
</form>
</body>

= send_private_mail.phpXbr>
from size = 38Xbr>
title size = 38xbr>
= 30 rows = 10>
= "Send!">

15. MySQL
15.2 send_privatejnail.php PHP- GPG

<?

$to_email = "lukeglocalhost" ;
// gpg,
// /tntp/ nobody
putenv ( "GNUPGHOME=/ tmp/ . gnupg" ) ;

//
$infile = tempnam("", "pgp")'
$outfile = $inile. " .asc" ;
// ,
$fp = fopen($infile, "w");
fwrite($fp, $body) ;
f close ($fp) ;
//
$comnand = "/usr/local/bin/gpg -a \\
--recipient 'Luke Welling <luke@ tangledweb.com.au>' \\
--encrypt -o $outfile $infile" ;
// gpg
system ($ command, $result) ;
//
unlink ($infile) ;
if ($result==0)
{
$fp = fopen($outfile, "r") ;
if (!$fp| Ifilesize ($outfile) ==0)
{
$result = -1;
}
else
{
//
$contents = freed ($fp, filesize ($outfile) ) ;
//
unlink <$outfile) ;
mail($to_email, $title, $contents, "From: $from\n") ;
echo "<hl>Message Sent</hl>
<p>Your message was encrypted and sent .
<p>Thank you . " ;

if ($result!=0)
{
echo "<hl>Error:</hl>
<p>Your message could not be encrypted, so has not been
sent.
<p>Sorry . " ;

298

3.

, . $to_email.

putenv("GNOPGHOME=/tmp/.gnupg");

, GPG.
nobody /trap/.
tempnam()
. , . , ,
. 'pgp',
, .

$coimnand = "/usr/local/bin/gpg - ".


"recipient 'Luke Welling <luke@tangledweb.com.au>' ".
"--encrypt -o $outile $infile";

gpg. . , GPG ,
.

system($command, $result);

Scommand Sresult.
, , ,
, .
, unlinkQ. , . , Web- , .

. GPG
, , ? GPG
Web-, ,
. 15.5.

Web-

>

3
>

>

15.5 , , Internet
.

15. MySQL

. Internet, .
, Web-.
. SMTP-
.
POP . , .
. 15.5 1, 2 3. 2 3 GPG , . 1
, HTML-.
, , . , SSL.
443, . SSL . SSL, .
,
-. URL, SSL. , ,
, . , , , . URL action .
:
<form method = post action = send_private_mail .php>

, SSL-, SSL:
<form method = post action = "https : //webserver/send_private_mail.php">

URL, , SSL,
.
, SSL,
.
, , . HTML-, .

300

3.


SSL 3.0 Netscape:
http://home.netscape.com/eng/ss!3/
.


. , Internet,
.


16

17
18

19

20

21

16

2 Web . ,
Web-.
:




, .
,
- Web- (, )
FTP-. .
,

6.
, .



HTTP .

16.

303

HTTP- , . HTML-. , , . 16.1.

Bad,

16.1
HTML-,

,

ii ^ : ! i*

hamlst

H.stoji

M.-J | Pirt

Upload new news files

Upload this ffle: f^

, . Browse () . ,
. .

Send File ( ). ,
-.

HTML-

HTML-. HTML- , . 16.1,
16.1.
16.1 upload.html HTML-
<html>
<head>
<title>Administration upload new files</title>
</head>
<body>
<hl>Upload new news files</hl>
<form enctype="multipart/form-data" action="upload.php" method=post>
cinput type="hidden" name="MAX_FILE_SIZE" value="1000">
Upload this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
</body>
</html>

, POST. PUT, NetScape Composer Amaya.


GET .
.
<form> enctype="multipart/formdata", , .

3U4

4.


. :
<input type="hidden"

name="MAX_FILE_SIZE"

value="1000">

MAX_FILE_SIZE , ( ).
:
<input name="userfile"

type="file">

name ( ) , , -.

PHP-
PHP- .
, Web- . , , .
HTML- userfile, PHP :
Suserfile Web-.

$userfile_name .
$userfile_size .
$usertile_type MIME- , text/plain
(/) image/gif (/gif).

$HTTP_POST_FILES:
$HTTP_POST_FILES['userfile'] ['tmp_name']
$HTTP_POST_FILES['userfile']['name']

SHTTP_POST_FILES['userfile'] ['size']
$ HTTP_POST_FILES ['userfile'] ['type' ]
, - . , .
,
, , . 16.2.
16.2 upload.php PHP- ,
HTML-
<head>
<title>Uploading...
</head>
<body>
<hl>Uploading

16.

J\J J

if ($userfile=="none")
{
echo "Problem: no file uploaded";
exit;
}
if ($userfile_size==0)
{
echo "Problem: uploaded file is zero length";
exit;
}
if ($userfile_type != "text/plain")
{
echo "Problem: file is not plain text" ;
exit;
}
if ( ! is_uploaded_f ile ($userf ile) )
{
echo "Problem: possible file upload attack";
exit;
}
$upfile = " /home /book/uploads/ " . $userf ile_name ;
if ( ! copy ($userf ile, $upfile) )
<
echo "Problem: Could not move file into directory";
exit ;
echo "File uploaded successfully<brxbr>" ;
$fp = f open ($upf ile, "r") ;
$contents = fread ($fp, filesize ($upfile) ) ;
f close ($fp) ;
$contents = strip_tags ($contents) ;
$fp = f open ($upf ile, "w") ;
fwrite($fp, $contents) ;
f close ($fp) ;
echo "Preview of uploaded file contents : <brxhr>" ;
echo $contents;
echo "<brxhr>" ;

?>
</body>
</html>
<?
// .
// is_uploaded_file 4.0.3.
// .
function is_uploaded_file($filename) {
if (!$tmp_file = get_cfg_var ( 'upload_tmp_dir ' ) ) {
$tmp_file = dirname (tempnam( ' ' , ' ' ) ) ;
}
$tmp_file .= '/' basename ($filename) ;
/* php.ini... */
return (ereg_replace ('/+', '/', $tmp_file) == $filename) ;

, . , , , .
.

306

4.

.
, Suserfile. "", .
( ,
$userffle_si/e ) (
$userffle_type).
,
/etc/passwd. .
,
. /home/book/uploads/. Web- , - .
, strip_tags()
HTML- PHP- -.
, ,
.
() . 16.2.

16.2

^ : -
i3J hR//w*bseiv

Uploading file...

He uploaded successfully
Preview of uploaded 61e content:
2nd July, 2000 - Widget Corporation today announced their forthcoming Initial Public
Offering. Analysts are confident the company's shares should leap on the first day in light of
recent deals with NASA.

2000 . ,
. BUGTRAQ.
BUGTRAQ, ,
http://lists.insecure.org/bugtraq/2000/Sep/0237.html

,
/etc/passwd,
is_uploaded_file(). 4.0.3. 4.0.2, .


. ,
, ,
Web-.

16.

J\) /

, /etc/passwd , .



.
. .

, ,
. , . , ,
. "" .

NT Windows
.

, php.ini.
upload_tmp_dir, , . memory_Hmit, .

, . , . -.

.



.
.


,
. . 16.3 .
16.3 browsedir.php -

<html>
<head>
<title>Browse Directories</title>
</head>
<body>
<hl>Browsing</hl>

308

4.

$current_dir = "/home/book/uploads/";
$dir = opendir($current_dir);
echo "Upload directory is $current_dir<br>"
echo "Directory Listing: <brXhrXbr>";
while ($file = readdir($dir))

echo "$file<br>"

echo "<hrXbr>"
closedir($dir);

?>
</body>
</html>

opendirQ, closedir() readdir().


opendir() .
fopen(), , ,
:
$dir = opendir ($current_dir) ;

, fopen(),
.
,
readdir(Sdir), . false. , false
"", , . - ,
, .
,
closedir($dir) , fclose().
. 16.3.

16.3


,
. ( ) ..
( ).

jrj

Browsing
Upload directory is /home/book/nploads/
Directory Listing.

ipo.txt

, () .
rewinddir(Sdir).
.

16.

dir,
. handle path, read(), close() rewind(),
"" .


.
dirname($path) basename($path) , , , .
, .
, . diskfreespace($path). ,
(Windows) (UNIX), .


.
mkdirQ rmdir() , ,
. , , .
mkdir() ,
.
( ) , :
mkdir( "/trap/ testing" , 0777);

. AND () , , umask. , umask = 022, , 0755.


,
umask:
$oldumaslc = umask ( 0 ) ;
mkdir ("/tmp/testing", 0 7 7 7 ) ;
umask ($oldumask) ;

umaskQ,
umask. umask ,
; , umask.
rmdirQ :
rmdir ("/tmp/testing") ;

rmdir (": \\tmp\\testing") ;


.

j 1U

4.


,
, Web-, . , .


, :
while ($file = $dir->read())
{
echo "<a href=\ "filedetails.php?file=".$file. "\ ">".$file."</aXbr>";
}
filedetails.php ( 16.4) .
: , fileowner() filegroup(), Windows
.
16.4 filedetails.php

<html>
<head>
<title>File Details</title>
</head>
<body>
<?
$current_dir = "/home/book/uploads/";
$file = basename($file);
//

echo "<hl>Details of file: ".$file."</hl>";


$file = $current_dir.$file;
echo "<h2>File data</h2>";
echo "File last accessed: ".date("j F Y H:i", fileatime($file))."<br>";
echo "File last modified: ".date("j F Y H:i", filemtime($file))."<br>";
$user = posix_getpwuid(fileowner($file));
echo "File owner: ".$user["name"]."<br>";
$group = posix_getgrgid(filegroup($file));
echo "File group: ".$group["name"]."<br>";
echo "File permissions: ".decoct(fileperms($file))."<br>";
echo "File type: ".filetype($file)."<br>";
echo "File size: " .filesize($file) ." bytes<br>" ;
echo "<h2>File tests</h2>" ;
echo "is_dir: ".(is_dir($file)? "true" : "false")."<br>";
echo "is_executable: ".(is_executable($file)? "true" : "false")."<br>";
echo "is_file: ".(is_file($file)? "true" : "false")."<br>";
echo "is_link: " . (is_link($file)? "true" : "false")."<br>";
echo "is_readable: ".(is_readable($file)? "true" : "false")."<br>";
echo "is_writable: ". (is_writable($file)? "true" : "false")."<br>";
?>
</body>
</html>
16.4 . 16.4.

16.

J J.

Details of file: ipo.txt


16.4

.
,

File data
File list accessed. 23 July 2000 01:48
File to modified 23 July 2000 OM8
File ownei; wwwna
File group: ncgroup
File permissions. 100755
File type; fie
File size: 206 bytes

File tests.
is_dir false
is_executable:true
is_file; true
Jink: false
is_readable: true
is writable: true

, , 16.4.
, basenameQ
, . ( ,
dirname().)
fileatime() filemtime() , , . , dateQ, .
( ) ,
.
fileowner() filegroup() , ,
(uid) (gid), .
, , , posix_getpwuid() posix_getgrgid(). uid gid, , ;
.
fileperms() . decoct() , UNIX.
filetype() .
: fifo, char, dir, block, link, file unknown.
filesizeQ .

is_dir(), is_executable(), is_file(), is_link(),
is_readable() is_writable(). ,
true false.

stat(), , ,
. lstat() .

J 12*

4.

-
, . ,
clearstatcache () ;

.
, , .


,
.
chgrp((ile, group), chmod(flle, permissions) chown(file, user)
UNIX. Windows-. , chown() , true.
chgrp() ,
. , ( ),
, root.
chmod() . chmod UNIX "", , :
chmod("somefile.txt",

0777);

chown() .
, root, .

,
,
.
touch().
.
touch UNIX. :
int touch (string file,

[int time])

,
, (
). , . , .
unlink() ( ,
delete). :
unlink(Sfilename);

, Win32. Windows
system("del filename.ext") ;

() rename():
copy($source_path, $destination_path);
rename($oldfile, $newfile);

16.

J 1 j

, , () 16.2.
renameQ ,
. .
, ,
. ,

, .


.
, , Web-
. ,
ezmlm
, .
Web-.
.
1. ()
():
string exec (string command [, array result [, int return_value]])

, , :
exec("Is -la");

() .
.
result, ,
, return_value
.
2. passthru()
passthru():
void passthru (string command [, int return_value])

passthru() . ,
, .
.
, ().
3. system()
systemQ:
string system (string command [, int return_value])

4.

. ( ), passthruQ.
(
) false ( ).
, .
4.
1. , .
. . - .
16.5 .
16.5 progex.php

<?
echo "<pre>" ;
// exec
exec ("Is -la", $result) ;
foreach ($result as $line)
echo "$line\ n" ;
echo "<brXhrXbr>" ;
// pass thru
passthru("ls -la");
echo "<brXhrXbr>" ;
// system
$result = system ("Is -la") ;
echo "<brXhrXbr>" ;
//
$result = 'Is -al~;
echo $result;
echo "</pre>" ;


, .
, ,
escapeshellcmd(), IK
- , . :
system (escapeshellcmd($command_with_user_data) ) ;

: getenvf) putenvQ
, .
: getenv(), , putenv(), .

16.

j IJ

, , .
phpinfoQ.
, . , :
getenv("HTTP_REFERER");
URL- ,
.
putenv():
$home = "/home/nobody";
putenv (" HOME=$home ") ;
CGI
:
http://hoohoo.ncsa.uiuc.edu/cgi/env.html



, UNIX.


17
, , . .

if

,
Internet. .
:


Web- HTTP

FTP
cURL



. , -: , ,
.
.
,
. HTTP, (Hypertext Transfer Protocol), Web-. FTP,
(File Transfer Protocol), . .

17.

J1 /

Internet , RFC
(Requests for Comments, ). Internet Engineering Task Force (IETF). RFC Internet. Web- RFC Editor
http://www.f-edi tor.org/

,
RFC ,
. , , .
, , RFC2616, HTTP/1.1, RFC822,
Internet.
, . SMTP,
POP IMAP, Web- HTTP
HTTPS, FTP.


mail(). 4, . SMTP
(Simple Mail Transfer Protocol, ).
mail() , . 27 HTML MIME, (Richard Heyes) HTML-, . SMTP
. IMAP (Internet Message Access Protocol, Internet, RFC2060) POP (Post Office
Protocol, , RFC1939 STD0053)
.
.
, , , POP,
.
IMAP.
IMAP-, POP NNTP (Network News Transfer
Protocol, ).
IMAP 26.

Web- NTTP
Web ,
. . .
, , ,
.
, ?

J1

4. PUP

, URL,
. , -
, URL,
.
, NASDAQ ( ).
Amazon.com. ( , .) 17.1.
17.1 lookup.php
NASDAQ, ( ,
)

Ssymbol _
<html>
<head>
<title>Stock Quote from NASDAO</title>
</head>
<body>
<?
//
$symbol="AMZN" ;
echo "<hl>Stock Quote for $symbol</hl>" ;
// URL
$theurl = "http://quotes.nasdaq-amex.com/Quote.dll?"
. "page=multiSmode=StockSsymbol=" . $symbol ;
if (!($fp = fopen($theurl, "r")))
{
echo "Could not open URL" ;
exit ;
}
$contents = fread($fp, 1000000);
f close ($fp) ;
// ,
$pattern = "(\\\$[0-9 ]+\\ . [0-9]+) " ;
if (eregi ($pattern, $contents, $quote) )
{
echo "$symbol was last sold at: " ;
echo $quote[l];
} else
{
echo "No quote available" ;
};
//
echo "<br>"
."This information retrieved from <br>"
. "<a href=\"$theurl\">$theurl</axbr>"
."on ".(date("l js F Y g:i a T"));
?>
</body>
</html>

. 17.1.

17.

I j > . . - * , - .
jj

17.1


NASDAQ
.

Bo<*

Tfonrad

Stop

<3 ". d.
M.>

jy . 'i^::

'..v^i l:.)Sra Hiitov

J \_ /


"M?J

^]
-

'

- '

Stock Quote for AMZN


XMZNwaj but sold at $ 33.0625
" mformabon retrieved from
so Wednesday 10thMay2000 1;205

i)

, .
, 2,
, URL.
. fopen()
$ = fopen ($theurl, r)

URL.
URL :
$contents = fread($fp, 1000000);
f close ($p) ;
, .
, ulesize(Sfile),
URL .
Web- Scontents.
eregi():
$pattern = ( \ \ \ $[0-9 ] +\\ . [0-9] +) ;
if (eregi ($pattern, $contents, $quote) )
{

echo $symbol was last sold at: ;


echo $quote[l];

!
.
.

, . (Philip Greenspun)
Bill Gates Wealth Clock ( ):
http : //www . webho . com/Weal thClock
. U.S. Census Bureau ( ). Microsoft, , -

j2\J

4.

, , .
: , , , . , .
,
, , , ,
URL. url_encode(). , URL, , ,
. :
$encodedparameter = url_encode($parameter);


"" , , IP- . ,
Yahoo!, URL, .
.
HTML- 17.2.
17.2 directory_submit.html HTML-
<head>
<title>Submit your site</title>
</head>
<body>
<hl>Submit site</hl>
<form method=post action="directory_submit.php">
URL: <input type=text name="url" size=30 value="http://"Xbr>
Email contact: <input type=text name="email" size=23Xbr>
<input type="submit" name="Submit site">
</form>
</body>
</html>

.
17.2.
17.2

, ,
URL
,



.

:c4fc..J

._....
_,,.
<:.1>
*

Submit site
TJRI/ jhttp;//wwwjogfedweb.cam.au
Email ccntact. [laure@tenglEdweb.com.au

;.>, ,.-..

;:

Hi,v

17.

321

Submit () , URL , ,
. , , . 17.3.

17.3


URL


,

.

Site submission results


Host is at IP 209.249.117.237
Email is delivered via; mail.tadgledwcb.com.a
AH submitted details are ok.
Thank you for submittmg your site.
It wffl be visited by one of our staff members soon.

, ,
PHP gethostbynameO getmxrrQ. 17.3.
17.3 directory_submit.php URL
<html>
<head>
<title>Site submission results</title>
</head>
<body>
<hl>Site submission results</hl>
// URL
$url = parse_url($url) ;
$host = $url[host];
if(!($ip = gethostbyname($host)))
echo "Host for URL does not have valid IP" ;
exit;
echo "Host is at IP $ip <br>" ;
//
$email = explode("@", $email) ;
$emailhost = $email[l];
if (!getmxrr($emailhost, $mxhostsarr))
echo "Email address is not at valid host";
exit;
echo "Email is delivered via:
foreach ($mxhostsarr as $mx)
echo "$mx ";

";

// ,
echo "<br>All submitted details are ok.<br>";
echo "Thank you for submitting your site.<br>"
."It will be visited by one of our staff members soon."
*. 216

J 2,2*

4.

II ...
?>
</body>
</html>
.
URL parse_url(). URL. (scheme), (user), (pass), (host),
(port), (path), (query) (fragment). , , URL.
URL
http://nobody:secret@bigcompany.com:80/script.php?variable=value#anchor

scheme: http://
user: nobody

pass: secret

host: bigcompany.com
port: 80
path: scriptphp

query: variable=value

fragment: anchor

,
:
$url = parse_url($url);
$host = $url[host];
IP- , DNS-,
gethostbyname(). IP-, false :
$ip = gethostbyname($host)

, gethostbyaddr(),
IP- .
, , ,
. , .
URL , . explodeQ:
$email = explode(@, $email);
$emailhost = $email[l];

, , . getmxrr():
getmxrr($emailhost, $mxhostsarr)

17.

MX (Mail Exchange, )
, Smxhostarr.
- DNS , .
, MX , . , . ( ,
, .) DNS
MX- , , .
,
- .

checkdnsrrQ true,
- DNS.

FTP
File Transfer Protocol ( ), FTP, . , fopen() FTP- , HTTP-,
FTP-. , , FTP.
.
UNIX, PHP- configure
--enable-ftp, make. FTP-
Win32,
extension=php_f tp . dll

"Windows Extensions" (" Windows") php.ini. ( .)

FTP
FTP-
. Web- . 17.4
, FTP- .
17.4 ftpmirror.php
FTP-
<html>
<head>
<title>Mirror update</title>
</head>
<body>
<hl>Mirror update</hl>
<?
//
$host = "ftp.cs.rmit.edu.au";
$user = "anonymous";
$password = "laura@tangledweb.com.au";
$remotefile = "/pub/tsg/ttsshl4 . zip" ;
$localfile = "$DOCUMENT_ROOT/ . . /writable/ttssh!4 . zip" ;

J2.Q

4.

II
$conn = ftp_connect("$host");
if (! $corm)
{
echo "Error: Could not connect to ftp server<br>";
exit;
}
echo "Connected to $host.<br>" ;
//
@ $result = ftp_login($conn, $user, $pass);
if (!$result)
{
echo "Error: Could not log on as $user<br>";
ftp_quit($conn);
exit;
}
echo "Logged in as $user<br>";
//
echo "Checking file time...<br>";
if (file_exists($localfile))
{
$localtime = filemtime($localfile);
echo "Local file last updated ";
echo date("G:i j-M-Y", $localtime);
echo "<br>";
}
else
$localtime=0;
$remotetime = ftp_mdtm($conn, $remotefile);
if (!($remotetime >= 0))
{
// , ,
// " "
echo "Can't access remote file time .<br>";
$remotetime=$localtime-H; //
}
else
{
echo "Remote file last updated ";
echo date("G:i j-M-Y", $remotetime) ;
echo "<br>";
}
if (!($remotetime > $localtime))
{
echo "Local copy is up to date.<br>";
exit;
}
//
echo "Getting file from server...<br>";
$fp = fopen ($localfile, "w") ;
if (!$success = ftp_fget($conn, $fp, $remotefile, FTP_BIKARY))
{
echo "Error: Could not download file";
ftp_quit($conn);
exit;
}
fclose($fp);
echo "File downloaded successfully";

17.

2* J

//
ftp_quit($conn);
?>

</body>
</htmi>

. 17.4.
[*> *:::
17.4


FTP ,


,
.

S:v'

Mirror update

Connected to flp.cs.nfflt.edu.au.
Logged in as anonymous
Checking time,..
Remote fflelastupdated 1 3I-Mar-1993
Getting ffle from server...
File downloaded successfully

. :
$host = ftp.cs.rmit.edu.au;
$user = anonymous ;
$password = laura@tangledweb.com.au;
$remotefile = /pub/tsg/ttssh!4.zip;
$localfile = $DOCUMENT_ROOT/../writable/ttsshl4.zip;

Shost FTP-, , Suser Spassword , ,


.
FTP- (anonymous
login), .. ,
. ,
,
, . .
Sremoteffle , .
Term SSH SSH Windows. (SSH secure shell (
). Telnet,
.)
Slocalfile ,
.
, .
,
FTP :
1. -.
1. ( ).

4.

3. , .
4. , .
5. -.
.
-

ftp

hostname

Windows UNIX.
:
$conn = ftp_connect($host) ;
if (!$conn)
{
echo Error: Could not connect to ftp server<br>;
exit;
}
echo Connected to $host.<br>;

ftp_connect().
, , false,
. ,
. ( .) ,
FTP- 21, FTP-.
-

. ftp_Iogin():
@ $result = ftp_login($conn, $user, $pass);
if (!$result)
{
echo "Error: Could not log on as $user<br>" ;
ftp_quit($conn);
exit;
}
echo "Logged in as $user<br>" ;

: FTP- (
ftp_connect()), . , true, false.
, @, . , , , . ,
Sresult, , .
, , FTP- ftp_quit(); .

, ,
, ,

17.

J 2* I

, . . , .

file_exists(). , , , .
, filemtime() , Slocaltime
, Slocaltime 0, ..
""
:
echo "Checking file time. . .<br>" ;
if (file_exists($localfile))

$localtime = filemtime ($localfile) ;


echo "Local file last updated " ;
echo date("G:i j-M-Y", $localtime) ;
echo "<br>" ;

)
else
$local time=0 ;

( ffle_exists() filemtime() 2 16.)


. ftp_mdtm():
$remotetime = ftp_mdtm($conn, $remotefile) ;

FTP- . UNIX, -1, - . FTP- ,


. Sremotetime "",
Slocaltime, $localtime+l. ,
:
if (! ($remotetime >= 0))

// , ,
// " "
echo "Can't access remote file time.<br>";
$remotetime=$localtime+l;
// ,

}
else

echo "Remote file last updated " ;


echo date("G:i j-M-Y", $ remote time );
echo "<br>" ;

, ,
:
if {! ($r emote time > $ local time ))

echo "Local copy is up to date.<br>";


exit;

328

4.


:
echo "Getting file from server...<br>";
$fp = fopen ($localfile, "w");
if (!$success = ftp_fget($conn, $fp, $remotefile, FTP_BINARY))
{
echo "Error: Could net download file";
fclose($fp);
ftp_quit($conn);
exit;
}
fclose($fp) ;
echo "File downloaded -successfully";

,
fopenQ. ftp_fget(), . .
FTP-,
. FTP-.
FTP : ASCII .
ASCII (.. ,
ASCII-), . FTP- FTP_ASCII
FTP_BINARY, . , ftp_fget(). zip-, FTP_BINARY.
ftp_fget() true, , false,
. Ssuccess; , .
fcloseQ.
ftp_fget() ftp_get(), :
int ftp_get (int ftp_connection, string localfile_path,
string remotefile_path, int mode)

, ftp_fget(),
. ,
, .
, - mgct,
.
ftp_fget() ftp_get().

- ftp_quit():
ftp_quit($conn);

-.

17.


,
, ftp_fget() ftp_get().
ftp_fput() ftp_put() :
int ftp_fput (int ftp_connection, string remotefile_path,
int fp, int mode)
int ftp_put (int f tp_conneotion , string remotef ile_path ,
string localfile_path, int mode)

_get-aeo.

-
, FTP,
. , . ,
, , , .
php.ini. 30 . , - . FTP,
, .
, , set_time_limit(). , .
,
set_time_limit<90) ;

90 .

FTP
FTP.
ftp_size() :
int ftp_size(int f tp_connection , string remotef ile_path)

-1 .
FTP- .
ftp_size() . ,

set_time_Umit().
FTP- :
$listing = ftp_nlist ($conn, "$directory_path") ;
foreach ($listing as $filename)
echo "$filename <br>" ;

4.

ftp_nlist().
FTP- ,
FTP-. FTP-,
FTP,
http://php.net/manual/re.ftp.php

mget (multiple get), ftp_nlist() , .


cURL
( 4.0.2) ,
cURL, Client URL libcurl,
(Daniel Stenberg).
fopenQ,
HTTP. fopen(). ,
, FTP-, FTP-.
cURL FTP, HTTP, HTTPS,
Gopher, Telnet, DICT, FILE LDAP. , HTTPS, HTTP POST HTTP GET, FTP HTTP, -, cookie-
HTTP.
, cURL .
cURL libcurl, configure
with-curl=[path]. path .
http://curl.haxx.se/

, cURL 7.0.2beta.
cURL .

1. cURL curl_init().
2. curl_setopt().
, URL, , URL,
, URL.
3. , curl_exec(), .
4. cURL curl_close().
, URL ,
curl_opt(). .

17.

331

cURL

, HTTPS ( fopen()
)

, HTML- POST

, , ,
.
, 17.5, Equifax Secure Server
HTTPS Web-.

17.5

https-curl.php

HTTPS-

<?
echo "<hl>HTTPS transfer with cORL</hl>" ;
$outputfile = " $DOCOMENT_ROOT/ . . /writable/equifax.html" ;
$fp = fopen($outputfile, "w") ;
echo "Initializing cURL session. . .<br>" ;
$ch = curl_init() ;
echo "Setting cURL options. . .<br>" ;
curl_setopt ($ch, CURLOPT_URL, "https://equifaxsecure. com") ;
curl_setopt ($ch, CURLOPT_FILE , $fp) ;
echo "Executing cHRL session. . .<br>" ;
curl_exec ($ch) ;
echo "Ending cURL session. . .<br>";
curl_close ($ch) ;
fclose($fp) ;

. fopcn(). , .
cURL curl_init():
$eh = curl_init() ;
cURL. , ,
, URL. , URL curl_setopt(), :
curl_setopt ($ch, CURLOPT_URL , "https ://equifaxsecure .com") ;
curl_setopt ($ch, CURLOPT_FILE , $fp) ;
curl_setopt() . , , .
. URL, . CURLOPT_URL. , , .
,
, . .
cURL :
curl exec ($ch) ;

3 3 2*

4.

URL, , $1.
cURL , :
curl close ($ch);
fclose($fp);
.
Snoopy,
http://snoopy.sourceforge.net/
cURL Web-.


, , ,
.
RFC
http://www.rfc-editor.org/

World Wide Web (World Wide Web Consortium):
http://www.w3.org/Protocols/

TCP/IP . .
Web- cURL
cURL. -:
http://curl.haxx.se/docs/httpscripting.shtml


18 PHP- . , , , MySQL .

18


, . MySQL , UNIX ,
, HTML-.
:

MySQL



1
date()
. PHP- .

date()
date() , . , , , UNIX. ,
date() .
, .
:
echo date("jS F Y " ) ;

"31th July 2001".


, date(),
. 18.1.

j JT-

4. PHP

18.1 PHP- dateQ

, , "am" "".

, , "AM"
"".

Internet- Swatch .
http://www.swatch.com.

. "01"
"31".

. ""
() "Sun" ().

. "January" ()
"December" ().

12- . "1" "12".

24- . "" "23".

12- . "01" "12".

24- . "00" "23".

. "00" "59".

, .
, "1", "".

. "1" "31".

. "Monday"
() "Sunday" ().

, .
"1", , "" .

.
"01" "12".

. "Jan" ()
"Dec" ().

. "1" "12".

. "00" "59".

.
"st", "nd", "rd" "th" , .

. "28" "31".

, , , "EST".

1 1970 . ;
UNIX .

. "" () "6" ().

, , "00".

, , "2000".

. "" "365".

. "-43200"
"43200".

18.

jjJ

UNIX
date() UNIX.
UNIX- 32-
, 1 1970 . . UNIX. ,
, .
UNIX , 2000- (Y2K), "" . , 2038 . .
, ""
(32 ). 2038 .
.
Windows-, date()
PHP- .
UNIX, niktimc(), :
int mktime (int hour, int minute, int second, int month,
int day, int year [, int is_dst])

, is_dst, , . 1,
, 0 , -1 ( ),
. ,
.
,
mktimeQ .
. , ,
0. , .
. ,
$timestamp = mktime ;
UNIX . , ,
$timestamp = date("U");

mktime() -, . 0 69 2000 2069,


70 99 1970 1999.

getdateQ
, , getdate(). :
array getdate

(int timestamp)

, , , . 18.2.

JJ

4.

.18.2 -, getdateQ

seconds

minutes

hours

mday

wday

year

yday

weekday

month


checkdate().
, . checkdateQ
:
int checkdate

(int month, int day, int year)

, 0 32767, 1
12, . .
,
checkdate(9, 18, 1972);

true, a
checkdate(9, 31, 2000)

MySQL
MySQL , . , MySQL . , 31th of July 2001 2001-0731 01-07-31. , MySQL, .
, MySQL . .
MySQL
date(), . , MySQL.
MySQL,
DATE_FORMAT() UNIX_TIMESTAMP().
DATE_FORMAT() ,
. MM-DD-YYYY (//) MySQL

IS.

JJI

YYYY-MM-DD (//).
:
SELECT DATE_FORMAT(date_coIunm,
FROM tablename;

'%m %d % Y ' )

% , %
, %\ .
MySQL . 18.3.
18.3 MySQL- DATE_FORMAT()

%W

%0

, (, 1st)

%Y

, 4-

, 2-

%d

%-

, 3-

%]

24-

%k

24-

%h %!

12-

%1

12-

%\

12- (hh:mm:ss [AM|PM])

24- (hh:mm:ss)

%S %s

AM

%w

, 0 () 6 ()

UNIX_TIMESTAMP , UNIX. ,
SELECT TJNIX_TIMESTAMP(date_coliunn)
FROM tablename;

UNIX. .

4.

UNIX , .
UNIX.



UNIX.
18.1.
18.1 calc_age.php
//
$day = 18;
$month = 9 ;
$year = 1972;
// //
$bdayunix = mktime ("", "", "", $month, $day, $year); //
// UNIX
$nowunix = time(); // UNIX
$ageunix = $nowunix - $bdayunix; //
$age = floor ($ageunix / (365 * 24 * 60 * 60)); //
//
echo "Age is $age";

. HTML-.
mktimeQ :
$bdayunix = mktime ("", "", "", $month, $day, $year);
$nowunix = mktime(); // UNIX
, :
$ageunix = $nowunix $bdayunix;

, . , , . ,
.
floor(), , , 20
:
$age = floor ($ageunix / (365 * 24 * 60 * 60)); //
//
, , UNIX (.. 32- ).


, .
, .

18.

. 15 1582 . 5 1582 .
.
. ,
20- .
, , , , . UNIX. , 4000 .. , .
(JD),
.
,
.
, :
int gregoriantojd (int month, int day,
string jdtoJulian(int julianday)

int year)

:
$jd = gregoriantojd (9, 18, 1582);
echo jdtojulian($jd);

mm/dd/yyyy
(//).

, , ,
UNIX.



MySQL, Web-:
http://php.net/manual/ref.datetime.php
http: //www.mysql. com/documentation/mysql/conmiented/
manual.php?section=Date_and_time_functions

,
:
http://php.net/manual/ref.calendar.php

, :
http://genealogy.org/~scottlee/cal-overview.html



. 19 .

19

.
,
GD. ,
.
:




: Web
MySQL.

gd,
http://www.boutell.com/gd/

1.6.2 4.
PNG.
JPEG, jpeg-6b
GD jpeg.
ftp:littp.uu.net/graphics/jpeg/

19.

J 41


with-jpeg-dir=/path/to/jpeg-6b
, , .
TrueType- FreeType, 4;
http://www.ftype.org/
TrueType PostScript Type 1 tllib,
ftp://ftp.neuroinformatik.ruhr-uni-bochum.de/pub/software/tllib/

with-tllib[=path/to/tllib]


GD JPEG, PNG WBMP. GIF . .

JPEG
JPEG ( "-") Joint Photographic Experts Group ( ) . , JPEG, JFIF, , JPEG.
, , JPEG

. , .. . JPEG- , .
, , .
JPEG/JFIF JPEG:
http://www.jpeg. rg/publi /jpeghomepage.htm

PNG
PNG ( "") Portable Network Graphics ( ). GIF (Graphics
Interchange Format, ) , . Web- PNG " ". , , , , ,
, Web- , GIF.
, GIF,
, - .
MNG,
.

4.

PNG :
http://www.freesoftware.com/pub/png/

WBMP
WBMP Wireless Bitmap ( ).
.
GD , .

GIF
GIF Graphics Interchange Format ( ). , Internet , , .
GD GIF?
, 1.3.
PNG GIF, GD 1.3 Web-
http://www.linuxguruz.org/downloads/gdl.3.tar.gz

, , , GD
. GIF .
, GD
GIF. GIF LZW (Lempel Ziv Welch), UNISYS. ,
GIF, UNISYS . , ,
Adobe, , , Photoshop,
GIF-. ,
, . ,
Web- GD GIF, , UNISYS .
- , GIF , UNISYS . , Internet.
Internet . ( ) UNISYS
http://www.Unisys.com/unisys/lzw/

Burn All Gifs (" GIF-")


http://burnallgifs.org/

,
,
PNG GIF.
PNG ,
LZW 19 2003 ., .

19.


:
1. , .
2. .
3. .
4. .
, 19.1.
19.1 simplegraph.php

Sales
()

<?
//
$height = 200;
$width = 200;
$im = IroageCreate ($width, $height) ;
$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0) ;
//
ImageFill($im, 0, 0, $black) ;
ImageLine ($im, 0, 0, $width, $height, $white) ,
4, 50, 150, "Sales", $white) ;
v:I:mageString($:i.m,
//
Header ("Content-type: image /png ") ;
ImagePng ($im) ;
//
ImageDestroy ($im) ;

. 19.1.

'

File'

Back

19.1

,

.

idS

Vew

foiviift)

Slop

Reiwsh

Home,

Seait.li

Kav.jite

4.


, . .
ImageCreate(), :
$im = ImageCreate($width, $height);

ImageCreate() . , . . (
.)
,
, -. ,
ImageCreateFromPNGO, ImageCreateFromJPEG() ImageCreateFromGIF(). , ,
$im = ImageCreateFromPNGC'baseimage.png") ;

,
, .


.
, .
, ,
, . , . ,
. , .
, ImageColorAllocateQ.
, (RGB) .
19.1 : .

$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0) ;

, .
, ,
, ,
.
:

19.



. .
ImageFilI() :
ImageFill($im, , , $black) ;

, ( ) .

,
, =0, =0. x=$width, y=$height. , !

(0, 0) (Swidth, Sheight)


:
ImageLine($im, 0, 0, $width, $height, $ white) ;

,
.
:
ImageString($im, 4, 50, 150, "Sales", $white) ;

ImageStringO .
:
int imagestring (int im, int font, int x, int y, string s, int col)

, , , .
1 5. . TrueType PostScript. . TrueType.
,
, ImageStringO , ,
ImageChar() ( ) . TrueType
PostScript , .
, . 19.2.

19.2

,

.


.

Normal
Anti-aliased

346

4.

, ,
. , " ". , . .


.
.
. Web-, , HTML-. Header(), MIME- :
Header

("Content-type:

iraage/png");

MIME- ,
Web-. HTML ( ),
Content-type:

text/html

, .
, ,
HTML. Header(), .
HTTP-. HTTP-. . . :
Header ("Location: http://www.domain.com/new_home_page.html");

, Header() , HTTP- . HTTP- ,


- . ,
echo
, , Header(). HTTP- HeaderQ , .

ImagePng ( $ i m ) ;

PNG.
, ImageJPEGQ,
JPEG, ImageGIFQ, GD.
, , ..
Header ("Content-type: image/jpeg");

Header ("Content-type: image/gif") ;

19.

34 /

, , , . , ImagePNG() ( ):
ImagePNG($im, $ilename);
, (,
).


, , .
ImageDestroyQ:
ImageDestroy($im);



, , , , . :
1. , .
2. , ,
<IMG>.
3. , .
1 2 . 3.
HTML-
:
<img src="simplegraph.php" height=200
width=200 alt="Sales going down">

PNG, JPEG
GIF , SRC
, .
, . . 19.3.

Sales
This month's sales are shown below.

Next month should show some improvement.

. - ' 19.3
Web- -
, .
.

348

4.

'- .) -.
ltltp'//*ebsvw/cbepte(13/degn_buttgaWiri

Ek

a 'Jj ;/3 1

.....

.--

Slop

.,1,

I
-

.-!

Create buttons

.....

Hi-Jay

"

73 I

Home

Type button text


J Home
Choose button color
sited
f Green

19.4
.

19.5 ,
make_button.php.

, ,
.
, ,
, , , Photoshop, GIMP .
, .
, TrueType, . TrueType- , .
, , , ,
. . , , .
, ,
. . 19.4. (HTML- , ; ,
CD-ROM design_button.html.)
Web-.
, , Web !
. 19.5.
makejbutton.php. 19.2.
19.2 make_button.php
design_button.html HTML-
<?
// ,
// button-text color
if (empty($button_text) || empty($color))
echo "Could not create image - form not filled out correctly";
exit;

19.
//
$im = imagecreatefrompng ("$color-button.png");
$width_image = ImageSX($im) ;
$height_image = ImageSY($im);
// 18
$width_image_wo_margins = $width_image - (2 * 18);
$height_image_wo_margins = $height_image - (2 * 18) ;
// , , ,
//
// ,
$font_size = 33;

do
{

$font_size-- ;
//
$bbox=imagettfbbox ($font_size, 0, "arial.ttf", $button_text) ;
$right_text = $bbox[2];
//
$let_text = $[0];
//
$width_text = $right_text - $left_text; // ?
$height_text = abs($bbox[7] - $bbox[l]); // ?

} while ( $font_size>8 &&


( $height_text>$height image_wo_margins ||
$width_text>$width_image_wo_margins )
);
if ( $height_text>$height_image_wo_margins | |
$width_text>$width_image_wo_margins )
{
//
echo "Text given will not fit on button. <BR>" ;
}
else
{
//
//
$text_x = $width_image/2. - $width_text/2.0;
$text_y = $height_image/2. - $height_text/2. ;
if ($left_text < 0)
$text x += abs($left_text);

//
//

$above_line_text = abs($bbox[7]) ;
// ?
$text_y += $above_line_text;
//
$text_y -= 2;

//

$white = ImageColorAllocate ($im, 255, 255, 255);


ImageTTFText ($im, $font_size, 0, $text_x, $text_y, $white,
"arial.ttf" , $button_text);
Header ("Content-type: image/png");
ImagePng ($im);

}
ImageDestroy ($im);

4.

, .
. ,
.


19.2 .
: (red-button.prig), (greenbutton.png) (blue-button.png).
, , Scolor.

:
$im = imagecreatefrompng ("$color-button.png");

ImageCreateFromPNG() PNG,
. ,
PNG.
ImageCreateFromJPEGO ImageCreateFromGIF().
^
ImageCreateFromPNGl) . , ImagePNGl).
.


$button_text , .
.
, , .
.
:
$width_image = ImageSX($im);
$height_image = ImageSY($im);

. , .
, ! 18 .
$width_image_wo_margins = $width_image - (2 * 18) ;
$height_image_wo_margins = $height_image - (2 * 18) ;

. 32 (, 33, ), , :
$font_size = 33;

, , :

19.

do
{

$font_size--;
//
$bbox=iraagettfbbox ($font_size, 0, "arial.ttf", $button_text);
$right_text = $bbox[2];
//
$left_text = $[0];
//
$width__text = $right_text - $left_text;
//
$height_text = abs($bbox[7] - $ b b o x [ l ] ) ;
//

} while

( $font_size>8 &&
( $height_text>$height_image_wo_margins

);

$width_text>$width_image_wo_margins )

| |

, . ImageGetTTFBBox(), TrueType-.
TrueType Image lTFl'ext().
, . . 19.6.

(0,0)

19.6
. (0,0).


$ = imagettfbbox ($font_size, 0,

"arial.ttf", $button_text);

: " $button_text, , TrueType Arial $font_size".


, , . , ( ), .
, . . 19.1.
19.1

4.

, , ,
"
.
, ImageTTFBBoxO,
. , . , ,
, .
. 19.6. , ,
. , ""
. (descenders).
(0,0). Y
, .
, .
, , , X, -1.
,
.
:
$right_text = $[2];
//
$left_text = $[0];
//
$width_text = $right_text $left_text;
//
$height_text = abs($bbox[7] $ [ 1 ] ) ; //

?
?

:
>
while ( $font_size>8 &&
(

$height_text>$height_image_wo_margins
$width text>$width_image_wo_margins )

| |

);

. : , , 8.
: .
,
, :
if ( $height_text>$height_image_wo_margins | |
$width_text>$width image_wo margins )
{

//
echo "Text given will not fit on button.<BR>";


, , . , .
$text_x = $width_image/2. - $width_text/2.0;
$text_y = $height_image/2. - $height_text/2. ;
- , ,
:
if

($left_text < 0)
$text_x += abs($left_text);//
$above_line_text = abs($[7]); // ?
$text_y += $above_line_text;
//
$text_y -= 2 ;
//

19.

j jj

, " ".


. , :
$white = ImageColorAllocate

($im, 255, 255, 2 5 5 ) ;

Imagel"lFlext():
ImageTTFText ($im, $font_size, 0, $text_x, $text_y, $white,
"arial.ttf", $button_text);

: ,
, , X Y , ,
, , .

,
, . ,
. , .


:
Header ("Content-type: image/png");
ImagePng ($im);

:
ImageDestroy

($im);

! , ,
. 19.5.



. .
, Web-. MySQL, - .
.
, Web- ,
.
MySQL poll. poll_results, : candidate num_votes . poll poll. SQL-, 19.3. mysql, root:
mysql -u root -p < pollsetup. sql
12 . 216

4. PHP
, , MySQL.
19.3 pollsetup.sql poll
create database poll ;
use poll;
create table poll_results (
candidate varchar(30),
num_votes int
);
insert into poll_results values
('John Smith1 , 0) ,
( 'Mary Jones' , 0) ,
( 'Fred Bloggs' , 0)
grant all privileges
on poll . *
to pollOlocalhost
identified by 'poll';
.
vote.html, 19.4.
19.4 vote.html
<html>
<head>
<title>Polling</title>
<head>
<body>
<hl>Pop Poll</hl>
<p>Who will you vote for in the election?</p>
<form method=post action="show_poll.php">
<input type=radio name=vote value="John Smith">John Smith<br>
<input type=radio name=vote value="Mary Jones">Mary Jones<br>
<input type=radio name=vote value="Fred Bloggs">Fred Bloggs<br><br>
<input type=submit value="Show results">
</form>
</body>
. 19.7.
submit, ,
.

19.7


,
submit
()

.

Y}4-4 ji?i h

Pop Poll
Wbc> will you vote for the election?
f John Smith
Mary Jones

19.

1 (

|*

Vw

*V''

| Bad.

'

loot

Slop

Swl*

H.Jffly ]

"SMI

i Address |t] bp:

19.8



,

.

355

Poll Results

tt

212 . 19.8.
, , .
, .
,
MySQL,
.
, . . 1 (
) 19.5.1.
19.5.1 showpoll.php 1

<?
/*************************************************************

//
if (!$db_conn = @mysql_connect("localhost" , "poll", "poll"))

echo "Could not connect to db<br>" ;


exit;

};
@mysql_select_db("poll") ;
if (! empty ($vote) )

// ,

$vote = addslashes ($vote) ;


$query = "update poll_results
set num_votes = num_votes + 1
where candidate = ' $vote ' " ;
if(!($result = @mysql_query ($query, $db_conn)))
{
echo "Could not connect to db<br>" ;
exit;

// ,
//
$query = "select * from poll_results" ;

JJ

4.

if ( ! ($result = 6mysql_query($query,

$db_conn) ) )

echo "Could not connect to db<br>";


exit;

}
$num_candidates = mysql_num_rows($result);
//
$total_votes=0;
while ($row = mysql_fetch_object ($result))
{
$total_votes +=
$row->num_votes;
}
mysql_data_seek($result, 0); //
1, 19.5.1, MySQL,
. , ,
. 2 19.5.2.
19.5.2 showpoll.php 2 ,

/*******************************************

******************************************/
//
$width=500;
//
// 640x480
$left_margin = 50; //
$right_margin = 50; //
$bar_height = 40;
$bar_spacing = $bar_height/2;
$font = "arial.ttf";
$title_size = 16;
//
$main_size = 12;
//
$small_size = 12;
//
$text_indent = 10; //
//
$ = $left_margin + 60; //
$ = 50;
$bar_unit = ($width-($x+$right_margin)) / 100;
// ""
//
//
$height = $num_candidates * ($bar_height + $bar_spacing) + 50;
2 , .
, , ,
. , ,
.
Swidth , $left_margin $right_margin , $bar_height $bar_spacing "" , $font, $title_size, $main_size, $small_size $text_indent
, .

19.

Jj /

. , . ( X), ( Y).
: ,
:
$bar_unit = ($width-($x+$right_margin)) / 100;

// ""
//

100, .
:
$height = $num_candidates *

($bar_height + $bar_spacing)

+ 50;

, , , . 3 19.5.3.
19.5.3 show/poll.php 3

/*******************************************

*******************************************/
//
$im = imagecreate($width,$height) ;
//
$white=ImageColorAllocate($im,255,255,255);
$blue=ImageColorAllocate($im,0,64,128);
$black=ImageColorAllocate($im,0,0,0);
$pink = ImageColorAllocate($im,255,78,243) ;
$text_color = $black;
$percent_color = $black;
$bg_color = $white;
$line_color = $black;
$bar_color = $blue;
$number_color = $pink;
//
ImageFilledRectangle($im,0,0,$width,$height,$bg_color);
//
ImageRectangle($im,0,0,$width-l,$height-l,$line_color);
//
$title = "Poll Results";
$title_dimensions = ImageTTFBBox($title_size, 0, $font, $title);
$title~length = $title_dimensions[2] - $title_dimensions[0];
$title_height = abs($title_dimensions[7] - $title_dimensions[1]) ;
$title_above_line = abs($title_dimensions[7]);
$title_x = ($width-$title_length)/2;
//
$title_y = ($y - $title_height)/2 + $title_above_line; //
// ,
ImageTTFText($im, $title_size, 0, $title_x, $title_y,
$text_color, $font, $title);
// ,
//
ImageLine($im, $x, $y-5, $, $height-15, $line_color) ;

J3

4.

3 ,
.

ImageFilledRectangle($im,0,0,$width,$height,$bg_color);
ImageFilledRectangleO, ,
. , . X Y . , , .
, .

ImageRectangle($im,0,0,$width-l,$height-l,$line_color);
. . , $\vidth-l $height-l. Swidth Sheight, .

, .
, :
ImageLine($im, $x, $y-5, $, $height-15, $line_color) ;
Sim, ($, $-5)
($, $height-15), $1_1.

.
. 4 19.5.4.
19.5.4 showpoll.php 4

/*******************************************

*******************************************/
//
//
while ($row = mysql_fetch_object ($result))
{

if ($total_votes > 0)
$percent = intval(round(($row->num_votes/$total_votes)*100));
else
$percent = 0 ;
//
ljnageTTFText($im, $main_size, 0, $width-30, $y+($bar_height/2) ,
$percent_color, $font, $percent."%");
if ($total_votes > 0)
$right_value = intval(round(($row->num votes/$total votes)*100));
else
$right_value = 0 ;
//
$bar_length = $x + ($right_value * $bar_unit);
//

19.
ImageFilledRectangle($im, $x, $y-2, $bar_length, $y+$bar_height,
$bar_color) ;
//
ImageTTFText ($im, $main_size, 0, $text_indent, $+ ($bar_height/2) ,
$text_oolor, $font, "$row->candidate") ;
// , 100%
ImageRectangle ($im, $bar_length+l , $y-2 ,
($x+(100*$bar_unit) ) , $y+$bar_height , $line_color) ;
//
ImageTTFText ($im, $small_size, 0, $x+ (100*$bar_unit) -50,
$y+($bar_height/2) ,
$number_color , $font, $row->num_votes. "/" $total_votes)
//
$=$+ ($bar_height+-$bar_spacing) ;
}

/*******************************************

*******************************************/
Header ("Content-type: image/png") ;
ImagePng($im) ;
/*******************************************

*******************************************/
ImageDestroy ($im) ;
4 , , .
, ImageTTFText().
ImageFilledRectangle():
ImageFilledRectangle($im, $, $-2 , $bar_length, $y+$bar_height,
$bar_color) ;
, 100%, Image Rectangle():
ImageRectangle ($im, $bar_length+l , $y-2,
($x+(100*$bar_unit) ) , $y+$bar_height, $line_color) ;
ImagePNGO, ImageDestroyO .
, .
, , , , ""
. , , .
, .


, , , (ImageArc()) (ImagePolygon()), .
. ,
, .

360

4.


Internet.
, GD, PHP- . GD
http://www.boutell.com/gd/
Zend Devshed:
http://www.zend.com
http://devshed.com
, ,
(Steve Maranda), Devshed.



, 4.

20

PHP


4.
:


cookie-


, , HTTP " ". ,
. , HTTP
, .
,

Web-.
,
. . ,
(shopping carts).
PHPLib, ,
.
http://phplib.netuse.de/index.php3

362

4.

. PHPLib, PHPLib
. ,
, PHPLib.


, . .
cookie-
, URL.
,
. . , "" , .
""
cookie-, URL, , . ( ,

" ").
, Web-, URL. URL , , , ,
.
, URL, cookie-.

cookie-?
cookie- , . cookie- , HTTP-, :
Set-Cookie: NAME=VALUE; [expires=DATE; ] [path=PATH;]
[domain=DOMAIN_NAME;] [secure]

cookie- NAME VALUE. . expires ,


cookie-
(, , cookie- , - , ).
path domain
URL, cookie-. secure ,
cookie- HTTP-.

20.

URL, cookie-,
. - URL, , .

cookie-
cookie- , setcookieQ
:
int setcookie (string name [, string value
[, string domain [, int secure]]]]])

[, int expire

[, string path

,
Set-Cookie.
cookie-
setcookie

("mycookie",

"value");

( ), Smycookie,
"value".
$HTTP_COOKIE_VARS["mycookie"].
cookie- setcookieQ ,
. cookie- ( URL ), , cookie- .
cookie-
HeaderQ cookie-.
, cookie-
( cookie- ).

cookie-
cookie- : ,
cookie-, , cookie- . ,
cookie-/ URL ( ).
cookie- . .
cookie-, , session_get_cookiejarams(). , lifetime, path domain.
:
session_set_cookie_params($lifetime,

$path,

$domain);

cookie- .
cookie-,
cookie- Netscape:
http://home.netscape.com/newsref/std/cookie_spec.html

364

4.


cookie- .
cookie-, .
, , URL. , URL
enable-trans-sid.
- , . SID,
, , GET:
< HREF="link.php?<?=SID?>">

--enable-trans-sid,
( , SID , --enabletrack-vars).

,
, .
.


,
. .
( ) ,
session_start():
session_start();
, . ,
. , , .
, session_start() , .
, (. ).
,
, - .

20.

session.auto_start php.ini (
).



, .
session_register(). , Smyvar :
$myvar = 5 ;
session_register("myvar");

: session_register() , . $.
. , .
, :
session_register("myvarl",

"myvar2");


, , .
. register_globals (. 1),
, , Smyvar. ,
$HTTP_SESSION_VARS,
, $HTTP_SESSION_VARS["myvar"].
GET POST. , .
, ,
(, isset()
empty()). , ,
GET POST. , , session_is_registered().
:
$result = session_is_registered("myvar");

, Smyvar ,
true false.
- SHTTP_SESSION_VARS
.


,
session_unregister():
session unregister("myvar");

366

4.

, ,
, , $.

( session_register()). ,
session_unset().
,

session_destroy();


,
.
.
$sess_var.
, , 20.1.
20.1 pagel.php

<?

session_start();
session_register("sess_var");
$sess_var = "Hello world!";
echo "The content of \ $sess_var is $sess_var<br>";
?>
<a href = "page2.php">Next page</a>

'.
. 20.1.
, . , , , . , .
(), ,
session_start().
3hltp://webserver/chapterZD/page1.php Microsoft Inl..
Eile Edit : :Yiew Favorites vlools
20.1

,

pagel.php.

:
:
: 0-"'' '
1J
:,".
<?*
--I
-
.:'.^--.- " _ '
::'"*^
M 3!> ' itf
*
, gack ;m; ";; "i: ,: sgp;:^f^^^^.;] '

I Ajjdress |ejhp://websewar/chaplaf20/page1.php

The content of Ssess_var is Hello world!


Next page

20.

367

, session_start().
20.2.
20.2 page2.php

session_start();
echo "The content of \ $sess_var ia $sess_var<br>";
session_unregister("sess_var");
<a href = "page3.php">Next page</a>

session_start() $sess_var ,
, (. . 20.2).
, session_unregister()
. : ,
$sess_var .
, page3.php,
. 20.3.
20.3 .
session_start();
echo "The content of \ $sess_var is $sess_var<br>";
session_destroy() ;

. 20.3, Ssess_var .
session_destroy() .

f 'f ""'""fr"m"Kir _

1
j

Si :-" " - . '

> II! \ '-':'': '.$


Jll
4
,9eck
'-;-
Stop
Ri^trash
Home
;

' "lr, b-

Favortur

j-

Help

Ba*

S^

; i AsJdrets je] http://wsbserver/chop!et20/page2,php

J3 http://websewer/chaptBr2D/pege3.php

The content of Ssess_var is Hello world!


Nest page

The content of Ssess var is

1
20.2 ,

page2.php.

20.3
.

368

4.


, php.ini. . 20.1 .
20.1

no

session.auto_start

()

session.cache_expire

180


( ).
cookie- .

session.cookie_domain

session.cookie lifetime

session.cookie_path

session.name

PHPSESSID

,
cookie-.

session.save_handler

.
,
.

session.save_path

/fmp

.


session.sa ve_handler.

session.use

1 ()

cookies


cookie-
. 0
.
cookie- .


cookie- .



.
, ,
,
. ,
MySQL .
24, .
,
14. mod_auth_mysql.
, , 14.3 14.
. , authmain.php, Web-. ,
members_only.php, ,

369

20.

. , logout.php, .
, , . 20.4. , authmain.php.
. , Members, , , . 20.5.
' hMp;/ /web serve r/choplerZO/aulh main, php ~ Micros

""

File dit
Back

.....

View

Favorites

-"., i

Slop

"

Toofs

Hslp
Hprrie

i!] Be*
* i - - . - ... . i ...: Sl'jp
0

; Search

.}

IWrash

:-"-'"., i

Hum*

Search

! AddBSS |ahtlp://webselvsr/chapter2U/au*tiiam.plif
' 1

Home page

Members only

You are nol logged in.

You are not logged in.

Userid:
Password:

Only logged in members may see this page.

Back to main p;i&

Members section
20.4
,

20.5 ,
,
.

( : testuser : test!23, 14), Members, , . 20.6.


. authmain.php, 20.4. .
20.4 authmain.php
session_start();
if ($userid && $password)
//
$db_conn = mysql_connect("localhost", "webauth", "webauth");
mysql_select_db("auth", $db_corm);
$query = "select * from auth "
."where name='$userid' "
. " and pass=password('$password')";
$result = mysql_query($query, $db_conn);
if (mysql_num_rows($result) >0 )
j
// ,
//
$valid_user = $userid;
session_register("valid_user") ;

4. PHP

J I \J

<html>
<body>
<hl>Home page</hl>
<?
if (session_is_registered("valid_user"))

echo "You are logged in as: $valid_user <br>" ;


echo "<a href=\"logout.php\">Log out</aXbr>";

}
else

if (isset($userid))

// ,
//
echo "Could not log you in";

}
else
{
// ,
//
echo "You are not logged in.<br>";

//
echo "<form method=post action=\"authmain.php\">";
echo "<table>";
echo "<trXtd>Userid:</td>" ;
echo "<td><input type=text name=useridx/tdx/tr>" ;
echo "<trXtd>Password:</td>";
echo "<tdxinput type=password name=passwordX/tdX/tr>";
echo "<trXtd colspan=2 align=center>" ;
echo "<input type=submit value=\"Log in\"X/tdX/tr>" ;
echo "</tableX/form>";
<br>
<a href="members_only.php">Members section</a>
</body>
</html>
hllp://websetver/chapter20/members_anly.php- Micr..

(
) ,
:
.

$valid_user.
: -
,
$valid_user, .

? , session_start().

$valid_user, .

'.&';":Ka;

Address jg] hp://websB(ver/chaptBr20/membere_only.php

&
_fj. $J

Members only
You are logged in as testuser.
Members only content goes here
Back lo main page

20.6

,

20.

3/1

if

, .
, :
echo
echo
echo
echo
echo
echo
echo
echo
echo

"<form method=post action=\ "authmain.php\ ">";


"<table>";
"<trXtd>Userid:</td>";
"<tdxinput type=text name=useridX/tdX/tr>" ;
"<trXtd>Password:</td>";
"<tdxinput type=password name=passwordx/tdx/tr>" ;
"<trXtd colspan=2 align=center>" ;
"<input type=submit value=\ "Log in\ "X/tdX/tr>" ;
"</tableX/f orm>" ;

(Submit),
. , ( Suserid
Spassword). , :
if ($userid && $password)
(
//
$db_conn = mysql_connect("localhost" , "webauth" , "webauth");
mysql_select_db ( "auth" , $db_conn) ;
$query = "select * from auth "
."where name=' $userid' "
. " and pass=password ( ' $password' ) " ;
$result = mysql_query ($query, $db_conn) ;

MySQL
. , $valid_user, . , , , , .
if

(mysql_num_rows ($result) >0 )


{
// ,
//
$valid_user = $userid;
session_register ("valid user") ;

, ,
. , , , :
if
{

(session_is_registered("valid_user") )
echo "You are logged in as : $valid_user <br>" ;
echo "<a href=\"logout.php\">Log out</aXbr>" ;

, , $valid_user, , :

3 / 2*

4.

if
{

(isset($userid) )
// ,
echo "Could not log you in" ;

$va!id_user ,
URL, :
members_only . php?valid_user=testuser

, , .
Members. 20.5.
20.5 members_only.php Members
Web-

<?

session_start() ;
echo "<hl>Members only</hl>" ;
//
if (session_is_registered("valid_user") )

echo "<p>You are logged in as $valid_user .</p>" ;


echo "<p>Members only content goes here</p>" ;

)
else
{
echo "<p>You are not logged in.</p>";
echo "<p>Only logged in members may see this page.</p>";
>
echo "<a href=\"authraain.php\">Back to main page</a>" ;

. , , , session_registered_user(). ,
, ,
.
logout.php,
. 20.6.
20.6 logout.php

<?

session_start() ;
$old_user = $valid_user;

// ,
//
$result = session_unregister ("valid_user") ;
session_destroy () ;

?>
<html>
<body>
<hl>Log out</hl>
<?
if ( ! empty ($old_user) )
{

if

($result)

20. PHP

J /j

1 1
echo "Logged out.<br>";
}

else
{

//
echo "Could not log you out.<br>";
else
{

// ,
// -
echo "You were not logged in, and so have not been logged out.<br>";

, . , , $valid_user . : ,
, .
, , .


4, PHPLib. , PHPLib
cookie-. URL, :
http://phplib.netuse.de/index.php3
http://home.netscape.com/newsref/std/cookie_spec.html


.
,
, .


, - .
:

, , eval()
: die exit





, ,
(' ") (\)
.

echo

"color = "#FFFFFF"";

. , ,
, . ,
echo

"color =

'#FFFFFF'";


echo

'color = "#FFFFFF"';

21. PHP

j /j

,
.
mysql
insert into company values ('Bob's Auto Parts');

MySQL.
addsIashesQ stripslashesQ, , , NUL-.
( "")
. php.ini
GET, POST, cookie .
magic_quotes_gpc
GET, POST cookie-.
magic_quotes_gpc "Bob's
Auto Parts", "Bob\'s Auto Parts",
.
get_magic_quotes_gpc() 1 0, magic_quotes_gpc. ,
stripslashes() , .
magic_quotes_runtime
, .
magic_quotes_runtime
get_magic_quotes_runtime(), 1 0.
set_magic_quotes_runtime().

, , evalQ
eval() -.
,
eval ( "echo 'Hello W o r l d ' ; " ) ;
. ,
echo

'Hello World' ;

, eval() .
, ,
eval(), ( ),
.
, eval() . , , ( ) , : , regexp,
eval().
, -
, eval().

J /

4. PHP

: die exit
exit. , :
exit;

.
die().

. Perl.
exit:
die("Script ending n o w " ) ;

or , , , :
mysql_query($query) or die("Could not execute query");

, :
function err_msg()
{
echo "MySQL error was: ";
echo mysql_error() ;
)
mysql_<juery ($query) or die (err_msg()) ;

,
.

.

,
, ,
. .
. , , .
, HTTP-.
,
. : serialize() unserialize().
serialize() :
$serial_object = serialize($my_object);

, , ,
. .
, serialize() employee, :

21.

377

class employee
{

var $name;
var $employee_id;

};

$this_emp = new employee;


$this_emp->name = "Fred";
$this_emp->employee_id = 5324 ;

:8:"employee":2:{s:4:"name";s:4:"Fred";s:ll:"employee_id";i:5324;}


.
,
. , addslashes(). , .
unserialize():
$new_object = unserialize($serial_object);

, stripslashes(),
addslashes()


, , .


,
, get_loaded_extensions() get_extension_funcs().
get_loaded_extensions() , , .
get_extension_funcs(),
.
21.1 ,
.
21.1 listjunctions.php ,
,
<?
echo "Function sets supported in this install are:<br>";
$extensions = get_loaded_extensions();
foreach ($extensions as $each_ext)
{
echo "$each_ext <br>";
echo "<ul>";
$ext_funcs = get_extension_funcs($each_ext);
foreach($ext_funcs as $func)
{
}

echo "<li> $func";

echo "</ul>";

J I

4.

, get_loaded_extensions() , a get_extension_funcs() .
, ,
.


, ( ) get_current_user():
echo get_current_user() ;


.

getlastmodO ( ):
echo date("g:i a, j M Y" ,getlastmodO ) ;

UNIX,
date() .


, dl().
. UNIX .so, Windows .dll.
dl()
dl("php_ftp.dll");

FTP ( Windows-).
, : php.ini. extension_dir ,
.
,
enable_dl php.ini. ,
.
. , dl() .


php.ini
. , ,
max_execution_time, .
ini_get()
ini_set().
21.2.

21. PHP

J / ~/

21.2 iniset.php php.ini


<?
$old_max_execution_time = ini_set (max_execution_time, 120) ;
echo old timeout is $old_max_execution_time <br>;
$max_execution_time = ini_get (max_execution_time) ;
echo new timeout is $max_execution_time <br>;
ini_set() . php.ini, .
.
120 ( 30 ).
ini_get() ,
, . , .


,
. Web- .
show_source() highlight_flle() . (,
show_source() highlight_file().)
. ( , - .) ,
show_source("list_functions.php");

, , , ,
HTML-. . , , .
highlight_string() , , .
php.ini. :
; Colors for Syntax Highlighting mode
highlight.string
=
#DDOOOO
highlight.comment
=
#FF8000
highlight.keyword
=
#007700
highlight.bg
=
#FFFFFF
highlight.default
=
#OOOOBB
highlight.html
=
#000000
RGB- HTML.


V ,
MySQL. , MySQL .
22 , , , , .


MySQL
22

MySQL

23
24
25
26
27
28
29
30




, Web

Web-

(PDF)

PHP
MySQL

MySQL.
,
- - 100 .
Web- . "" Web . Web-
Web-, , , Web. Web-
. ,
.
,
Web-.
, , , - .
:

Web-
Web-



j 2*

5. MySQL

, : PHP, HTML CSS


Web-
, , .
, .
, Web-,
.
-, Web- .
, .
.
. , Web , , ,
. .
, Web- . .
,
. Web- , .
Web- ,
: ,
.

, Web-, .

Web-
Web-. , .
, . , . , .
.
. Web- , , , .

. ? ? -

22, PHP MySQL

JJ

? ,
(use cases).
, . ,
, .
, . ,
(Open Source) . , , , , .
. Web- .
, , , , ,
.
.
. .
, . .
.
, .


, . , , , .
, , .
.
, .
, , , .
,
. , :
http://www.php.net/manual/

, PHP- . " "


{syntactic sugar). . , .
, .
, .
, , .
.
, , Web Web-

J 4

5. MySQL

, , - . Open Source ,
, , . , , ,
.

, .
, .


Web- .
. , .
, .


, ,
, , ..
Web- , . , . ,
. , .


:
.
.
.
,
.
, . , Ssurname.
. , $ , .
$surname_of_the_current_user ( ) ,
( ).
. ,
. , : , . , , . -

22. PHP MySQL

3J

, .
.
(, Sresult),
(, PI).
,
, , Sname SName. , ,
.
, , $WaReZ. .
, , . :
$username
$user_name
$UserName

, , . ,
-.
, . . , PHP- , : addslashesQ ( ) mysql_connect()
( MySQL). . , . - . - ,
.
, , . , .
,
PHP- . ,
MySQL mysql_, imap_. , (shopping cart)
cart.
,
. .


.
, .
:

, ( include) . , .

. , , .

13 . 216

386

5. MySQL

. .
, .

. , . ,
:
//
//
//

,
.
. - , .
: "
?".

.
. ,

, .

,
-


() . .
.
, , .
( ), . . ,
.
.
.
:
1:
if (condition) {
// -

2:
if (condition)
// -

. -,
.

22. PHP MySQL

37


.
,
. / ,
. ,
dbfunctions.php.
:
.
. , dbfunctions.php
, . ,
.

.
,
. , , , GiantScript.php (" ").


, . , ,
. , , , , .
,

. ,
. , - (build manager).
.
, . .


, Web-.
,
. , , . . .


, . . .
.

5. MySQL

, ,
, . .


, . ,
(, , ).
,
. , .
. , , .
.

, , .
, .
. , , ,
.
,
.
( ). . ,
. ,
.
.
,
. , .
.
.
, .
, . , .
, UNIX /
Open Source, CVS (Concurrent Versions System ). CVS UNIX.
, DOS, Windows Macintosh.
/,
Internet-, CVS . PHP, Apache, Mozilla ,
, .

22. PHP MySQL

38!/

CVS Web- :
http://www.cvshome.org/

CVS ,
, Java Windows, .
.
CVS. Microsoft Visual
Source Safe Visual Studio.


.
.
(IDE integrated development environment). IDE . ,
, , Web-. ( ,
, ).
IDE .
:
Zend IDE Windows UNIX:
http://www.zend.com/
, /, , ,
.
. Web-.
KPHPDevelop Desktop Environment Linux:
http://kphpdev.sourceforge.net/
IDE , , . ( CVS.)
, MySQL, PostgreSQL Sybase.

PHPCoder Win32:
http://phpcoder.stsoft.cjb.net
, . , . PHPCoder .

PHPEdit Win32:
http://www.phpedi t.com

5. MySQL

, . .

PHPGem:
http: //phpgem.ru.net: 8100/

PHPGem , , ,
MySQL PostgreSQL. PHPGem PHP-, .
, . ,
.

( )

( Web- )

, ,
.
, . , javadoc HTML-, Java-.
.
:
phpDoc:
http://sourceforge.net/projects/phpdoc

MySQL. ,
phpDoc
.

PHPDocumentator:
http : //phpdocu . sourcef orge . net

,
javadoc, .
phpautodoc:
http : //sourcef orge . net/pro jects/phpautodoc/

, javadoc.

22, PHP MySQL

3 J/ 1

( - ) SourceForge:
http://sourceforge.net

SourceForge, ,
UNIX/Linux, .


, Web-. .
,
. . . , -
.
"" , .
.
. , .
.
, ,
.
,
, .
, ,
. , , . ,
Web- , . , .
,
. - , . , ,
.
, . , , , , . - , ,
.
,
, , .

jy 2,

5. MySQL


, HTML
Web- (CSS cascading style sheets)
.
.
, .
PHP- HTML-.

. . . Web-,
HTML-, .
:
.
, , . TLA Consulting 5.

API-
. 6.

.
- . ,
- ,
PHP-. .

. ,
FastTemplate:
http://thewebmasters.net


, Web,
. , Web- .
.


, , . , , MySQL.
:
.
. .

22. PHP MySQL

jry J

.
. (, , ) .

. MySQL
EXPLAIN. ( 11.)

.

PHP-.
HTML- echo print(), . ( .) .
, . ,
.
. .

, .
, , . . , . ,
HTML-.

Zend
Zend Technologies ( ) , 4. ( , ) 3. ,
, 4.
Zend Optimizer. 40% 100%. 4.0.2 . ,
Web- Zend :
http://www.zend.com

, .
Zend Cache, PHP- . , . .

394

5. MySQL

, , Web. - , . . ,
.
. ( , .)
-, , . :

,


,

, , , .
, Web, .
Web- , Web-
. , .
. Web- .
. .
Web
. , .
- Web-. , , ,
. 100 . ,
, .
Web- ,
.
( .)

22. PHP MySQL


.
.
Web- Web- Web Site Engineering: Beyond Web Page Design
(Thomas A. Powell). .
Web- CVS :
http : //www . cvshome . org

(
!), , Open Source Development with CVS (Karl Franz Fogel) CVS Pocket Reference (Gregor
N. Purdy).
PHP-, IDE
SourceForge:
http://sourceforge.net

Web- Zend.
. .
http : //www . zend . com

,
, ,
, Web-. Web- Extreme
Programming:
http : / /www . extremeprogramming . org


23 ,
, .

23

PHP-.
,
. . ,
, .
:







'


:

,

,
, , .

23.

j /


, , . , , , , . , ,
. , , ,
, Java.
, , .
.
, .
. .
, ,
, , . , , .
. ,
.
:
Parse error: parse error in
/home/book/public_html/chapter23/error.php on line 2

<?

$date = date(m.d.y');

?>

date() ,
, .
, , .
, ,
, :
<?

$date = date('m.d.y) ;

?>

:
Parse error: parse error in
/home/book/public_html/chapter23/error.php on line 4

, ,
. ,
,
.

5. MySQL

:
if

(true)
echo

"error here";

,
. , . 1001 (parse
error on line 1001) , 1000 , .
, . , .


. . .
.

include

("filename.php");

. .
. ,
filename.php ,
, :
Fatal error: Failed opening required
' filename.php'
(include_path='.:/usr/local/lib/php1) in
/home/book/public_html/chapter23/error.php on line 1
, . .
. ,

.
$i = 10;
$j = 0;
$k = $i/$k;

:
Warning: Division by zero in
/home/book/public_html/chapter23/divO.php on line 3
.
,
.
,
.

23.

399

:


MySQL


.

.
. strip_tags() ,
stripslashes() ?
, , , . ,
nonexis ten t_f unction () ;
:
Fatal error: Call to undefined function: nonexis ten t_f unction ()
in /home/book/public_html/chapter23/error .php on line 1

, ,
, .
strstrQ ,
. :
strstr() ;

:
Warning: Wrong parameter count for strstrf) in
/home/book/public_html/chapter23/error .php on line 1

PHP , , .
:

<?

if($var == 4)
{

strstr() ;

strstrQ ,
$var 4. .
,
,
. ,
.
. .

4UU

5. MySQL


,
. , .
,
.
, fopen(), , . fopen()
false.

.
MySQL
MySQL
. mysql_connect()
:

MySQL Connection Failed: Can't connect to MySQL server on 'hostname'


(111)

MySQL Connection Failed: Can't connect to local MySQL server through


socket '/tmp/mysql.sock1 (111)

MySQL Connection Failed: Unknown MySQL Server Host 'hostname'

MySQL Connection Failed: Access denied for user:


(Using password: YES)

(2)

'usernameSlocalhost'

, mysql_connect()
false. , .

, . MySQL ,
.
PHP-, MySQL,
false .
mysql_pconnect(), mysql_select_db() mysql_query().
, mysql_error(), mysql_errno().
MySQL , mysql_error() , a mysql_errno() 0.
,
. :
$result = mysql_query( 'select * from does_not_exist' );
echo mysql_errno();
echo '<BR>';
echo mysql_error();

:
1146
Table 'dbname.does not exist' doesn't exist

23.

4U1

, MySQL ( mysql_error() mysql_errno()).


, .
, . ,
MySQL (mysqld) .
, , .
, , Web .

. , ,
.
, - .
SQL-, SQL , , . ,
:
select * from does_not_exist;

, does_not_exist . mysql_emio()
mysql_error().
SQL-, , , .
, , , . , , exists
column name, :
select * from exists where column_name = 'not in database';

, .
,
, .

,
, .
, , ,
.
, .
, , , .
:
$sp = fsockopen ( "localhost", 5000 ) ;

4U-2

5. MySQL


5000 localhost.
:
$sp = fsockopen ( "localhost", 5000, &$errorno, &$errorstr );
if(!$sp)
echo "ERROR: $errorno: $errorstr";

, . :
ERROR:

111: Connection refused

, ()
.
, .
, . , ,
.
,
. , , .
, .
, MySQL 200 . , , , .

.
, .

, AddSlashes() ( ). , , , O'Grady, .

.


. , , .
, :
for ( $i = 0; $i < 10; $i++ );
{
echo "doing something<BR>";

23.

4U3

. . , . , .
, "doing something" for 10
. ,
. for 10 , echo.
, , .
, . , . ,
.
,
. . ,
.
.
, , ,
. ,
. .
, ,
. 22 ,
. , , , .
, Order Quantity ( ). , ? " ", ?
, .
, ? ?
(,
JavaScript), .
, , URL-, ?
. . -,
, -,
,
.

4L/T1

5. MySQL


,
. 23.1 ,
. ,
.
23.1 dump_variables.php

<?

// HTML//
echo "\n<!-- BEGIN VARIABLE DUMP >\n\n";
echo "<!-- BEGIN GET VARS >\n";
echo "<!-- ".dump_array($HTTP_GET_VARS)." -->\n";
echo "<!-- BEGIN POST VARS >\n";
echo "<!-- n.dump_array($HTTP_POST_VARS)." >\n";
echo "<! BEGIN SESSION VARS -->\n";
echo "<!-- ".dump_array($HTTP_SESSION_VARS)." -->\n";
echo "<!-- BEGIN COOKIE VARS -->\n";
echo "<!-- ".dump_array($HTTP_COOKIE_VARS)." -->\n";
echo "\n<! END VARIABLE DUMP >\n";

// dump_array()
// ,
//
function dump_array($array)
{
if(is_array($array))
{
$size = count($array);
$string = "";
if($size)

$count = 0 ;
$string .= "{ ";
//
foreach($array as $var => $value)

$string .= "$var = $value";


if($count++ < ($size-l))

$string .= ", ";

}
}
$string .= " }";
}
return $string;

}
else
{
// ,
return $array;

23.

403

, .
GET-, POST-, cookie-
, .
HTML-.
:
1

<!-- { varl = ' v a l u e l , var2 = 'value2', var3 = 'valueS' } >

HTML- ,
, . .
.
20.4, 20, :
<! BEGIN VARIABLE DUMP >
<!-- BEGIN GET VARS -->
<!

<!
<!-<!
<!-<!
<!--

>

BEGIN POST VARS -->


{ userid = testuser, password = testl23 } -->
BEGIN SESSION VARS >
{ valid_user = testuser ) >
BEGIN COOKIE VARS >
{ PHPSESSID = 2552dc82bb465af56d65e9300f75fd68 } >

<!-- END VARIABLE DUMP ~>

, POST-, userid password. , , valid_user. 20, cookie-


. PHPSESSID, .


. , . , .
,
. 23.1.
, . , E_ERROR, .
.
( ) :
E_ALL & ~E_NOTICE

, . (&)
AND, (~) NOT.
: ALL AND NOT E NOTICE.

406

5. MySQL

23.1

E_ERROR

E_WARNING

E_PARSE

E_NOTICE

16

E_CORE_ERROR

32

E_CORE_WARNING

64

E_COMPILE_ERROR

128

E_COMPILE_WARN!NG

256

E_USER_ERROR

512

E_USER_WARNING

1024

E_USER_NOTICE

2048

E_ALL

E_ALL .
, OR (|):
E_ERROR | E_WARNING | EJPARSE | E_NOTICE | E_CORE_ERROR | E_CORE_KARNING
E_COMPILE_ERROR | E_COMPILE_WARNING | E_OSER_ERROR | E_USER_WARNING |
E_USER_NOTICE

, (
E_NOTICE):
E_ERROR | E_WARNING | E_PARSE | E_CORE_ERROR |
E_CORE_WARNING | E_COMPILE_ERROR |
E_COMPILE_WARNING | E_USER_ERROR | E_OSER WARNING | E USER NOTICE


php.ini
.
, php.ini:
error_reporting
display_errors
log_errors
track_errors

=
=
=
=

E_ALL & ~E_NOTICE


On
Off
Off

:
,

HTML

23.

407


,
$php_errormsg
,
E_ALL. .
, ,
.
(error_reporting). ,
(display_errors) (log_errors). .
.
.
(track_errors)
,
. , , .
, :
<>
<> </>: error message in <b>path/file.php</b>
on line <b>lineNumber</bXbr>

.
, .
HTML- , .
. ,
, Netscape . , HTML-, , , :
<table>
<trxtd>
<br>
<b>Error Type</b>: error message in <b>path/file.php</b>
on line <b>lineNumber</bXbr>

Netscape .

. errorjreporting().
, php.ini. . :
//
$old_level = error_reporting(0);
// ,
//
error_reporting($old_level);

4U

5. MySQL

, , , .
, .


trigger_error(). , .
, , ,
. : E_USER_ERROR, E_USER_WARNING
E_USER_NOTICE. ,
E_USER_NOTICE.
trigger_error():
trigger_error("This computer will self destruct in 15 seconds",
E_USER_WARNING);

( , 4.0.1.)


, C++ Java.
. ,
4.0.1 , .
, , .
set_error_handler() ,
, .
set_error_handler() ,
.
. ,
.
. .
set_error_handler():
set_error_handler("myErrorHandler");

myErrorHandlerQ,
. :
myErrorHandler(int error_type, string error msg)

.
:

(error_msg)


exit

23.

409

23.2 , , set_error_handler(), .
23.2 handle.php

//
function myErrorHandler ($errno, $errstr)
echo "<brXtable bgcolor = ' #cccccc' XtrXtd>
<PXB>ERROR:</B> $errstr
<P>Please try again, or contact us and tell us that
the error occurred in line ". LIKE ." of file "'. FILE
if ($errno == E_USER_ERROR| |$errno == E_ERROR)

."'",-

echo "<P>This error was fatal, program ending";


echo "</tdX/trX/table>" ;
// , ..
exit;
echo "</tdX/trX/table>" ;
//
set_error_handler("myErrorHandler");
//
trigger_error("Trigger function called", E_USER_NOTICE);
fopen("nofile", "r");
trigger_error("This computer is beige", E_USER_WARNING);
include ("nofile");
trigger_error("This computer will self destruct in 15 seconds",
E USER ERROR);

. 23.1.

hp://vbsrr/cr,apter;3/hendls.plif>

ERROR: '!

'.''''' ;:.

^eatft 'ry | ' tefi us tbat:tiit ernjr occurrei in foe S

23.1

,

.

ERROR: ('!".' H MCh 6kj f *eaoit| : ;:;

Please try again, or contactus and teu us feat tr* irrorMcicred m fie ^ c:
ERROR: This
Pke tty agm or contact us aiiH te!l \a tfcit Sir nrirr oratrcr! sj line E of fife '.luaiieftncWptM^totu'chspteriVbmdle pip'
.^1;1)*81':**
:

&#*?[&'!

-,':^:.

Pletse ay ajan, or 4% <*!| ||)''.&! if So ;s of 9e 'ybe/bMlt/puilt_hojl'clMptertJ/limB.tbp'


ERROR: " computer wi2 self des&uctio If
I1r;r try again or tontact us and trll in that. Uir enor oran-td m Inc F. nf fut '*ntcok/puMc._hMl'Uiai)teir*jr,dle.pbp'

41U

5. MySQL

.
, . ,
, .
, .
? ? ?
,
. ,
, - . ,
, , E_USER_ERROR, .


3 . ,

, .
4,
Zend.
- 3 ,
, enable-debugger, php.ini: debugger.host,
debugger.port debugger.enabled.
, ,
, .


24 .
.

Web-.
. .

Web (bookmarks)
, , . Web-,
.
,
, ,
. , , .
:




, PHPBookmark (
) ,
Backflip:
http://backflip.com

412,

5. MySQL


,
, .
.
-, . , .
-,
. .
-, .


, ,
. , .


, . ,
MySQL
.
, , :

. .
.

,
.

. , , ,
.

, , , .

. .
, . . ,
.

. .

- 24.

41J



MySQL. :

. ,
URL-.


.
. ,
" ". ,
, , . , , , .
.


-, . 24.1.

24.1
PHPBookmark.

414

5. MySQL

. , . ,
:
.
.
.
.
. HTML-
.
. ( API .)
, .
;
chapter24 CD-ROM. . 24.1.
24,1 PHPBookmark

bookmarks.sql

SQL- PHPBookmark

login, php

register_form.php

register_new.php

f orgot_form. php

, ,

f orgot_pass wd. php

member.php

add_bm_form.php

add_bms.php

deleie_bms.php

recommend.php

change_pass wd_form .php

change_passwd.php

logout, php

bookmark_fns.php

data_valid_fns.php

db_fns.php

user_auth_f ns .php

url_fns.php

output_fns.php

, HTML-

bookmark.gif

PHPBookmark

24,

41J

MySQL, .
. , , , .
, .

,
magic quotes. , MySQL addslashesl),
stripslashesl). .


PHPBookmark . , . ,
URL- . , . ,
. 24.2.
user
username passwd
laura
luke

email

7cbf26201e73c29b laura@tangledweb.com.au
1fef10690eeb2e59 luke@tangledweb.com.au
bookmark
username bm_URL
laura
laura

http://slashdot.org
http://php.net

24.2 PHPBookmark.
( ), .
(bm_URL).
.
24.1 SQL- , Web.
, !
24.1 bookmark.sql SQL-
create database bookmarks;
use bookmarks ;
create table user (
username varchar(16) primary key,
passwd char(16) not null,
email varchar(lOO) not null

416

5. MySQL

create table bookmark (


username varchar(16) not null,
bm_URL varchar(255) not null,
index (username),
index (bm_URL)
grant select, insert, update, delete
on bookmarks.*
to bm_user@localhost identified by 'password';
, (root) MySQL.
:
mysql -u root -p < bookmarks. sql

.
, , .


login.php, . 24.2.

24.2

login.php

PHPBookmark _

<?

require_once ( "bookmark_fns .php" ) ;


do_html_header ( " " ) ;
display_site_info() ;
display_login_form() ;

do_html_f ooter ( ) ;

, , , API-, .
. ,
( ), HTML-, .
. 24.3.
bookmark fns.php, 24.3.
24.3 bookmarkjfns.php
PHP Bookmark
<?

//
// ,
require_once ( "data_valid_f ns . php" ) ;
require_once ( "db_f ns . php" ) ;
require_once ( "user_auth_f ns . php" ) ;
require_once ( "output_f ns . php" ) ;
require_once ( "url_fns . php" ) ;

24.

41/

JSlS
018 ., Edit. .^iew

$*
Boeki

.Took,

tjelp

a & :a
Stop

Search

ijssj http.//websefveiychaptef24/login,php

24.3

PHPBookmark

HTML
login.php.

PHPbookmark
Store your bookmarks online with) usl
See what other users use!
Share your favorite links with others!

Pass-word; ]

Forgot vour password?

, , .
, .
, . bookmark_fns.php ,
.
, include.
, require_once() , 4.0.112. , require() include() ,
.
outputJFns.php. HTML-. ,
login.php do_html_header(), display_site_info(),
display_login_fonn() do_html_footer(), .
, . do_html_header() 24.4.
24.4 do_html_header() outputjns.php -
,

function do_html_header($title)
// HTML-
<html>
<head>
<titleX?=$title?X/title>
<style>
body { font-family: Arial, Helvetica, sans-serif; font-size: 13px }
li, td { font-family: Arial, Helvetica, sans-serif; font-size: 13px)
hr { color: #3333cc; width=300; text-align=left}
a { color: #000000 }
14 . 216

41

5. MySQL

</style>
</head>
<body>
<img src="bookmark.gif " alt="PHPbookmark logo" border=0
align=left valign=bottom height = 55 width = 57>
<hl>Snbsp ; PHPbookmark</hl>
<hr>
<?

if ($title)
do_html_heading($title) ;

,
. , login. php, .
display_site_info() ; display_login_form()
, . 24.3; do_html_footer()
HTML.
( HTML-
22. , API.
, .)
. 24.3 , , , , . .


: , , . .

,
.
login. php ("Not a
member?"), ,
register_form.php. 24.5.
24.5 register_form.php
PHPBookmark
<?
require_once ("bookmark_fns .php") ;
do_html_header ( "User Registration") ;
display_registration_form() ;
do_html_f ooter ( ) ;

output fns.php. . 24.4.



display_registration_form(), output_fhs.php. Register, register_new.php,
24.6.

24.

Ella fedit Ye*

Fgvorites

Tools

''"" ui:-" :; '7'


:

-<;- ;$top:::<: j:; "Refresh

24.4

,

.

:Home

Search

PHPbookmark
User Registration
'"-:-,
'
"
Ema(Uddrm:

serna me
; chars);

:
Password , --; ';.':C
Confirm pis s
Register

24.6 register_new.php

//
require once("bookmark_fns.php");
// ,
// ,
//
session_start();
//
if (!tilled_out< $HTTP_POST_VARS))
do_htinl_header ("Problem:") ;
echo "You have not filled the form out correctly - please go back"
. " and try again. " ;
do html_f ooter () ;
exit;
//
if (!valid_email($email))
<
do_html_header("Problem:");
echo "That is not a valid email address.
. " and try again. " ;
do html_f ooter () ;
exit;

Please go back

//
if ($passwd != $passwd2)
{
do_html_heading("Problem:");
echo "The passwords you entered do not match - please go back'
." and try again.";
do_htinl_f ooter () ;
exit;

4 .2 U

5. MySQL
II
// ,
// .
if (strlen($passwd)<6 || strlen ($passwd) >16)

do_html_header ( "Problem: " ) ;


echo "Your password must be between 6 and 16 characters."
."Please go back and try again.";
do_html_f ooter ( ) ;
exit;

}
//
$reg_result = register ($username, $email , $passwd) ;
if ($reg_result == "true")
{
//
$valid_user = $username ;
session_register ( "valid_user " ) ;

//
do_html_header ("Registration successful") ;
echo "Your registration" was successful . Go to the members page "
."to start setting up your bookmarks!";
do_HTML_ORL ( "member .php" , "Go to members page") ;
}
else
{
//
//
do_html_header ( " Problem : " ) ;
echo $reg_result;
do_html_footer() ;
exit;
}
//
do_html_f ooter () ;

- .
. (
, ,
20.)
, . :

, .

fiUed_out():
if

( ! f illed_out ( $HTTP_POST_VARS ) )

.
data_valid_fns.php .

:
if

(valid_email ($email) )


data_valid_fns.php.

24.

, :
if (Spasswd != $passwd2)

:
if (strlen($passwd) < 6 || strlen ($passwd) > 16)
,
, 16 ,
.

filled_out()
valid_email() , , 24.7 24.8.
24.7 filled_out() data_valid_fns.php
,

function filled_out($fotm_vars)
{

// ,
foreach ($form_vars as $key => $value)

if (!isset($key) || ($value == ""))


return false ;

return true ;

24.8 valid_email() data_valid_fns.php



function valid_email ($address)
{
//
if (ereg("A[a-zA-ZO-9_]+@[a-zA-ZO-9\-]+\. [a-zA-ZO-9\-\ .]+$", $address) )
return true ;
else
return false ;
filled_out() $HTTP_POST_VARS
$HTTP_GET_VARS. , true, false.
valid_email() , 4 . , true, false.

. 24.6, :
$reg_result = register ($username, $email, $passwd) ;
if ($reg_result == "true")
{

//
$valid_user = $username ;
session_register ("valid_user") ;

422

5. MySQL
II
do_html_header("Registration successful");
echo "Your registration was successful.
Go to the members page "
."to start setting up your bookmarks'";
do_HTML_URL("member.php", "Go to members page");

register() ,
, .

. .
24.5.
ossful - Microsoft Internet Explorer

a Reqistratic
i i'e .' .dit " View
;

Baqk

-'..

Fgvuiites
.':

Joels

Stop '

fclefp

Refresh

. /i^.. v'-'/>! ';( '-


Home '' ;

Searuh

|Address jg] hnp://webseiver/chepter24/register_new.php


~j

24.5


PHPbookmark
Registration successful
Your registration was successful. Go to the members page to start setting
up your bookmaiks!
Go to member? page

register() user_auth_fns.php

24.9.
24.9 register() user_auth_fns.php

function register($username, $email, $password)
//
// true
//
$conn = db_connect();
if (!$conn)
return "Could not connect to database server - please try later.";
//
$result = mysql_query("select * from user where username='$username'");
if (!$result)
return "Could not execute query";
if (mysql_num_rows($result)>0)
return "That username is taken - go back and choose another one.";
// ,
$result = mysql_query("insert into user values
('$username' , password)'$password'), '$email')");

24.
if (!$xesult)
return "Could not register you

4.2 J

in database - please try again later.";

return true;

.
, false. true.
,
db_coimect().
. , . 24.10.
24.10 db_connect() db_fns.php -

MySQL

function db_connect ( )
{
$result = mysql_pconnect ("localhost" , "bm_user" , "password");
if (!$result)
return false ;
if ( ! myeql_select_db ( "bookmarks " ) )
return false ;
return $ result;

, . .


(login.php, . . 24.3)
, member.php.
. , . . 24.11.
24.11 member.php _
//
require_once ( "bookmark_f ns . php" ) ;
session_start() ;
if ($username & $passwd)
//

<

if ( login ($username, $passwd) )

<

// ,
//
$valid_user = $username ;
session_register ( "valid_user " ) ;

424

5. MySQL
else
//
do_html_header ( "Problem : " ) ;
echo "You could not be logged in.
You must be logged in to view this page.";
do_html_ur 1 ( " login . php " , " Login " ) ;
do_html_f ooter ( ) ;
exit;

do_html_header ("Home") ;
check_valid_user ( ) ;
// ,
if ($url_array = get_user_urls ($valid_user) ) ;
display_user_urls ($url_array) ;
//
display_user_menu() ;
do_html_f ooter ( ) ;

20.
-, , . , . :
if ($username && $passwd)
//

if ( login ($username, $passwd) )


{
// ,
//
$valid_user = $username ;
session_register ( " valid_user " ) ;
}

login().
uscr_auth_fns.php .
,
. $valid_user.
, :
do_html_header ("Home") ;
check_valid_user () ;
// ,
if ($url_array = get_user_urls ($valid_user) ) ;
display_user_urls ($url_array) ;
//
display_user_menu () ;
do_html_f ooter () ;

. ,
check_valid_user() user_auth_fns.php,
get_user_urls() url_fns.php display_user_urls() outputjns.php -

24.

check_valid_user() ,
.
,
, .
get_user_urls() ,
display_user_urls()
. check_valid_user()
,

.
member.php display_user_menu().
member.php
. 24.6.

login() check_valid_user(). loginQ 24.12.
24.12 login()
user_auth_fns.php

!
.- ':'

(3 Hume Microsoft Internet Exptomr


pie

&ft View Favbritec lools

I Berk " 1 '

hjelp

R,S;,K

,! Si

!:}^a*M |j hltp //webseivet/chaplerZ^/membarphp


jd': ^S

J^ PHPbookmark
Home
Logged in as laura
Bookmark

Delete?

hltrr//sla5hdol

hllp'.'/mysql Kifn

Home | Add BM I Delete BM I Change oasswofd


Recommend URLs to me 1 LuQoyt

24.6 member.php
, ,
,
.

function login($username, $password)


//
// , true,
// false.
//
$conn = db_connect();
if (!$conn)
return 0;
//
$result = mysql_query("select * frofti user
where username='$username'
and passwd = password('$password')");
if (!$result)
return 0;
if (mysql_num_rows($result)>0)
return 1;
else
return 0;

. ,
true, ,
, false.
check_valid_user() ,
, . , . 24.13.

4.Z

5. MySQL

24.13 check_valid_user() user_auth_fns.php ,

_
function check_valid_user ( )
// , ,
// ,

global $valid_user ;
if (session_is_registered("valid_user") }
{
echo "Logged in as $valid_user . " ;
echo "<br>" ;
else

//
do_html_heading ( " Problem : " ) ;
echo "You are not logged in.<br>";
do_html_url ( "login . php" , "Login" ) ;
do_htrol_f ooter ( ) ;
exit;

, ,
, , .


. 24.6, "Logout".
logout.php. 24. 14.
24.14 logout.pnp _
<?

//
require_once ( "bookmark_f ns . php" ) ;
session_start () ;
$old_user = $valid_user; // , -
$result_unreg = session_unregister ("valid_user") ;
$result_dest = session_destroy () ;
// HTML-
do_html_header ("Logging Out");
if ( ! empty ($old_user) )
{
if ($result_unreg && $result_dest)
{
//
echo "Logged out.<br>";
do_html_url ("login. php" , "Login") ;
}
else
{
//
echo "Could not log you out.<br>";

24.
else
{
// ,
// -
//
echo "You were not logged in, and
so have not been logged
out.<br>";
do_html_url("login.php", "Login");
}
do_html_footer();

E^f Change password -Micrusoft Internet Explotur


: File
.

dit

Beck .'

Vtew

Favorites

:' ..-...""<

H-^USH

loois , fcjeip

Slop.

. Refresh

Home

Search

: ; Address je] p //webser^r/diepter24/chnnge_pssswdjoim.php^j o^Go

^P PHPbookmark
Change password
Logged in as laura

. , 20.



"Change Password", , -

Old password:

Uew password

Change password

Home 1 Add i
1 Chan ) password
Recommend URL? to me 1 Loaoul

-J

. 24.7.
turvunif 24.7


,
, ,
changejasswajorm.php
change_passwd_form.php. < &
. 0.
.
changejpasswd.php, 24.15.
24.15 change_passwd.php
require_once ( "bookmark_f ns . php" ) ;
session_start() ;
do_html_header ("Changing password") ;
check_valid_user () ;
if (!filled_out($HTTP_POST_VARS))
{
echo "You have not filled out the form completely.
Please try again . " ;
display_user_menu() ;
do_html_footer () ;
exit ;
else
if ($new_passwd!=$new_passwd2)
echo "Passwords entered were not the same.
Not changed.";
else if (strlen($new_passwd)>16 || strlen($new_passwd)<6)
echo "New password must be between 6 and 16 characters.Try again.";
else
//
if (change_password($valid_user, $old_passwd, $new_passwd))
echo "Password changed.";
else
echo "Password could not be changed.";

4.2

5. MySQL
display_user_menu();
do_html_footer();

, (
check_valid_user()), (filled_out()), . , change jasswordQ:
if (change_pas sword ($valid_user , $old_passwd, $new_passwd) )
echo "Password changed.";
else
echo "Password could not be changed.";

user_auth_fns.php
24.16.
24.16 change_password() user_auth_fns.php

function change_password($username, $old_password, $new__password)
//
// true false

//
//
//
if
{

,
true,
false
(login ($username, $old_password) )
if ( ! ($conn = db_connect ( ) ) )
return false;
$result = mysql_query( "update user
set passwd = password (' $new_password ')
where username = ' $username ' " ) ;
if (!$result)
return false;
//
else
return true;
//

}
else
return false; //

loginQ. ,
.


,
. , , login.php, "Forgot your password?", . forgot_form.php,
(. . 24.8).
. , .
forgotjasswd.php, . 24.17.

24,

24.8
forgotjbrm.php
,




.

3 Kttp://webs9ivefychaptef24/forgoLfonnphp

PHPbookmark

Reset password
Emeryow ; \ |
Change password

24.17 forgot_passwd.php ,
,

<?
require_once("bookmark_fns.php");
do_html_header("Resetting password");
if ($password=reset__password($username))

<

if (notify_password($username, $password))
echo "Your new password has been sent to your email address." ;
else
echo "Your password could not be mailed to you."
." Try pressing refresh.";

}
else
echo "Your password could not be reset - please try again later.";
do_html_url("login.php", "Login");
do_html_footer();

: reset_password()
notily_password(). .
reset_password() . 24.18.
24.18 reset_password() user_auth_fns.php


function reset_password($username)
//
// false
// 6 13
$new_password = get_random_word(6, 13);

43 U

5. MySQL
II 0 999
//
srand ((double) microtime() * 1000000);
$rand_number = rand(0, 999);
$new_password . = $rand_number;

// false
if (!($conn = db_connect()) )
return false;
$result = mysql_c[uery ( "update user
set passwd = password('$new_password')
where username = '$username'");
if (!$result)
return false; //
else
return $new_password; //

,
get_random_word() 0 999.
get_random_word() user_auth_fns.php.
24.19.
24.19 get_random_word() user_auth_fns.php
,
function get_random_word($min_length, $max_length)
//
//
//
$word = "" ;
$dictionary = "/usr/diet/words";
$fp = fopen($dictionary, "r") ;
$size = filesize($dictionary);

// ispell

//
srand ((double) microtime() * 1000000);
$rand_location = rand(0, $size);
fseek($fp, $rand_location);
//
while (strlen($word)< $min_length || strlen($word)>$max_length)
if (feof($fp))
fseek($fp, 0); // ,
$word = fgets($fp, 80);
// ,
//
$word = fgets($fp, 80); //
$word=trim($word); // \
// fgets
return $word;

. UNIX ispell , /usr/dict/words, .


, , ispell :

24.

4 .3 1

http: //f icus-www. cs .ucla.edu/ficus-members/geof f /ispell-dictionaries .html

( .. ).
, , ,
. , .
, 0 , . , , , fgets().
. -,
, :
if (feof($fp))
fseek($fp, 0); // ,

-, . , .
Sniinjength Smaxjength, .
reset_password().
, . notify_password(), .
notify_password(), 24.20.
24.20 notify_password() user_auth_fns.php

function notify_password($username , $password)
// ,

if ( ! ($conn = db_connect () ) )
return false ;
$result = mysql_query (" select email from user
where username= ' $username ' " ) ;
if (!$result)
return false;
//
else if (mysql_num_rows ($result)==0)
return false; //
else

$email = mysql_result ($result, 0, "email");


$from = "From: support@phpbookmark \r\n" ;
$mesg = "Your PHPBookmark password has been changed to $password \r\n"
."Please change it next time you log in. \r\n" ;
if (mail ($email, "PHPBookmark login information", $mesg, $from) )
return true ;
else
return false;


PHP- mail()
.
, , ,

432

5. MySQL

. "zigzag487"
,
. 0 (
""), 1 1 ( "L").

45000 .

,
, ,
22500000. ,

.


, .

i.mrlrLhir, Mmi.php

PHPbookmark
Add Bookmarks
Logged in as laura.

Add buekmark

| MA BM |
| Change password
Recommsnd URLs to me | Lsaojjl

24.9 addjbmjorm.php
,

.


Add BM .
, . 24.9.
.
. addjbms.php,
24.21.
24.21 add_bms.php

require_once("bookmark_fns.php");
session_start () ;
do_html_header("Adding bookmarks");
check_valid_user();
if (!filled_out($HTTP_POST_VARS))

{
echo "You have not filled out the form completely.
Please try again.";
display_user_menu();
do_html_footer();
exit ;
}
else
{
// URL-
if (strstr($new_url, "http://")===false)
$new_url = "http://".$new_url;

// URL-
if (8fopen($new_url, "r"))
//

24.

43 3

if
(addjbm($new_url) )
echo "Bookmark added.";
else
echo "Could not add bookmark."
}

else
echo "Not a valid URL . " ;
// ,
if ($url_array = get_user_urls ($valid_user) ) ;
display_user_urls ($url_array) ;
display_user_menu() ;
do_html_f ooter ( ) ;

,
.
filled_out() , .
URL-. strstrQ
, http://. , . , . 17, fopenQ URL, http://. ,
, URL- , add_bm()
.
, fopen() , Internet. HTTP- -, fopenQ .
, ,
url_fns.php. add_bm() 24.22.
24.22 add_bm() urHns.php

_
function add_bm($new_url)
{

//
echo "Attempting to add " . htmlspecialchars ($new_url) . "<BR>" ;
global $valid_user;
if (!($conn = db_connect ( ) ) )
return false ;
// ,
$result = my sql_query ("select * from bookmark
where username= ' $valid_user '
and bm_URL= ' $new_url ' " ) ;
if ($result & (raysql_num_rows($result)>0) )
return false ;
//
if (!mysql_query( "insert into bookmark values
( ' $valid_user ' , ' $new_url ' ) " ) )
return false;
return true ;

5. MySQL

. , . ( , ,
, .)
, .
add_bm.php. member.php,
get_user_urls() display_user_urls(). .

member.php add_bm() get_user_urls()


display_user_urls(). , ,
. get_user_urls() url_fiis.php,
a display_user_urls() output_fns.php.
get_user_urls() 24.23.
24.23 get_user_urls() urHns.php

function get_user_urls ($username)


{
// URL-
if (!($conn = db_connect () ) )
return false ;
$result = mysql_query( "select bm_URL
from bookmark
where username = ' $username ' " ) ;
if (!$result)
return false;
// URL-
$url_array = array ();
for ($count = 1; $row = mysql_fetch_row ($result) ; -H-$count)
<
$url_array [$count] = $row[0] ;
}

return $url_array;

. .
URL- false, .
get_user_urls()
display_user_urls(). HTML-,
URL- . . . 24.6. URL- .
URL- , .



Delete BM, , URL-. display_user_urls():
echo

"<tdxinput

type=checkbox name=\"del_me [] \ "


value=\"$url\"X/td>" ;

24.

43 J

delme[]. , , , $del_me, .
Delete BM deletejbms.php, 24.12.
2424 delete_bms.php _
<?

require_once ( "bookmark_f ns . php" ) ;


session_start () ;
do_html_header ("Deleting bookmarks") ;
check_valid_user () ;
if (!filled_out($HTTP POST_VARS
{
echo "You have not chosen any bookmarks to delete.
Please try again . " ;
display_user_menu ( ) ;
do_html_f ooter ( ) ;
exit;
}
lae
{
if (count ($del_me) >0)
{
foraach ($del me as $url)
<
if ( dale te_bm($ valid user, $url) )
cho "Deleted " .htmlspecialchars ($url) . " .<br>" ;
else
echo "Could not delete " .htmlspecialchars ($url) ." .<br>" ;
}
>
else
cho "No bookmarks selected for deletion";
)
// ,
if ($url array = get_user_urls($valid_user) ) ;
display_user_urls ($url_array) ;

display_user_menu ( ) ;
do_html_f ooter () ;

. , , :
foreach($del me as $url)

if (deletejbm($valid_user, $url) )
echo "Deleted " .htmlspecialchars ($url) ." .<br>" ;
else
echo "Could not delete " .htmlspecialchars ($url) ." .<br>";

, delete_bm()
. 24.25.

436

5. MySQL

24.25 delete_bm() urljns.php



function delete bra($user,
f

$url)

// URL-
if (!($conn = db_connect()))
return false;
//
if (!mysql_query ( "delete from bookmark
where username='$user' and bm_url='$url' ") i
return false;
return true;

.
. , " ".
.
. 24.10.
addjbms.php, get_user_urls() display_user_urls().


, , recommend.php.
.
" ". , ,
. ,
.

..//webeet\er/dM4>ter24/delete_bms.pl4J
SQL- .
,
.
Deleting bookmarks
, , MySQL
Logged in as laura
.
Deleted http:Mheaqe.com.au.

Bookmark
Delete?

bllo:/.-sl35lidol c

. htlp.//rrivsgl com

"
:
.
Home | Add BM | DalBle BM I Change password
Recommend URLs to me | Logout
.
, ,
,
24.10
, ,
.
.

24.

43 /

:
select distinct (2 .user-name)
from bookmark , bookmark 2
where .username='$valid_user'
and bl.username != b2.username
and bl.bm_ORL = b2.bm_URL


, . , 2. . .
(bl.username), (URL-),
(bl.bm_URL = b2.bm_URL).
(bl.username != bl.username).
,
. ,
:
select bm_URL
from bookmark
where username in $sim_users
and bm_URL not in $user_urls
group by bm_URL
having count(bm_URL)>$popularity

$sim_users .
$user_urls
, . , Spopularity " " . URL-, .
,
Spopularity, URL-,
.
Web.
24.26
24.27. recommend.php (. 24.26).
reconunend_urls() url_fns.php (. 24.27).
24.26 recommend.php ,

<?

require_once("bookmark_fns.php");
session_start();
do_html_header("Recommending URLs");
check_valid_user();
$urls = recommend_urls($valid_user);
display_recommended_urls($urls);

display_user_menu();
do_html_footer();

438

5. MySQL

24.27 recommend_urls() urljfns.php



function recommend_urls ($valid_user, $popularity = 1)
{
//
// . URL-,
// ,
//
//
if (!($conn = db_connect()))
return false;
// ,
//
if (!($result = mysql_query("
select distinct(2.username)
from bookmark , bookmark 2
where .username='$valid_user'
and .username != b2.username
and bl.bm_URL = b2.bm_URL
")))
return false;
if (mysql_num_rows($result)==0)
return false;
//
// URL- IN
Srow = mysql_fetch_object($result);
$sim_users = "('"($row->username)."'";
while ($row = mysql_fetch_object($result))
{
$sim_users .= ", '".($row->username)."'";
}
$sim_users .= ")";
// URL-
// ,
if (! ($result = mysql_query("
select bm_URL
from bookmark
where username='$valid user'")))
return false;
// URL-
// IN
$row = mysql_fetch_object($result);
$user_urls = " (' ". ($row->bm_URL) ."'";
while ($row = mysql_fetch_object($result))
{
$user_urls .= " , '". ($row->bm_URL) ."'";
}
$user_urls .= ")";
//
//
//
//
//
//



URL-

$popularity = 1,
,

24.
// URL-
if (! ($result = mysql_guery("
select bm_URL
from bookmark
where username in $sim_users
and bm_URL not in $user_urls
group by bm_URL
having count(bm_ORL)>$popularity
")))
return false;
if (!($num_urls=mysql_num_rows($result)))
return false;
$urls = array () ;
// URL-
for ($count=0; $row = mysql_fetch object($result); $count++)
{
$urls[$count] = $row->bm_URL;
}
return Surls;

recommend.php . 24.11.

Peiiesh

Home

)http://webserver/cnapter24/recommend.php

PHPbookmark
24.11
,

pets.com.


slashdot.org.

Recommending URLs
Logged in as laura.
Recommendallom
hlto://Dels com
Home | Add BM | : ,i i,
Recommend URLs to me I

,\ Chanoe password

Search

43;/

5. MySQL


PHPBookmark.
:

"Add this to my bookmarks" (


)

, URL-

""


! !


,
,
.

25

(shopping cart).
Book-O-Rama, 2.

.
(
, , shopping basket)
.
( ).
, , .

:
,


,
,
,

44 .Z

5. MySQL

, Book-O-Rama, . . :
. ,
.
. .

,
.

Book-O-Rama.
.


Book-O-Rama . .
, .
, , ..
, MySQL ,
- .


.
,
.
, . , , ,
.

. ,
.
,
,
.

25.

44 J

,
. .
. .
,
.

.
, , .
, . ,
.
.
, , .
.
(,
), ( ,
), .
. , .


, ,
,
.
(, ). ,
, .
, , , . , ,
,
.
. .


.
: . - . . 25.1 . 25.2.

444

5. MySQL

^-

>

. 25.1 Book-O-Rama , .

25.2 Book-O-Rama
, .

. 25.1 . , . ,
.
.
.

25.

44 J

. 25.2 . ,
. .
.
- ,
, . , , .
:

.
( ,
.)

.
, .
API- , . , HTML, .
, , .
, Book-O-Rama.
book_sc (Shopping Cart) , , 2.
CD-ROM. . 25.1.
25.1 Shopping Cart

index.php

.
.

show_cat.php

show_book.php

show_cart.php


. ,

.

checkout.php

purchase.php
process.php
login.php


.
.

.

.

.

44

5. MySQL

logout.php

admin.php

change_password_form.php

,
.

change_password. php

insert_category_form.php

,

.

insert_category.php

insert_book_form. php

,
.

insert_book.php

edit_category_form.php

,
.

edit_category.php

edit_book_form. php

,
.

edit_book.php

delete_category. php

delete_book.php

book_sc_fns.php

admin_fns.php

,
.

book_fns.php

order_fns.php

output_fns.php

HTML.

data_valid_fns.php

db_fns.php


book_sc.

user_auth_fns.php

book_sc.sql

SQL

SQL-
book_sc.

populate.sql

SOL

SQL-
book sc.

25.

44 /

.
, (
) , . , .
, magic
quotes. , addslashesl) MySQL , stripslashesO. .
magic quotes .htaccess:
php_value magic_quotes_gpc on ( PHP 4)

php3_magic_quotes_gpc on ( PHP 3)


, Book-O-Rama, 2,
.
SQL- book_sc 25.1.
25.1 book_sc.sql SQL- book_sc
create database book_sc;
use book_sc;
create table customers
(
customerid int unsigned not null auto_increment primary key,
name char (40) not null,
address char(40) not null,
city char(20) not null,
state char(20),
zip char(10),
country char(20) not null
);
create table orders
(
orderid int unsigned not null auto_increment primary key,
customerid int unsigned not null,
amount float(6,2),
date date not null,
order_status char(10),
ship_name char(40) not null,
ship_address char(40) not null,
ship_city char(20) not null,
ship_state char(20),
ship_zip char(10),
ship_country char(20) not null
);

44

5. MySQL

create table books


(
isbn char (13) not null primary key,
author char(30),
title char(60),
catid int unsigned,
price float(4,2) not null,
description varchar(255)
);
create table categories
(
catid int unsigned not null auto_increment primary key,
catname char(40) not null
);
create table order_items
(
orderid int unsigned not null,
isbn char(13) not null,
item_price float(4,2) not null,
quantity tinyint unsigned not null,
primary key (orderid, isbn)
);
create table admin
(
username char(16) not null primary key,
password char(16) not null
>;
grant select, insert, update, delete
on book_sc. *
to book_sc@localhost identified by 'password';

Book-O-Rama , , .
, :
, .
. , .
, .
.
order_items itemjrice ( ), . ,
.
admin .
. , .
, MySQL book_sc.sql, (root):

25.

44

mysql -u root -p < book_sc. sql

( .)
book_sc (
password).
, populate.sql. , MySQL.


, : , .
index.php . 25.3.
, ( ) .
,
.
,
, show_cat.php. , Internet, . 25.4.
Internet . ,
(. . 25.5).
View Cart ( ) Add to
Cart ( ), . ,
.
.

Ble tfit ^3ew Favorites : lools .


-. '%:;^"'1

Back

25.3


,

.

15 . 216

.-.

jflk-O-R.

Welcome to Book-O-Rania
Please cliuose a category:
Internet
Self-help
Gardening

'

' '&

.Mai! .,;,.'. Prim

Total Items = QV -?I8W

4JU

5. MySQL

Fonrd

Step

;*

Mime

;.

'-'* ' -' ....... '--' .............. ai._-..~.

3 hp-.//webservor/chepterZ5/sho_cphp?aied-1

25.4

PHP end MwSQL Web DevEloDment bv Luke Wellina and La'jra Thomson

Sams Teath Yomself PHP4 in 11 Hours by Mall Zandilta

tile

t,d,l View (%,ni,i,,.,

Tuult,

Help

Total Items-
Total Pto = SO.OO '

PHP and MySQL Web Development


25.5.

,
.

Author: Luke Welling and Laura Thomson


ISBN: 06721742
Our Price: 49 99
DescrlpUon: PHP 8. MySQL Web Development teaches the reader to develop dynamic, ecornmerce web sites. You will learn lu integrals and implement these technologies by following
teal-world examples and working through sample projects.

25.

451


, index.php, (.
25.2).

<?

25.2

index.php

include ( ' book_sc_f ns . php ' } ;


//
session_start() ;
do_html_header ( "Welcome to Book-O-Rama") ;
echo "<p>Please choose a category :</p>";
//
$cat_array = get_categories () ;
//
display_categories ($cat_array) ;
//
// , ,
//
if (session_is_registered( "admin user") )
{
display_button ("admin. php" , "admin-menu", "Admin Menu");
}
do html footer () ;

book_sc_fns.php,
.
,
.
.
HTML-,
do_html_header() do_html_footer() ( output_fns.php).
, , . .
, .
:
//
$cat_array = get_categories () ;
//
display_categories ($cat_array) ;
get_categories() display_categories() , , book_fns.php output_fns.php. get_categories()
, display_categories(). get_categories() 25.3.

452

5. MySQL

25.3 get_categories() outputjns.php



_
_
function get_categories ()

//
$ = db_connect() ;
$query = "select catid, catname
from categories";
$result = @niysql_query ($guery) ;
if (!$result)
return false ;
$num_cats = @mysql_num_rows ($result) ;
if ($num_cats =0)
return false;
$result = db_result_to_array ($result) ;
return $result;

.
db_result_to_array() db_fhs.php (. 25.4). MySQL ,
.
25.4 db_result_to_array() db_fns.php

MySQL

_
function db_result_to array ($result)
{
$res_array = array () ;
for ($count=0; $row = @mysql_fetch_array ($result) ; $count++)
$res_array[$count] = $row;
return $res_array ;

index. php,
display_categories() output_fns.php. , . 25.5.
25.5 display_categories() outputjns.php

_
function display_categories ($cat_array)
{
if ( ! is_array ($cat_array) )
{
echo "No categories currently available<br>" ;
return ;
}
echo "<ul>" ;
foreach ($cat_array as $row)
{
$url = "show_cat.php?catid=" . ($row[" catid"] ) ;
$title = $ row ["catname"] ;
echo "<li>";

25.

.3

do_html_url($url, $title);
}
echo "</ul>";
echo "<hr>";

. , show.cat.php, ,
(catid). ( , MySQL
.)
,
.



. show_cat.php, 25.6.
25.6 show_cat.php

<?

include ( ' book_sc_f ns . php ' ) ;


//
session_start() ;
$name = get_category_name ($catid) ;
do_html_header ($name) ;
//
$book_array = getjbooks ($catid) ;
display_books ($book_array) ;
// ,
//
if (session_is_registered("admin_user") )
{

display_button ("index. php" , "continue", "Continue Shopping");


display button ("admin. php" , "admin-menu", "Admin Menu") ;
display~button ("edit_category_form.php?catid=$catid" , "edit-category" ,
"Edit Category") ;

else

display_button("index.php", "continue-shopping" , "Continue


Shopping") ;

do_html_footer () ;

, .

session_start(), get_category_name()
:
$name = get_category_name ($catid) ;

. 25.7.

JT

5. MySQL

25.7 get_category_name() book_fns.php



function get_category name ($catid)
{
//
$conn = db_connect() ;
$query = "select catname
from categories
where catid = $ cat id" ;
$result = @mysql_query ($query) ;
if (!$result)
return false ;
$num_cats = @mysql_num_rows($result) ;
if ($num_cats =0)
return false ;
$result = mysql_result ($result, 0, "catname") ,return $ result;

HTML-
, :
$book_array = getjbooks ($catid) ;
display_books ($book_array) ;

get_books() display_books()
get_categories() display_categories(), . , ,
.
display_books()
show_book.php. -, . ISBN .
show_cat.php
, . , .


showjbook.php ISBN , . 25.8.
25.8 show_book.php

_
<

'
~~~
~
include ( ' book_sc_f ns . php ' ) ;
//
session_start() ;

//
$book = get_book_details($isbn) ;
do_html_header <$book ["title" ] ) ;
display_book_de tails ($book) ;
// URL- "continue"
$target = "index. php" ;
if ($book[" catid"])
{
$target = "show_cat.php?catid=" . $book[" catid" ];

25.
//
// ,
if( check_admin_user ( ) )

display button ( "edi t_book_f orm . php?isbn=$isbn" , "edit-item", "Edit


Item") ;
display_button ("admin. php" , "admin-menu", "Admin Menu");
display_button($target, "continue", "Continue");
)
else
{
display_button ("show_cart.php?new=$isbn" , "add-to-cart" ,
"Add " .$book[" title"] . " To My Shopping Cart") ;
display_button($target, "continue-shopping" , "Continue Shopping");
}
do html_footer () ;

.
, :
$book = get_book_details($isbn) ;

. HTML
:
display_book_details($boolc) ;

, display_book_details()
, images/Sisbn.jpg. , .
. "Continue Shopping" ( ), , Add to Cart . ,
.
. .


Scart.
, ISBN , . , , :
0672317842 => 1

, .
$cart
.
, Total Items ( ) Total Price ( ) , Sitems $total_price.

45v)

5. MySQL

show_cart.php
show_cart.php.
, View Cart Add
to Cart. show_cart.php , . ISBN,
.
. 25.6.
View Cart , .
, .
. 25.7 , .
Add to Cart , show_book.php , (
). URL-,
, . new
0672317842 ISBN ,
.
*' .

.,,,,

-^

Beck- HewajL*

3ii.'(.i

;^,'it}^t

^.,

ii

<s-'t4L.ii t-^u:t!,ti

-J^

Hrsl-.sy

-,V

Mnti

'^ '

} *

25.6
show_cart.php,

,

.

25.7
show_cart.php
new

.

-I'rtm

"<

'

Your shopping cart


There are no item? it your can

Your shopping carl


Total

' *-

Sam;Taacti Vpuisetf PHP4 in 24 Houre by Matt Zsnds

PHP and MySQL Web De^lopme^l by UA* WeUing and Ujla Ttiomsa

S24.99

M9-99
748

25.

. Save Changes ( ) Go To Checkout ( ). . Quantity Save


Changes. , , show_cart.php .
, .
.
show_cart.php, 25.9.
25.9 show_cart.php

<?

include ('book_sc_fns.php');
//
session_start() ;
if ($new)
{
//
if {!session_is_registered("cart"))

$cart = array () ;
session_register("cart");
$items = 0;
session_register("items");
$total_price = "0.00";
session_register("total_price");

if($cart[$new]>
$cart[$new]++;
else
$cart[$new] = 1;
$total_price = calculate_price($cart);
$items = calculate_iterns($cart);

if($save)

foreach

($cart as $isbn => $qty)

if($$isbn=="0")
unset($cart[$isbn]);
else
$cart[$isbn] = $$isbn;

$total_price = calculate_price($cart);
$items = calculate_iterns($cart) ;

}
do_html_header("Your shopping cart");
if($cartSSarray_count_values($cart))
display_cart($cart);

else
{

echo "<p>There are no items in your cart" ;


echo "<hr>";

$target = "index.php";

5. MySQL
II ,
//
if ($new)

$details =
get_book_details ($new) ;
if ($details ["oatid" ] )
$target = "show cat.php?catid=" . $details ["catid"] ;

>

display_button($target, "continue-shopping" , "Continue Shopping")


$path = $PHP_SELF;
$path = str_replace("show_cart.php" , "", $path) ;
display_button ("https : //" . $SERVER_NAME . $path. "checkout .php" ,
"go-to-checkout" , "Go To Checkout");
do_html_f ooter ( ) ;

: , .
.


,
. View Cart :
if ($cart&&array_count_values ($cart) )
display _cart($cart) ;
else
{
echo "<p>There are no items in your cart" ;
echo "<hr>" ;
}

, , display_cart(). , .
display_cart() HTML,
. 25.6 25.7. outputjns.php 25.10. , .
25.10 display_cart() outputjns.php

_
function display_cart($cart, $change = true, $images = 1)
{
//
// (true false)
// (1 , 0 )
global $ i terns ;
global $total_price;
echo "<table border = 0 width = 100% cellspacing = 0>
<form action = show_cart . php method = post>
<trXth colspan = ". (l+$images) ." bgcolor=\"#cccccc\">Item</th>
<th bgcolor=\ " #cccccc\ " >Price</thXth bgcolor=\ " #cccccc\ " >Quantity</th>
<th bgcolor=\"#cccccc\">Total</thX/tr>" ;

25.
//
foreach ($cart as $isbn => $qty)
$book = get_book_details($isbn);
echo "<tr>";
if($images ==true)
echo "<td align = lef t>" ;
if (file_exists("images/$isbn.jpg"))
$size = GetImageSize("images/".$isbn.".jpg");
if ($size[0]>0 && $size[l]>0)
echo "<img src=\"images/".$isbn.".jpg\" border=0 " ;
echo "width = ". $size[0]/3 ." height = " .$size[l]/3 . ">";
else
echo "Snbsp;";
echo "</td>";
echo "<td align = lef t>" ;
echo "<a href = \"show_book.php?isbn=".$isbn."\">"
.$book["title"]."</a> by " .$book["author"];
echo "</tdXtd align = center>$".number_format($book["price"], 2) ;
echo "</tdXtd align = center>";
// ,
//
if ($ change == true)
echo "<input type = text name = \"$isbn\" value = $qty size = 3>";
else
echo $qty;
echo "</tdXtd align = center>$".number_format($book["price"]*$qty,2)
."</tdX/tr>\n";
//
echo "<tr>
<th colspan = ". (2+$images) ." bgcolor=\"#cccccc\">finbsp;</td>
<th align = center bgcolor=\"#cccccc\">
$ items
</th>
<th align = center bgcolor=\"#cccccc\">
\$".number format($total_price, 2).

//
if ($ change == true)
{
echo "<tr>

<td colspan = ". (2+$images)


<td align = center>
<input type = hidden name
<input type = image src =
border = 0 alt =
</td>
<td>Snbsp;</td>

echo "</f ormX/table>" ;

. ">Snbsp;</td>
= save value = true>
\"images/save-changes.gif\"
V'Save Changes\">

4C)U

5. MySQL

, :
1. TSBN
get_book_details(),
.
2. , . ,
. ,
, . (
, gd, 19, .)
3. . showjbook.php ISBN
.
4. , Schandc true
( true ), . ,
Save Changes. ( , .)
, . .


show_cart.php Add To
Cart,
. , .
-, ,
, :
if(!session_is_registered("cart"))
{
$cart = array 0;
session_register("cart");
$items = 0;
session_register("items");
$total_price = "0.00";
session_register("total_price");
}

.
-, , , :
if ($cart[$new])
$cart[$new]++;
else
$cart[$new] = 1;

, . ,
.
.

25.

-,
. calculate_price() calculate_items():
$total_price = calculate_price ($cart) ;
$items = calculate_i terns ($cart) ;

book_fhs.php. , , 25.11 25.12.


25.11 calculate_price() book_fns.php

_
function calculate_price ($cart)
{
//
$price = 0.0;
if (is_array ($cart) )
{
$conn = db_connect() ;
foreach($cart as $isbn => $qty)
{
$query = "select price from books where isbn= ' $isbn ' " ;
$result = mysql_query ($query) ;
if ($result)
{
$item_price = mysql_result ($result, 0, "price");
$price +=$item_price*$qty;

return .$price;

, calculate_price()
, . , ,
, , ( )
. , .
25.12 calculate_items() book_fns.php

function calculate_i terns ($cart)


{
//
$items = 0;
if (is_array ($cart) )
{
foreach($cart as $isbn => $qty)
{
$i terns += $qty;
}
}
return $items ;
}
_

calculate_items() .

5. MySQL


show_cart.php Save Changes, . . , Save Changes
. save.
, ,
Save Changes. , ,
.
ISBN , :
echo "<input type as text name = \"$isbn\" value = $qty size = 3>" ;

, :
if ($save)

foreach ($cart as $isbn => $qty)


{
if ($$isbn=="0")
unset ($cart [$isbn] ) ;
else
$cart[$isbn] = $$isbn;
}
$total_price = calculate_price ($cart) ;
$items = calculate_i terns ($cart) ;

Sisbn
.
SSisbn ( ).
( 1.) ,
SSisbn , Sisbn.
Save Changes.
0, unset().
:
if ($$isbn="0">
unset ($cart [$isbn] ) ;
else
$cart[$isbn] = $$isbn


calculate_price() calculate_items() Stotal_price Sitems.


, .
Stotal_price Sitems do_html_header().
,
show_cart.php. , , .
do_html_header() :

25.
if(!$items) $items = "";
if (!$total_price) $total_price

'0.00'


Go to Checkout (
), cheekout.php.
SSL,
. ( SSL 15.)
. 25.8.
, ( ,
). , ,
25.13.
25.13 cheekout.php
//
include ('book_sc_fns.php ') ;
//
session_start() ;
do_html_header("Checkout");
if($cartSarray_count_values($cart))
display_cart($cart, false, 0);
display_checkout_form($HTTP_POST_VARS);
else
echo

"<p>There are no items in your cart";

display_button("show_cart.php",
Shopping");

"continue-shopping"

"Continue

do html footer();

Total.flem
Toul Price l

Checkout
25.8
cheekout.php

.

Sams PHP4 In 24 Hauls by MM Sndstra


PHP apd MySQL Web DevBluDmert by Lithe Welling and Laura T)iom30l

G4.99
(4999

".

Name
Address
Cily/Suhutb
Stale/
Postal Code cr Zip Coda
Country

-.
Name

1
1

24.9
49 99

trtae

464

5. MySQL

. ,
. , .
25.8.
Purchase , purchase.php. . 25.9.

tWe

1-'';1-;:;:':

"

''''^ ' 1-
;

-'

HstGfy

Prift

^ https://webseiver/chopter25/puidiHse ptip

25.9
purchase.php


,

.

Checkout
Sams Teach Yourself PHP4 in 24 Hpufs by Malt Zandslra
PHP and MySQL Wpb Developrnpm by L(jVs Wpllir.g and Laura Thorn
Shipping
TOTAL INCUJBlNQ SHIPPING
Credit Card Detail
Type
Number
AMEX cods (if required)
EpiryDat8
Name on Card

[jane Doe

Please press Purchase to

e Shopping to add or remove

$ *

checkout.php .
25.14.
25.14 purchase.php

include ('book_sc_fns.php');
//
session_start();
do_html_header("Checkout");
//
!

if($from== process'||$cart&S$namefiS$addressSS$citySS$zipSS$country)
//
if($from!='process')
if(!insert_order($HTTP_POST_VARS))
echo "Could not store data, please try again.";
displayjbutton("checkout.php", "back", "Back");
do_html_footer();
exit;
// ,
//
display_cart($cart, false, 0);
display_shipping(calculate_shipping_cost());

25.
//
display__card_form ($HTTP_POST_VARS) ;
display_button("show_cart.php", "continue-shopping",
"Continue Shopping");
}
else
i
echo "You did not fill in all the fields, please try again.<hr>"
echo "<form action = ' checkout.php' method = post>";

// , ,
//
foreach($HTTP_POST_VARS as $name => $value)
echo "<input type = hidden name = $name value = '$value'>\n";
ft
display_form_button("bac)c", "Back") ;
echo "</form>";

)
do_html_footer () ;

: , ,
insert_order().
, . 25.15.
25.15 insert_order() order_fns.php

function insert_order($order_details)
{
global $total_price;
global $cart;
//
extract($order_details);
// ,
if(!$ship_name&&!$ship_addressS&!$ship_cityS5
!$ship_stateSS'$ship_
zipSS!$ship_
country)
{
$ship_name = $name;
$ship_address = $address;
$ship_city = $city;
$ship_state = $state;
$ship_zip = $zip;
$ship_country = $country;
!
$conn = disconnect() ;
//
$query = "select customerid from customers where
name = '$name' and address = '$address'
and city = '$city' and state = '$state'
and zip = '$zip' and country = '$country'";
$result = mysql_query($query);
if(mysql numrows($result)>0)
<
$customer_id = mysql_result($result, 0, "customerid");

466

5. MySQL
else
{
$query = "insert into customers values
',
'$name','$address','$oity','$state','$zip','$country')";
$result = mysql_query($query);
if (!$result)
return Calse;
}
$query = "select customerid from customers where
name = '$name' and address = '$address'
and city = '$city' and state = '$state'
and zip = ' $zip' and country = ' $country'" ;
$result = mysql_query($query);
if (mysql_nutnrows ($result) >0)
$customerid = mysql_result($result, 0, "customerid");
else
return false;
$date = date("Y-m-d");
$query = "insert into orders values
(", $customerid, $total_price, '$date', 'PARTIAL',
'$ ship_name',
1
$ship_address','$ship_city','$ship_state','$ship_zip',
'$ship_country')";
$result = mysql_query($query);
if (!$result)
return false;
$query = "select orderid from orders where
customerid = $customerid and
amount > $total_price-.001 and
amount < $total_price+.001 and
date = '$date' and
order_status = 'PARTIAL' and
ship_name = '$ship_name' and
ship_address = '$ship_address' and
ship_city = '$ship_city' and
ship_state = '$ship_state' and
ship_zip = '$ship_zip' and
ship country = '$ship_country'";
$result = mysql_query($query);
if(mysql_numrows($result)>0)
$orderid = mysql_result($result, 0, "orderid");
else
return false;
//
foreach($cart as $isbn => $quantity)
{
$detail = get_book_details($isbn);
$guery = "delete from order_items where
orderid = $orderid and isbn = '$isbn'";
$result = mysql_query($query);
$query = "insert into order_iterns values
C$orderid', '$isbn', ".$detail["price"].", $quantity) '
$result = mysql_query($query);
if (!$result)
return false;
}
return $orderid;

4 /

25.

, , , .

:
display_shipping(calculate_shipping_cost());
(calculate_shipping_cost())
$20. ,
.
, display_card_fonn() output_fns.php


Purchase,
process.php.
. 25.10.
Bin

Ed*

at

.
; ^.

Checkout
25.10

., ir)t
SamsTe.ch YourilfPHP< in'24 Hour bj Ms Z.nd.lr.

..

D4.99
W993

" "

QOwitlty
1 "
<

'

Tettl
24.99
3-99

Thanhyou for shopping wtlh us. Your order has bean placed.

process.php 25.16.
25.16 process.php

include ('book_sc_fns.php');
//
session_start() ;
do_html_header("Checkout");
if($cartSS$card_type&S$card_numberSS$card_monthSS$card_yearSfi$card_name )
// ,
//
display_cart($cart, false, 0) ;

468

5. MySQL

display_shipping(calculate_shipping_cost() ) ;
if (process_card($HTTP_POST_VARS) )
{
//
session_destroy() ;
echo "Thank you for shopping with us.
Your order has been placed.";
display_button("index.php" , "continue-shopping" , "Continue Shopping")
}
else
{
echo "Could not process your card, please contact the card issuer or
try again . " ;
display_button ("purchase. php" , "back", "Back");

}
}

else
{
echo "You did not fill in all the fields, please try again. <hr>";
echo "<form action = 'pur chase. php' method = post>" ;
echo "<input type = hidden name = from value = process>\n" ;
// ,
//
foreach($HTTP_POST_VARS as $name => $value)
echo "<input type = hidden name = $name value = ' $value ' >\n" ;
display_form_button("back" , "Back") ;
echo "</form>" ;

}
do_html_footer () ;

, , :
if (process_card($HTTP_POST_VARS) )
{
/ /
session_destroy () ;
echo "Than kyou for shopping with us.
Your order has been placed.";
display_button ("index. php" , "continue-shopping", "Continue Shopping");
}

, $HTTP_POST_VARS,
(track_vars). . .
true.
,
. :
. , . . . ,
, . .
.

25.

469

, , PGP GPG, 15.


.

.
, .
15.


.
Web- , . , 24.
.
,
login.php, , admin.php.
. 25.11. ( login.php 24. CD-ROM.)
. 25.12.

25.11

25.12

Administration
Gcitaffiain alie
Add ne-.v caieoor
Adfl j na

/U

5. MySQL

25.17.
25.17 admin.php

//
require_once ( "book_sc_f ns . php" ) ;
session_start() ;
if ($username &S $passwd)
//
{

if (login ($username, $passwd) )


{
// ,
//
$admin_user = $username ;
session_register ("admin_user") ;
}
else
{

//
do_htrol_header ( " Problem : " ) ;
echo "You could not be logged in.
You must be logged in to view this page.<br>"
do_html_url ("login, php" , "Login") ;
do_html_f ooter ( ) ;
exit;

do_html_header ( "Administration" ) ;
if (checJc_admin_user ( ) )
display admin_menu ( ) ;
else
echo "You are not authorized to enter the administration area.
do_html_f ooter ( ) ;

24.
24 .
-
Sadminjuser check_admin_user().
, ,
admin_fns.php.
, insert_category_form.php insert_book_form.php. . (insert_category.php insert_book.php), ,
, . , ,
.
insertjbookjbrm.php . 25.13.

25.

; .* mm
1 I 11
:>.;

25.13



.

Add a book

Slop

',:.,

471

* Fw

-0-Ri

ISBNBook Title

Book Author |
Category: | Internet
Price:

Description

, Category HTML- SELECT.



get_categories().
Add Book ( )
insertjbook.php. 25.18.
25.18 insert_book.php -

_ _
//
require_onoe ( "book_sc_f ns . php" ) ;
session_start() ;
do_html_header ( "Adding a book") ;
if (checJc_admin_user() )

if (filled_out($HTTP_POST_VARS))
{

if (insert_book($isbn, $title, $author, $catid, $price, $description) )


echo "Book '$title' was added to the database . <br>" ;
else
echo "Book '$title' could not be added to the database . <br>" ;

}
else
echo "You have not filled out the form.
Please try again.";
do_html_url( "admin. php", "Back to administration menu") ;
}
else
echo "You are not authorised to view this page.";

do_html_f ooter ( ) ;

, insert_book().
, ,
adminjfhs.php.

4 / 2i

5. MySQL

, .

. Go to main site ( ) , (
index.php). , . .
.
, , $admin_user.
, show_book.php . . 25.14.
: Edit
Item ( ) Admin Menu ( ). ,
Log Out (
).
( 25.8):
if( check_admin_user )
{
display_button("edit_book_form.php?isbn=$isbn",
"edit-item", "Edit Item");
displayjbutton("admin.php", "admin-menu", "Admin Menu");
display button($target, "continue", "Continue");
}

show_cat.php, , .
Edit Item, edit_book_form.php. . 25.15.

E*

Vim,

Foun

. 1 ,

Back

Stop

Help

^ '"&

Ftelrosh

Home

p
Him

> J3 https-.//webserver/chaptetES/stiow.baoKp

25.14

show_book.php

.

PHP and WSySQL Web Development


Author: Luke Welling and Laura Thomson
ISBH: 0672317642
Our Price: 49 39
Description: PHP & MySQL Web Development leachus the reader tctdevelop dynamic, secure
commerce web sites. You will learn to integrals and implement these technologies by following
reat-woild examples and wording through sample projects.

25.

.;- !,
. 1 ,V

'I

Ll

i5 i

:il

vj |

,J

if .

|) hps.7/websawe^i*optef25/ecjitbookjomi.php7isbn-a672317e42

25.15

edit Jbookjorm. php

,
.

473

>0

Edit book details

ISBN:

|0672317842

Book Title:

|PHP and MySQL Webl

Book Author

[uuke Welling and Laura

Category:

llntemet

Price:

J49.99

Description;

JPHP & MySQL Web Development teaches the ceadec to


develop dynamic, secure e-commecce web sites. You ^
[will learn to integrate and implement these

['%: k

^|

]5;::teefe;book:fj

Back lo 3dministfa(jgn

, ,
. . . 25.19.
25.19 display_book_form() adminjns.php

function display_book_form($book = "")
// .
// .
//
// .
// .
// $edit false
// insert_book.php.
// ,
// .
//
// update_book.php.
// , "Delete book".
II ,
//
$edit = is_array ($book) ;
// HTML-
// -
<form method=post
action="<?=$edit?"edit_book.php":"insert_book.php"
<table border=0>
<tr>
<td>ISBN:</td>
<toXinput type=text name=isbn

4/4

5. MySQL
value="<?=$edit?$book["isbn"]:""; ?>"x/td>
</tr>
<tr>
<td>Book Title:</td>
<tdxinput type=text name=title
value="<?=$edit?$book["title"]:""; ?>"X/td>
</tr>
<tr>
<td>Book Author:</td>
<tdxinput type=text name=author
value="<?=$edit?$book["author"]:""; ?>"X/td>
</tr>
<tr>
<td>Category:</td>
<tdxselect name=catid>
<?
//
$cat_array=get_categories() ;
foreach ($cat_array as $thiscat)
{
echo "<option value=V";
echo $thiscat["catid"];
echo "\"" ;
// ,
//
if ($edit ss $thiscat["catid"] == $book["catid"])
echo " selected";
echo ">";
echo $thiscat["catname"];
echo "\n";
}
?>
</select>
</td>
</tr>
<tr>
<td>Price:</td>
<tdXinput type=text name=price
value="<?=$edit?$book["price"] : "" ; ?>"X/td>
</tr>
<tr>
<td>Description:</td>
<tdxtextarea rows=3 cols=50
name=description>
<?=$edit?$book["description"]:""; ?>
</textareaX/td>
</tr>
<tr>
<td <? if (!$edit) echo "colspan=2"; ?> align=center>
<?
if ($edit)
// ISBN,
// ISBN
echo "<input type=hidden name=oldisbn
value=\"".$book["isbn"]."\">"
>>
<input type=submit
value="<?=$edit?"Update":"Add"; ?> Book">
</formX/td>
<?
if ($edit)

25.

4 /J

echo "<td>" ;
echo "<form method=post action=\"delete_boolc.php\">" ;
echo "<input type=hidden name=isbn
value=\"" . $book["isbn"] . " \">"
echo "<input type=submit
value=\ "Delete book\">";
echo "</formX/td>" ;
</td>
</tr>
</table>
</form>

, ,
, :
<input type=text name=price
value="<?=$edit?$book ["price"] :""; ?>">

. , , . editjbook.php deletejbook.php, .
, , , . ,
, . (
.) ,
7. , , ,
"". , .
. , CD-ROM.


. :
. .
. , .
,
.

. ,
.

476

5. MySQL

, ,
, , ,
.. .


, -
. FishCartSQL. :
http://www.fishcart.org/

, , , ,
. ( ) 3
PHPLib.
, - , .
.



.
, , .

, ,
.

Web-, ,
,
.
, .
:
Web-
,

, Web-
SuperFastOnlineNews -. , .
.
SuperFastOnlineNews . . , , ,
Web-,

47

5. MySQL


, ,
.


, :
,
,


-, ,
.


.
.

FTP
FTP- Web-.
. ( ). Web ,
-.
FTP . .


16, HTTP-
Web-. .
,
.
, .
.
.



. , .

26.

, . Web- -
, , . , , , ,
. ,
,
.


.
, . MySQL , . ,
(BLOB) MySQL .
. <IMG
SRO .
, . ,
,
.
. 26.1.
pictures/
/

ajs23.jpg

26.1


.

cp331.jpg, clo95.jpg

d/

dd332.jpg

xz113.jpg

yw632.jpg, yo224.jpg, yz775.jpg

, . , 10000 26 .
400 . , 10000
. , , .
. 26.1 ,
.


, - . ,
. ,
.

0U

5. MySQL

, , .
.
.
. .
,
,
, .

. ,
.
.


, , . .
, . ,
.
, , . , .

. . .

, "" ,
1 10.
, .
, , .
, .
HTML- <> XML . .


, . , . , ,
, . , .

26.

4 1

. 26.2 ,
<TABLE>

<TRxTD COLSPAN=2>TOP <></>

<TRxTD>
26.2

.

Side menu
</TDxTD>

MAIN CONTENT CELL

</>

, , ?
.
, ,
, . HTML- <TD>,
. HTML- .
, .
, , , ,
.
, .
, .
auto_prepend_file
auto_append_file, ,
.
. ,
,
<? header("Location: destination.php"); ?>

- , , Web-. ,
cookie- 4, cookie
Web-.


. , ,
, ?
16 . 216

482

5. MySQL

, , JPEG - . 19.
resizejunage.php, ,
<IMG SRO. 26.1.
26.1 resizejmage.php JPEG- " "
<?

if ( ! $max_width)
$max_width = 150 ;
if ( ! $max_height)
$max_height = 100;
$size = GetlmageSize ($image) ;
$width = $size[0] ;
$height = $size[l];
$x_ratio = $max width / $width;
$y_ratio = $max_height / $height;

if ( ($width <= $max_width) && ($height <= $max_height) )


$tn_width = $width;
$tn_height = $height;
}
else if ( ($x_ratio * $height) < $max_height) {
$tn_height = ceil ($x_ratio * $height) ;
$tn_width = $max_width;
}
else {
$tn_width = ceil($y_ratio * $ width );
$tn_height = $max_height;
}

$src = ImageCreateFromJpeg ($ image) ;


$dst = ImageCreate($tn_width,$tn_height) ;
ImageCopyResized($dst, $src, 0, 0, 0, 0,
$tn_width, $tn_height , $width , $height) ;
header ("Content- type: image/ jpeg") ;
Image Jpeg ($dst, null, -1) ;
ImageDestroy ($sro) ;
ImageDestroy ($dst) ;

,
. ,
200 200, .
, . , 400 300
200x150. .
,
HEIGHT WIDTH <IMG SRO. .
, 100 . , .

26.

4 J

19.
ImageCopyResized() .
. . $max_width $max_height . ,
.
$x_ratio = $max_width / $width;
$y_ratio = $max_height / $height;
,
. X
Y , :
if ( ($width <= $max_width) &S ($height <= $max_height) ) {
$tn width = $width;
$tn~height = $height;
}

else if (($x_ratio * $height) < $max_height) {


$tn_height = ceil($x_ratio * $height);
$tn width = $max_width;
}

else {
$tn_width = ceil($y_ratio * $width);
$tn height = $max_height;
}


. 26.1 .
26.1

create_database.sql

SQL

SQL-

include_fns.php

do_fns.php

select_fns.php


SELECT

user_airth_(ns.php

header.php

footer.php

logo.gif

, header.php

headlines.php

page.php

4 "

5. MySQL

resize_image.php


headlines.php

search_form.php

search.php

login.php

togout.php

stories.php

,
. ,

story.php

story_submit.php


, story.php

delete_story.php

,
stories.php

keywords.php

keyword_add.php

,
keywords.php

keyword_delete.php
publish.php

publish_story.php
unpublish_story.php

,
keywords.php
,
,

,
publish.php
,
publish.php


26.2 SQL-,
. create_database.sql.
CD-ROM
.
26.2 create_database.sql SQL-

drop database if exists content;
create database content;
use content;
drop table if exists writers;

26.

45

create table writers (


username
varchar(16) primary key,
password
varchar(16) not null,
full_name
text
);
drop table if exists stories;
create table stories (
id
int primary key auto_increment,
writer
varchar(16) not null,
page
varchar(16) not null,
headline
text,
story_text text,
picture
text,
created
int,
modified
int,
published int
);
drop table if exists pages;

# writers.username
# pages.code

create table pages (


code
varchar(16) primary key,
description text
);
drop table if exists writer_permissions;
create table writerjpermissions (
writer
varchar(16) not null,
page
varchar(16) not null

);

# writers.username
# pages.code

drop table if exists keywords;


create table keywords (
story
int not null,
# stories.id
keyword
varchar(32) not null,
weight
int not null
);
grant select, insert, update, delete
on content. *
to contentslocalhost identified by 'password';
,
, writers.
, .
pages , . writer_permissions , .
stories headline (),
story_text ( ) picture (), . created
(), modified () published () UNIX .
:
mysql -u root < create_database. sql

486

5. MySQL

, ,
.


headlines. php. 26.3.
, . .
26.3 headlines.php

<?
include ( " include_f ns .php") ;
include ("header .php") ;
$conn = db_connect () ;
$pages_sql = "select * from pages order by code" ;
$pages_result = mysql_query ($pages_sql , $conn) ;
while ($pages = mysql_fetch_array ($pages_result) ) {
$story_sql = "select * from stories
where page = ' $pages [code] '
and published is not null
order by published desc";
$story_result = mysql_query ($story_sql, $conn) ;
if (mysql_num_rows ($story_result) ) {
$story = mysql_fetch_array ($story_result) ;
echo "<TABLE BORDER=0 WIDTH=400>" ;
echo "<TR>" ;
echo "<TD ROWSPAN=2 WIDTH=100>" ;
if ($story [picture] )
echo "<IMG SRC=\"resize_image.php?image=$story [picture] \">" ;
echo "</TD>" ;
echo "<TD>";
echo "<H3>$pages [description] </H3>" ;
echo $story [headline] ;
echo "</TD>" ;
echo "</TR>" ;
echo "<TRXTD ALIGN=RIGHT>" ;
echo "<A HREF=\"page .php?page=$pages [code] \">" ;
echo "<FONT SIZE=l>Read more $pages[code] . . .</FONT>" ;
echo "</A>" ;
echo "</TABLE>" ;

include

("footer .php") ;

?>

, , header. php
footer.php . , , .
.
select * from pages order by code

, .

26.
select * from stories
where page = ' $pages [code] '
and published is not null
order by published desc

.
. 26.3 headline.plip .

IfO^JSuperFastOnlineNews
The Top News Stories From
Around the World
26.3

JPP

Man gives birth


!:*M.^.~!!U^:.

Sports Latest - All The Winners


and Losers
Basketball is bad lor you
*.*1.l *,-,:* -i^'l

Up To The Minute Weather


Reports and Forecasts
Storms to corne

mimimm

:
< HREF="page.php?page=l"XFONT SIZE=l>Read more news . . .</FONTX/A>

Spage
. , page.php.
. page.php 26.4.
26.4 page.php
<?

include ("include_fns.php") ;
include ( "header . php" ) ;
$conn = db_connect() ;
if (!$page) {
header ( "Location : headlines . php" ) ;
exit;
$sql = "select * from stories
where page = ' $page '
and published is not null
order by published desc" ;
$result = mysql_query ($sql, $conn) ;

1 0

5. MySQL

while ($story = mysql_fetch_array ($result) )


{
echo "<H2>" . $story [headline] . "</H2>" ;
if ($story [picture]) {
$size = getlmageSize ($story [picture] ) ;
$width = $size[0] ;
$height = $size[l] ;
echo "<IMG SRC=\"$story [picture] \" HEIGHT=$height WIDTH=$width
ALIGN=LEFT>" ;
>
echo $story[story_text] ;
$w = get_writer_record($story [writer] ) ;
echo "<brXFONT SIZE=1>" ;
echo $w[full_name] . " , " ;
echo date("M d, H : i " , $story [modified] ) ;
echo "</FONT>" ;
}
include

(" footer . php " ) ;

, page. php Spage, . page. php


, ,
if (!$page) {
header ("Location: headlines .php") ;
exit;
}

, Spage
.

select * from stories
where = ' $ '
and published is not null
order by published desc
, , ( ).
,
.
. 26.4 page. php .
, .


paccMotpHM . stories.php.
, , . . 26.5.
,
. ,
. stories.php 26.5.

26,

>||SuperFastOnlineNews
Man gives birth

26.4

A man today gave birth in a hospital on Staten Island. NY. The baby boy
weighed in atiust over eight pounds and is doing well. The parents were
naturally overjoyed at the birth of their first son, and have have said they
hope to have a large family
Father Ted. M, conceived using a new method known as paternatility
whereby the fertilised embryo is transferred to the father's body at an early
stage. It is believed that this method reduces many of the risks of childbirth.

William Blllinp. Ditc 12.00-15

jFire!
Breal<ing news Reports are coming in of a fire in a barn somewhere in Arizona. Our
sources say the barn is very likety to burn to the ground and will not be economically
viable to repair.
lA bystander is reputed to have said 'There was quite a lot of smoke"
Iwilum . 1>*11.22

sj'oST"

Warning: Cannot send session cache foniter - headers already sent (output started
at /home/chris/pubHc_htrol/conterit/stories pbp.2) in .3tome/ehm/pubuc_htinJ/eonteiit/mclud?_fu5.pup on bne 11
Welcome. William Billings (Logout)
- stories:

26.5

Man gives birth


Fire!
SFON Launch Party report

Page
Created Last mollified
news Dec 11. 22:20 Dec 12, 00:15 [FubbhedDec 11. 21-30]
news

Dec 11. 19:19 Dec 11. 22:03 [Published Dec 11. 21:30]

news

Dec 11, 13:45 Dec 11, 13:4S [;4t] [ddete] [kejwwdsj

weattierDec 11. 13^5Dec 11. 13:48 [ejt] [dfiett] rkv<irds1


Storms to come
Sun shmmg, weather is sweet weather Dec 10, 12:25 Dec 10. 14:32 [Published Dec 1.0. 1432]

490

5. MySQL

26.5 stories.php ,

<?
include ("include_fns.php");
session_register("auth_user");
if (!check_auth_user()) {
?>
<FORM ACTION="login.php" METHOD=POST>
<TABLE BORDER=0>
<TR>
<TD>Username</TD>
<TDXINPOT SIZE=16 NAME="username"X/TD>
</TR>
<TR>
<TD>Password</TD>
<TDXINPUT SIZE=16 TYPE="PASSWORD" NAME="password"X/TD>
</TR>
</TABLE>
<INPUT TYPE=SOBMIT VALUE="Log in">
</FORM>
<?
}
else {

$conn = db_connect();
$w = get_writer_record($auth_user);
echo "Welcome, ".$w[full_name];
echo " (<A HREF=\"logout.php\">Logout</A>)";
echo "<p>";
$sql = "select * from stories where writer = '$auth_user' ".
"order by created desc";
$result = mysql_query($sql, $conn);
echo
echo
echo
echo

"Your stories: " ;


mysql_num_rows($result);
" (<A HREF=\"story.php\">Add new</A>)";
"<brXbr>" ;

if (mysql_num_rows($result)) {
echo "<TABLE>";
echo "<TRXTH>Headline</THXTH>Page</TH>" ;
echo "<TH>Created</THXTH>Last modif ied</THX/TR>" ;
while ($qry = mysql_fetch_array($result)) {
echo "<TR>";
echo "<TD>";
echo $qry[headline] ;
echo "</TD>";
echo "<TD>";
echo $qry[page];
echo "</TD>";
echo "<TD>";
echo date("M d, H:i", $qry [created] );
echo "</TD>";
echo "<TD>";
echo datef'M d, H:i", $qry[modified] );
echo "</TD>";
echo "<TD>";
if

($qry[published])
echo "[Published " . d a t e ( " M d,
else {

H:i",

$qry[published])."]";

26.
echo " [<A HREF=\"story.php?story=" .$qry[id] . "\">edit</A>] ";
echo " [<A HREF=\"delete_story .php?story=" . $qry f i d ] ."\">delete
echo " [<A HREF=\ "keywords. php?story=" .$qry[id] . "\">keywords</A>] ";

echo "</TD>";
echo "</TR>";
echo "</TABLE>";
}

, . ,
.
$auth_user . . , . 14.
login.php,
. $HTTP_REFERER. , .

. stories.php, .
$w = get_writer_record($auth_user);
echo "Welcome, ".$w[full_name];
echo " (<A HREF=\"logout.php\">Logout</A>)";

get_writer_record() db_fns.php
. logout.php
$auth_user.
SQL- , :
select * from stories where writer = '$auth_user'
order by created desc

, , ,
. , .
.
:
echo dateC'M d,

H:i",

$qry[created]);

:
echo date("M d, H:i", $qry[modified]);

, :

Qy 2,

5. MySQL

if ($qry [published])
echo "[Published ".date("Md, H:i", $qry [published] )."]";
else {
echo "[<A HREF=\"story.php?story=".$qry[id] . "\">edit</A>]
echo "[<A HREF=\"delete_story.php?story=".$qry[id] ."\">delete</A>]
echo " [<A HREF=\"keywords.php?story=".$qry[id] . "\">Jceywords</A>] " ;
}
, .
, .

story.php. . 26.6 .

_
Hcadkie
ISFON Launch report
j[news]The~Tbp"NewsStories From ^ound the World
Stoiy tezt (can contain HTML tags)
Yesterday has already gone dawn in history as the day Che best news site on the

26.6

boogie ere several A - l i s t celebs vho wish to remain nonynncus.

Or i^load HTML Be
Picture

T"!'

story.php 26.6.
26.6 story.php

<?

include
if

("include_fns.php") ;

(isset($story) )
$s = get_story_record($story) ;

<FORM ACTION="story_submit.php" METHOD=POST ENCTYPE="multipart/form-data">


<INPOT TYPE=HIDDEN NAME=" story" VALUE="<? echo $story;?>">
<INPOT TYPE=HIDDEN HAME="destination" VALUE="<? echo $HTTP_REFERER;?>">
<TABLE>
<TR>
<TD ALIGN=CEKTER>Headline<TD>
</TR>
<TR>
<TDXINPUT SIZE=80 NAME= "headline"
VALUE="<? echo $s [headline] ;?>"X/TD>
</TR>

26.
<TR>
<TD ALIGN=CENTER>Page<TD>
</TR>
<TR>
<TD ALIGN=CENTERX? echo query_select ("page" ,
"select p. code, p. description
from pages p, writer_permissions w
where p. code = w.page
and w. writer = ' $auth_user ' " , $s [page] ) ;?X/TD>
</TR>
<TR>
<TD ALIGN=CENTER>Story text (can contain HTML tags)</TD>
</TR>
<TR>
<TDXTEXTAREA COLS=80 ROWS=7 NAME="story_text"
WRAP=VIRTUALX? echo $s [story_text] ;?X/TEXTAREA>
</TD>
</TR>
<TR>
<TD ALIGN=CENTER>Or upload HTML file</TD>
</TR>
<TR>
<TD ALIGN=CENTERXINPUT TYPE=FILE NAME="html" SIZE=40X/TD>
</TR>
<TR>
<TD ALIGN=CENTER>Picture</TD>
</TR>
<TR>
<TD ALIGN=CENTERXINPUT TYPE=FILE NAME="picture" SIZE=40X/TD>
</TR>

<?
if ($s [picture]) {
$size
= getlmageSize ($s [picture] ) ;
$width = $size[0] ;
$height = $size[l] ;
?>
<TR>
<TD ALIGN=CENTER>
<IMG SRC="<? echo $s [picture] ;?>"
WIDTH=<? echo $width;?> HEIGHT=<? echo $height;?>>
</TD>
</TR>
<? } ?>
<TR>
<TD ALIGN=CENTERXINPUT TYPE=SUBMIT VALHE="Submit"X/TD>
</TR>
</TABLE>
</FORM>

. , Sstory .
if

(isset($story) )
$s = get_story_record($story) ;

get_story_record() db_fns.php. . -

494

5. MySQL

, Sstory NULL, $s .
<INPUT SIZE=80 NAME="headline" VALUE="<? echo $s [headline] ;?>">

Sstory ,
, .
Sstory , .
echo query_select("page" ,
"select p. code, p. description
from pages p, writer_permissions w
where p. code = w.page
and w. writer = ' $auth_user ' " , $s [page] ) ;

query_select() select_fns.php. HTML SELECT SQL-. NAME SELECT. SQL-


, VALUE ,
OPTION ,
. . SELECTED ,
.
<INPUT TYPE=HIDDEN NAME="story" VALUE="<?echo $story;?>">

- Sstory.
story_submit.php , Sstory,
SQL- UPDATE INSERT.
story_submit.php 26.7.
26.7 story_submit.php

// story_action.php
// /
include ( "include_f ns . php" ) ;
$conn = db_connect() ;
$time = time () ;
if ( ($html) && (dirname($html_type) == "text") ) {
$fp = fopen($html, "r") ;
$story_text = addslashes(fread($fp, filesize ($html) ) ) ;
f close ($fp) ;
}
if ($story) {
//
$sql = "update stories
set headline = '$headline',
story_text = '$story_text' ,
page = ' $page ' ,
modified = $time
where id = $story" ;
>
else {
//

26.

4 J

$sql = "insert into stories


(headline, story_text, page, writer, created, modified)
values
( ' $headline ' , ' $story_text ' , ' $page ' , '$auth_user ' , $time,
$time) " ;
}

$result = mysql_query ($sql, $conn) ;


if

(!$result) {
echo "There was a database error when executing <PRE>$sql</PRE>" ;
echo mysql_error ( ) ;
exit ;

}
if ( ($picture) && ($picture != "none") ) {
if

(!$story)
$story = mysql_insert_id() ;

$type = basename ($picture_type) ;


switch ($type) {
case "jpeg":
case "pjpeg" :

default:

$filename = "pictures/$story . jpg" ;


copy ($picture, $filename) ;
$sql = "update stories
set picture = '$filename'
where id = $story";
$result = mysql_query ($sql, $conn) ;
break ;
echo "Invalid picture format: $picture_type" ;

header ("Location: $destination") ;


?>

delete_story.php.
DELETE .
delete_story.php 26.8.

26.8

delete_story.php

__

<?

// delete_story.php

include

("include_fns.php") ;

$conn = db_connect() ;
$now = time () ;
$sql = "delete from stories where id = $story";
$result = mysql_query ($sql, $conn) ;
header ("Location: $HTTP_REFERER") ;



, .
. . .

496

S. MySQL

Its

*:,

> ek -.

- |> _;] $

P ; ' Q

Keywords for SFONLaunch Party report

26.7

.

KtywordWeieht
launch
10
[;
party
10
[:
SFON 8
[;
celebrities 5
[
boogie
3
[;

. 26.7 , .
keywords.php , . CD-ROM.
keyword_add.php keyword_delete.php. .
keyword_add.php :
insert into keywords (story, keyword, weight)
values ($story, '$keyword', $weight)
, keyword_delete.php :
delete from keywords where story = $story and keyword = '$keyword'

.
, search_form.php,
search.php,
. search.php
26.9.
26.9 search.php

<?

include ("include_fns.php");
include ("header.php");
$conn = db_connect();

26.
if ($keyword) {
$k = split (" ", $keyword) ;
$num_keywords = count ($k) ;
for ($i=0; $i<$num_keywords; $i++) {
if <$i)
$k_string .= "or k. keyword = '".$k[$i]."' " ;
else
$k string .= "k. keyword = '".$k[$i]."' " ;
}
$and .= "and ($k_string) " ;
}
$sql = "select s.id,
s . headline ,
10 * sum (k. weight) / $num_keywords as score
from stories s , keywords k
where s.id = k. story
$and
group by s.id, s. headline
order by score desc, s.id desc";
$result = mysql_query ($sql, $conn) ;
echo "<H2>Search results</H2>" ;
if (mysql_num_rows ($result) ) {
echo "<TABLE>" ;
while ($qry = mysql_fetch_array ($result) ) {
echo "<TRXTD>";
echo $qry [headline] ;
echo "</TDXTD>" ;
echo floor ($qry[score] )."%";
echo "</TDX/TR>" ;
}

echo "</TABLE>" ;
}
else {
echo "No matching stories found" ;

}");

include

("footer.php") ;

, , . - , AND OR, .
if ($keyword) {
$k = split (" ", $keyword) ;
$num_keywords = count ($k) ;
for ($i=0; $i<$num_keywords; $i++) {
if <$i)
$k_string .= "or k. keyword = '".$k[$i]."' " ;
else
$k_string .= "k. keyword = "' . $k[$i] . " ' ";

$and .= "and ($k_string) " ;


}

PHP- split() , Skeyword, .


, , -

5. MySQL

. , $and, :
and (k.keyword = 'keywordl' or k. keyword = ' keyword2' or
k.keyword = 'keywords ')

, :
select s.id,
s.headline,
10 * sum(k,weight) / $num_keywords as score
from stories s, keywords k
where s.id = k.story
and (k.keyword = 'keywordl1
or k.keyword = 'keyword2 '
or k.keyword = 'keywords ')
group by s.id, s.headline
order by score desc, s.id desc

, . , .
1 10,
100.
,
10.


,
. publish.php. 26.10.
26.10 publish.php ,
,

<?
include

("include_fns.php");

$conn = db_connect() ;
$sql = "select * from stories order by modified desc";
$result = mysql_query($sql, $conn);
echo "<H2>Editor admin</H2>";
echo "<TABLE>";
echo "<TRXTH>Headline</THXTH>Last modif ied</THX/TR>" ;
while ($story = mysql_fetch_array($result)) {
echo "<TRXTD>" ;
echo $story[headline];
echo "</TDXTD>" ;
echo date("M d, H : i " , $story[modified]);
echo "</TDXTD>" ;
if ($story[published])
{
echo

"[<A HREF=\"unpublish_story.php?story=$story[id]\">unpublish</A>]

26.

else {
echo " [<A HREF=\"publish_story .php?story=$ story [id] \">publish</A>]
eoho "[<A HREF=\"delete story .php?story=$story [id] \">delete</A>] "

echo "[<A HREF=\"story.php?story=$story[id]\">edit</A>]

";

echo "</TDX/TR>" ;
}
echo "</TABLE>";

, . . . .
stories.php , , . if . , .
, ,
unpublish story.php, publish_story-php delete_story.php.
publish_story.php SQL-:
update stories set published = $now
where id = $story
.
, unpublish_story.php ,

:
update stories set published = null
where id = $ story
, .
, .


, :
.
, .
, . , , , .
.
, , aspell.


Web ,
Web IMAP.


,
Web

, Web.
Web-
- IMAP. Web. ,

Web , Hotmail.
Warm
Mail, :
IMAP





,

. Web- .
,
.

27. , Web

5U1

: IMAP.
, . Post Office Protocol ( ) 3,
Internet Message Access Protocol ( Internet).
,
, . IMAP
, . IMAP , .
RFC (RFC 1939
RFC 2060 IMAP 4.1). :
http://www.imap.org/papers/imap.vs.pop.brief.html

SMTP (Simple Mail Transfer Protocol


), PHP- mail(). RFC 821.


IMAP , IMAP. , IMAP. , , phpinfo().
, .
FTP :
ftp://ftp.cac.Washington.edu/imap/c-client.tar.Z

UNIX . rfc822.h, mail.h linkage.h


/usr/local/include, ,
, with-imap , .
Windows,
, UNIX. Windows . ,
, IMAP-, :
http://www.php4win.de

, IMAP-, ,
NNTP (Networks News Transfer Protocol ). IMAP
, Warm Mail NNTP.
, . .
, .

j()2:

5. MySQL

,
. , . IMAP, :
imap_open()
imap_close()
imap_headers()
imap_header ()
imap_fetchheader()
imap_body()
imap_delete ()
imap_expunge()
, .
,
.
(, ). .
.
, , , .
IMAP , SMTP mail().
, .


Web . - . 27.1.

27.1


Warm Mail

27. , Web

j(J J

, ,
. . , , , , , .
. . ,
(""). ,
. , ,
, .
.
, ,
, index.php, . , , index.php, . ,
. , .
, .
,
.
, .
Warm Mail . 27.1,.
27.1 Warm Mail

index.php

include_fns.php

data_valid_fns.php
>

do_fns.php

mail

mail_fns.php


, . .

oufput_fns.php

HTML-

user_auth_fns.php

create_database.sql

SQL

SQL- book_sc


Warm Mail , .

5. MySQL

.
:
username Warm Mail.
password .
address ,
From () .
displayname "" ,
.
, :
username Warm Mail, .
server , . , localhost
mail.tangledweb.com.au.
port ,
. - 110,
IMAP- 143.
type , 'POPS'
'.
remoteuser .
accountid .
SQL-,
27.1.
27.1 create_database.sql SQL- mail
create database mail;
use mail;
create table users
(
username char (16) not
password char (16) not
address char (100) not
displayname char (100)
);

null primary key,


null,
null,
not null

create table accounts


(
username char (16) not null,
server char (100) not null,
port int not null,
type char (4) not null,
remoteuser char (50) not null,
remotepassword char (50) not null,
accountid int~ unsigned not null auto_increment primary key
);
grant select, insert, update, delete
on mail . *
to mail@localhost identified by 'password' ;

, SQL- , :
mysql -u root -p < create_database . sql

27. , Web

J(J J

(root). create_database.sql db_fns.php.


CD-ROM populate.sql. .
, . . populate.sql .
, .


, index, php 27.2. , .
27.2 index.php - Warm Mail

<?
//
//
//
//

Warm Mail.
, ,

//************************************************************************
// // 1:
//
// ,
//
//************************************************************************
include ('include_fns.php');
session_start();
$buttons = array();
// , -
//
$status = ' ' ;
// ,
//
if($username||$password)
{
if(login($username, $passwd))
{
$status .= "<p>Logged in successfully.<brXbrXbrXbrXbrXbr>" ;
$auth_user = $username;
session_register("auth_user");
}
else
{
$ status .= "<p>Sorry, we could not log you in with that
username and password.<brXbrXbrXbrXbrXbr>" ;
>
}
if($action == 'log-out')
{
session_destroy();
unset($action);
unset($auth_user);

DUO

5. MySQL
II ,
//
switch ( $action )
{
case ' delete-account ' :
{
delete_account($auth_user, $account) ;
break;
}
case 'store-settings' :
{
store_account_settings ($auth_user, $HTTP_POST_VARS) ;
break;
}
case 'select-account' :
{
// ,
//
if ($accountSSaccount_exists ($auth_user , $account) )
{
$selected_account = $account;
session_register ( ' selected_account ' ) ;

// ,
$buttons[0] = 'view-mailbox';
$buttons[l] = 'new-message';
$buttons[2] = 'account-setup';
// log-out
if (check auth_user())
{
$buttons[4] = 'log-out';
}
ff*************************************************************************
/I 2 :
// HTML- ,
//
//************************************************************************
if ($action)
{
//
//
do_html_header ($auth_user, "Warm Mail - ".
format_action($action) , $selected_account) ;
}
else
{
//
do_html_header ($auth_user , "Harm Mail", $selected_account) ;
}
display_toolbar ($buttons) ;
//********************************* ****************************************
II II :
// ,
//*************************************************************************
/I , ,
//
echo $status;

27. , Web
if ( ! check_auth_user ( ) )
{

echo "<P>You need to log in";


if ( $actionSS$action!=' log-out ' )
echo " to go to " . format_action ($action) ;
echo " . <brXbr>" ;
display_login_form($action) ;

else
{

switch ( $action )
{
//
// ,
//
case 'store-settings' :
case 'account-setup' :
case 'delete-account' :
1
display_account_setup ($auth_user) ;
break;
}
case ' send-message ' :
{
if (send_message ($to, $cc, $subject, $message) )
echo "<p>Message sent .<brXbrXbr><brXbrXbr>" ;
else
echo "<p>Could not send message. <brXbrXbrXbrXbrXbr>"
break ;
}
case 'delete' :
{
delete_message ($auth_user, $selected_account, $messageid) ;
// 'break'
// case
>
case 'select-account' :
case 'view-mailbox' :
{
// ,
display_list ($auth_user , $selected_account) ;
break;
}
case 'show-headers'
case 'hide-headers' :
case 'view-message' :
{
// ,
//
// ,
$fullheaders = ($action==' show-headers ');
display_message ($auth_user, $selected_account, $messageid,
$fullheaders) ;
break;
(
case 'reply-all' :
{
// $
// (carbon copy)
if (!$imap)
$imap = open_mailbox ($auth_user, $selected_account) ;
if ($imap)

JU

5. MySQL

$header = imap_header ($imap, $messageid) ;


if ($header->reply_toaddress)
$to = $header->reply_toaddress ;
else
$to = $header->f romaddress ;
$cc = $header->ccaddress;
$subject = 'Re: ' . $header->subject;
$body = add_quoting(stripslashes (imap_body ($imap,
$messageid) ) ) ;
imap_close($imap) ;
display new_message_form($auth_user, $to, $cc, $subject, $body) ;
}
break;

}
case ' reply ' :
{
// reply-to () , from
// ()
if (!$imap)
$imap = open_mailbox($auth user, $selected_account) ;
if ($imap)
{
$header = imap_header ($imap, $messageid) ;
if ($header->reply_toaddress)
$to = $header->reply_toaddress;
else
$to = $header->f romaddress ;
$subject = 'Re: ' . $header->subject;
$body = add_quoting(stripslashes (imap_body ($imap, $messageid) ) ) ;
imap_close ($imap) ;
display_new_message form($auth_user, $to, $cc, $subject, $body) ;

}
break;
}
case 'forward' :
<
//
//
if ( ! $imap)
$imap = open_mailbox($auth_user, $selected_account) ;
if($imap)
{
$ header = imap_header ($imap, $messageid) ;
$body = add_quoting(stripslashes (imap_body ($imap, $messageid) ) ) ;
$subject = 'Fwd: ' . $header->subject;
imap_close($imap) ;
display new_message_form($auth_user, $to, $cc, $subject, $body) ;

break;

}
case 'new-message' :
{
display_new_message_form($auth_user , $to, $cc, $subject, $body) ;
break;

27. , Web
//*************************************************************************
// 4 :
do_html_footer();
//************************************************************************
?>

.
. , .
display_button(),
display_form_button() (submit).
output_fns.php. URL- :
index.php?action=log-out

index.php, Saction ,
.
:
1. , . ,
.
2. .
3. . .
4. .
, .
, .


index.php, ,
. 27.2.

27.2

Warm Mail

.

J 1U

5. MySQL

.
( Saction )
, .
:
include ('include_fns.php');
session_start();

, $auth_user $selected_account(). .
, .
$buttons = array();
, :
$buttons[0] = 'view-mailbox';
$buttons[1] = 'new-message' ;
$buttons[2] = 'account-setup';

:
do_html_header($auth_user, "Warm Mail", $selected_account);
display_toolbar($buttons);

, . 27.2. output__fns.php. , .
:
if(!check_auth_user())
{
echo "<P>You need to log in" ;
if($actionSS$action! ='log-out')
echo " to go to ".format_action($action);
echo " . <brXbr>" ;
display_login_form($action);
)

check_auth_user() user_auth_fns.php.
, . , , , . 27.2. display_login_form() output_fns.php.
Log In (
), , . 27.3.
.
, Susername Spassword. , :
if($username||$password)
{
if(login($username, $passwd))

27. , Web

JX

$status .= "<p>Logged in successfully .<brXbrXbrXbrXbr><br>"


$auth_user = $username ;
session_register ( "auth_user" ) ;
else
$status .= "<p>Sorry, we could not log you in with that
username and password.<brXbrXbrXbrXbrXbr>"

, loginQ, ,
24 25.
$auth_user.
, , , :
if(check_auth_user())
{

$buttons[4] = 'log-out';

Log Out . 27.3.


.
, :
echo $status,-


Warm Mail, . Account Setup ( ), Saction account-setup
index.php. . 27.4.

" Rsuesh.

;-(?

' Seai*

er2?fincte.i php?ecftoP

27.3



.

Fs^ar-^s

Hwioiy

>

512

5. MySQL

27.4

,


.

27.2. Saction
.
:
do_html_header ($auth_user, "Warm Mail - ".
format_action($action), $selected_account);

:
case 'store-settings' :
case 'account-setup' :
case 'delete-account' :
display account_setup($auth_user) ;
break;

.
display_account_setup(). 27.3.
27.3 display_account_setup() outputjns.php

function display_account_setup($auth_user)
// "new account"

(" ")

display_account_form($auth_user);
$list = get_accounts($auth_user);
//
foreach($list as $key => $account)
//
//
//
//

.

HTML-.

27. , Web

Jij

display_account_f orm ( $auth_user ,


$ account [ ' accountid' ] ,
$account [ ' server ' ] ,
$account [ ' remoteuser ' ] ,
$account[ ' remotepassword' ] ,
$account [ ' type ' ] ,
$account [ ' port ' ] ) ;


. , . display_account_form() ,
. 27.4. , :
,
. output_fiis.php.
HTML- .

get_accounts() maiMhs.php. 27.4.
27.4 get_accounts() mail_fns.php

_
_
function get_accounts ($auth_user)
{

$list = array () ;
if (db_connect () )
{

$query = "select * from accounts where username = ' $auth_user ' " ;
$result = mysql_query ($query) ;
if ($result)
{

while ($settings = mysql_fetch_array ($result) )


array_push( $list, $settings) ;

else
return false ;
}

return $list;
,
.



Save Changes ( ), store-settings. index.php :
case 'store-settings' :
{

store_account_settings($auth_user, $HTTP_POST_VARS) ;
break;

17 . 216

J 14

5. MySQL

store_account_settings()
. 27.5.
27.5 store_account_settings() maiHns.php

_
function store account_settings($auth_user,
{
if (!fillad_out($settings) )

echo "All fields must be filled in.


return false ;

$settings)

Try again. <brxbr>" ;

>
else
{
if ($settings[ 'account1 ]>0)
$query = "update accounts set server = ' $settings [server] ',
port = $settings [port] , type = '$ settings [type] ',
remoteuser = '$settings[remoteuser] ' ,
remotepassword = ' $settings [remotepassword] '
where accountid $settings [account]
and username = ' $auth_user ' " ;
else
$query - "insert into accounts values ( ' $auth_user ' ,
'$settings [server] ' , $settings [port] ,
' $ set ting a [type] ' , ' $settings [remoteuser] ' ,
' $ set tings [remotepassword] ' , NULL) " ;
if(db connect () && mysql_query ($query) )
<
return true ;
>
else
{
echo "could not store changes . <br><brXbrXbrXbrXbr>" ;
return false;

. .
index.php:
case 'store -settings' :
case 'account-setup1 :
case ' delete-account ' :
{
display account setup ($auth_user) ;
break;
}
, , display_account_setup() . .

27. , Web

J1J


. Save Changes. store-settings. , .


Delete Account ( ), . delete-account.
index.php :
case 'delete-account1 :
{

delete_account($auth_user, $account) ;
break;

delete_account(), 27.6. ,
.
, .
27.6 delete_account() maiHns.php

function delete_account ($auth_user, $accountid)


{

//
/ /
$query = "delete from accounts where
accountid= ' $accountid ' and
username = ' $auth_user ' " ;
if (db_connect())
{

$result = mysql_query ($query) ;

return $result;


index.php. :
case 'store-settings' :
case 'account-setup' :
case 'delete-account' :
{

display_account_setup ($auth_user) ;
break;

516 5. MySQL

,
.


.
$selected_account.
,
:
if (number_of_accounts ($auth_user) ==1)
{

$accounts = get_account_list($auth_user) ;
$selected_account = $accounts [0] ;
session_register ( "selected_account" ) ;

}
number_of_accounts() mail_fns.php , . get_account_list()
. .
0.
number_of_accounts() 27.7.
27.7 number_of_accounts() mail_fns.php ,

_
function nurober_of_accounts ($auth_user)
{

// ,
//
$query
= "select count (*) from accounts where username =
1
$auth_user ' " ;
if (db_connect ( ) )
{

$result = mysql_query ($query) ;


if ($result)
return mysql_result($result, 0, 0) ;

return 0 ;

get_account_list() get_accounts()
, .
,
.
SELECT, .
, .
27.5.
SELECT do_html_header()
output_fns.php, :

<?

// ,
//

27. , Web

J 1 /

if (number_of_accounts ($auth_user) >1)


{

echo "<form target= ' index . php?action=open-mailbox ' method=post>" ;


echo '<td bgcolor = "#ff6600" align = right valign = middle>' ;
display_account_select($auth_user, $selected_account) ;
echo '</td>';
echo "</form>" ;

HTML-,
. HTML-, display_account_select() .
,
display_account_select() HTML- :
<select onchange=window. location=this . options [selectedlndex] .value
name=account>
<option value = 0 selected>
Choose Account</a>
<option value = ' index. php?action=select-accountsaccount=10 '>
mail . domain . com
</option>
<option value = ' index. php?action=select-accountsaccount=ll '>
mail . server . com
</option>
<option value = ' index. php?action=select-accountsaccount=9 ' >
localhost
</option>
</select>

,
JavaScript. , HTML-,
.

3|] http://webservet/chapter27/index.php?acfion-selet*accouni&accounl-l

27.5

SELECT
localhost

28-5-20
N 2i28-Sep-30DO emamamost.domain Re- Warm Mail f3473 charsi
N -- .maiiam.sl domain PHP Scrlcllna (830 chats!
M 412S-Sec-300n .maiimosl.aomaln Time for a Holiday (1591 tharsl
Make t40.0DO DBf WaBHI! f 1030 chars

5. MySQL

, JavaScript-
window.location . SELECT, window.location
1
I
index.php?action=select-accoimt&account=10 . URL-. , JavaScript
JavaScript- , .
display_account_select() outputjns.php
. , get_account_list().
SELECT
select_account. . 27.5, window.location
URL- .
. -, ( index. php)
$selected_account :
case 'select-account' :
{

// ,
//
if ($accountSSaccount_exists ($auth_user , $account) )
{

$selected_account = $account;
session_register ( ' selected_account ' ) ;

-, , :
case 'select-account' :
case ' view-mailbox ' :
{

//
// view maibox,
display_list($auth_user, $selected_account) ;
break;

, View
Mailbox, .


display _list().
. 27.8.
27.8 display_list() output_fns.php

function display_list($auth_user, $accountid)


<

//
global $ table_width ;
if (!$accountid)

27. , Web

J 1v

echo "No mailbox selected<brXbrXbrXbrXbrXbr>. " ;


else
$imap = open_mailbox($auth_user, $accountid);
if($imap)
echo "<table width = $table_width cellspacing = 0
cellpadding = 6 border = 0>" ;
^headers = imap_headers($imap);
//
//
// imap_fetchheaders, ,
// echo
$messages = sizeof($headers) ;
for($i =0; $i<$messages;
echo "<trXtd bgcolor = ' " ;
if($i%2)
echo "#ffffff";
else
echo "#ffffcc";
echo " ' Xa href = ' index . php?action=viewmessage&messageid=" . ($i+l) . " '>";
echo $headers[$i] ;
echo "</aX/tdX/trX\n" ;

}
echo "</table>";
else
$account = get_account_settings ($auth_user, $accountid) ;
echo "could not open mail box
" . $account [ ' server' ] . " .<brXbrXbrXbr>"

IMAP- . .
open_mailbox() mail_fns.php. 27.9.
27.9 openjnailboxQ mailjns.php

function open_mailbox($auth_user, $accountid)
{
// ,
if(number_of_accounts($auth user)==l)
{
$accounts = get_account_list($auth_user);
$selected_account = $accounts[0];
session_register("selected_account");
$accountid = $selected_account;
)
// IMAP,

520

5. MySQL
$settings = get_account_settings ($auth_user , $accountid) ;
if ( Isizeof ($settings) ) return 0;
$mailbox = "{" $settings [server] ;
if ($settings[ type] ==' POPS')
$mailbox .= '/';
$mailbox . = " : " . $settings [port] . " } INBOX" ;

// ,
@ $iraap = imap_open ($mailbox , $settings [remoteuser] ,
$settings [remotepassword] ) ;
return

$imap;

imap_open().
:
int imap_open (string mailbox, string username,
string password [, int flags])

, :
mailbox ,
, , .
:
{hostname/protocol :port}boxname

, IMAP.
, ,
, .
, , IMAP :
{localhost: 143) INBOX

:
{ localhost/ : 110 } INBOX

username
password
, ,
"open mailbox in read-only mode" ( "
").
, mailbox imap_ppen() . , , {$, 4 .
, , false .
imap_close(imap_stream).

521

27. , Web

IMAP . imap_headers(),
:
$headers = imap_headers($imap);


, . , . .
, . 27.5.
,
imap_header(). imap_headers() .


, display_Iist(),
.
:
index.php?action=view-message&messageid=6

mcssagcid ,
. , IMAP-
, .
,
. 27.6.

, Dlf.

L'iii

>

, ^=,.,

:i

__

g
|
| -,

Hcwv

Mail

-*

Piinl

1
if

Section -view-mesEeqe&messageid-S

27.6

view-message
.

.

This is a LEGITIMATE. LEGAL, MONEY MAKING OPPORTUNITY. It does not isquire you lo come Into contact with people, do any hard wi
and best of all, you never have to leave the house except to the mail, if you believe that someday you'll get that big break that youVe been
wafting for, THIS 13 m Slmpty follow the Instructions, and your dreams will come true. This multi-level e-mail order marketing program
works
perfectly, 100% EVERY TIME.
The following income opportunity is one you in ay be interested in taking a look at. it can be started with very HtOe investment and the
Income return is TREMENDOUS!

ill

.f*

5. MySQL

index. php :
case ' show-headers '
case ' hide-headers '
case ' view-message '

// ,
//
// ,
$ullheaders = ($action=' show-headers' ) ;
display_message($auth_user, $selected_account, $messageid,
$fullheaders)
break;

Saction 'show-headers'.
false Sfullheaders false. 'show-headers' .

$fullheaders = ($action== ' show-headers ');

, , , :
if ( $action== ' show-headers ' )
$f ullheaders = true ;
else
$f ullheaders = false;

display_message(). HTML-, . retrieve_message() :


$message - retrieve_message ($auth_user , $accountid,
$messageid, $f ullheaders) ;

retrieve_message() mail_fns.php.
27.10.
27.10 retrieve_message() maiHns.php

_
function retrieve_message($auth_user, $accountid, $messageid,
$f ullheaders)

$ mess age = array () ;


if (! ($auth_user && $messageid && $accountid) )
return false ;
$imap = open_mailbox($auth_user, $accountid) ;
if ( ! $imap)
return false ;
$header = imap_header ($imap, $messageid) ;
if (! header)
return false;
$message[ 'body' ] = imap_body ( $ imap , $messageid) ;
if ( ! message [ ' body ' ] )
message [ 'body'] = '[This message has no body] \ n \ n \ n \ n \ n \ n 1 ;

27. , Web
if ($fullheaders)
$message [ ' f ullheaders ' ] = imap_fetchheader ($imap, $messageid)
else
$message [ ' f ullheaders ' ] = ' ' ;
$ me ss age [ ' subject ' ] = $header->subject;
$ mess age [ ' f romaddress ' ] - $ header- >f xomaddress ;
$ mess age [ ' toaddress ' ] = $header->toaddress ;
$message[ 'ccaddress ' ] =
$header->ccaddress;
$message[ 'date'] =
$header->date;
//
// from to
// f romaddress toaddress,
imap_close($imap) ;
return $message ;

-, open_mailbox().
.
.
IMAP- imap_header(), imap_fetchhcader()
imap_body().
imap_headers. .
:
imap_headers()
, .
imap_header()
.
imap_fetchheader()
.
imap_header() , a imap_fetchheader() ,
. ( .)
imap_header() imap_body() ,
.
imap_header() :
$header = imap_header ($imap, $messageid) ;

:
$message[ 'subject'] = $header->subjact;

imap_body():
$message['body'] = imap_body ($imap, $messageid) ;

, imap_close()
. display_message() , . 27.6.


. 26.7 Show Headers ( ). show-headers, . . 27.7.

524

5. MySQL

http://websetver/cnapter7/index php?action-snQW-tieaders&messageid5

27.7
show-headers,


,

Mk. 140,000 per Week!!!

.-)

; .

by MviilhWijIBumelnl! a 4)9.4 :>ftKtSEUm<E Mi n I DM.11 [I74;


nip
'.
' .'" ' ;:'

.
Miif.i ,',|(

0
gig
This Is a LEGITIMATE, LEGAL, MONEY MA

view-message show-headers ( hide-headers). , ,


. retrieve_message()
:
if($fullheaders)
$message['fullheaders'] = imap_fetchheader($imap, $messageid);
.


Delete
delete.
index.php:
case 'delete' :
{

delete_message($auth_user, $selected_account, $messageid);


// 'break'
// case
1

case 'select-account :
case 'view-mailbox' :
//
// ,
display_list($auth_user, $selected account);
break;
}

delete_message() , , .
delete_message() 27.11.

27. , Web

27.11 delete_message() mail_fns.php



function delete_message($auth_user, $accountid, $message_id)
{
//
$imap = open_mailbox($auth_user, $accountid) ;
if ($imap)
{
imap_delete ($imap, $message_id) ;
imap_expunge($imap) ;
imap_close ($imap) ;
return true ;
}
return false;

1. imap_delete()
imap_expunge(). , imap_delete() . . imap_expunge() .


, . : , ,
. .


, New Message (
). new-message, index. php:
case ' new-message ' :
display_new_message_form($auth_user, $to, $cc, $subject, $body) ;
break;

>

.
. 27.8. ,
.
Send Message send-message,
:
case ' send-message '

if (send_message($to, $cc, $subject, $message) )


echo "<p>Message sent.<brXbrXbrXbrXbrXbr>" ;
else
echo "<p>Could not send message. <brXbrXbrXbrXbrXbr>" ;
break ;

526

5. MySQL

3 Wtp //webservar/chapter27/if>dex php'Jaction-fofward&mBSsngeid-S

27.8


.

> This is a LEGITIMATE, LEGAL, MONEY MAKING OPPORTUNITY. It does not


require you to come into contact with people, do any hard work and best
of all, you never have to leave the house except to the mail. If you
believe that someday you'll get that big break that you've been waiting
for, THIS 13 IT! Simply follow the instructions, and your dreams will
come true. This multi-level e-mail order marketing program works
> perfectly, 100% EVERY TIME.
> The following income opportunity is one you may be interested in
taking a look at. It can be started with very little investment and

send_message(), . 27.12.
27.12 send_message() mail_fns.php

function send_message($to, $cc, $subject, $message)
//
global $auth_user;
if (! db_connect() )
return false;

$query

"select address from users where username='$auth user'";

$result = mysql_query($query);
if (!$result)

return false;

else if

(mysql_num_rows($result)==0)

return false;
else
$other = "From: ".mysql_result($result, 0, "address")."\r\ncc: $cc";
if (mail($to, $subject, $message, $other))
return true ;
else
return false;

27. , Web

52, /

,
mail().
. From ().


Reply (), Reply All ( ) Forward () , New Message.
. . 27.8. . ">". Subject () . Reply Reply All ,
.
index.php:
case 'reply-all' :
{
//
if(!$imap)
$imap = open_mailbox($auth_user, $selected_account);
if($imap)
{
$header = imap header($imap, $messageid);
if($header->reply_toaddress)
$ to => $header->reply_toaddress ;
else
$to e $header->fromaddress;
$cc = $header->ccaddress;
$subject = 'Re: '.$header->subject;
$body = add_quoting(stripslashes(imap_body($imap, $messageid)));
imap_close($imap);
display new_message_orm($auth_user, $to, $cc, $subject, $body);

}
break;
)
case 'reply' :
{
// Reply-to From
if(!$imap)
$imap = open mailbox($auth_user, $selected account);
if($imap)

$header = imap_header($imap, $messageid);


if($header->reply_toaddress)
$to = $header->reply_toaddress;
else
$to = $header->fromaddress;
$subject = 'Re: '.$header->subject;
$body add_guoting(stripslashes(imap_body($imap, $messageid)));
imap_close($imap);
display_new_message_form($auth user, $to, $cc, $subject, $body);

break;

// 'break'

j 2,0

5. MySQL

case 'forward'
{

// , ,
if(!$imap)
$imap = open_mailbox($auth_user, $selected_account);
if($imap)
{

$header = imap_header($imap, $messageid);


$body = add_quoting(stripslashes(imap_body($imap, $messageid)));
$subject = 'Fwd: '.$header->subject;
imap_close($imap);

display_new_message_form($auth_user, $to, $cc, $subject, $body);


}
break;
}

, display_new_message() .
Web- .


. . :

. ( 24.)

, ,
. . . ,
.

, . , , 16.
28.


. NNTP- IMAP . imap_open()
. INBOX
, . 29
Web- , .


, .
, .

28

Web-,
, . (mailing list manager, MLM).
MLM . ,
. Pyramid-MLM.

. ,
http://www.topics.com


.
,
HTML- , . ,
.
,
, ,
HTML.

J J (j

5. PHP MySQL

. .
, :
.
HTML
.

.

,
.
.
HTML
.

.

.
, ().


. ,
; ,
; .


,
, .
HTML, , .
, .
. , , , .

28.

531

, ,
.
MySQL .


, ,
. , . ,
. , , Web-. HTML.
, 16.
, , . , ,
HTML , , HTML.
,
, . .


,
""
HTML-.
HTML- . PHP- mail()
. HTML MIME Mail, (Richard
Heyes). HTML- , HTML-.
Web-
http://www.heyes-computing.net/scripts/

( CD-ROM.)
.
.
Web-.



, 27.
, , , , .

. , ,

532

5, MySQL

. ,
, . 28.1, 28.2 28.3.

28.1
.

28.2
.

28.3

28.

JjJ

. 28.1 ,
. , ( ), ( ) , ( ).
, ,
. 28.2. (
),
, .
, , .
28.3. , ,
, .
, .
, index.php,
. . 28.1.
28.1

index.php

,
.

include_fns.php

data_valid_fns.php

db_fns.php


mlm.

mlm_fns.php

,
.

output_fns.php

HTML.

upload.php

,
.

.

user_auth_fns.php

create_database.sql

SQL

SQL- mlm
Web
.

,
.


:
Lists (): , .
Subscribers (): .
Sub_lists ( ): , ( --).

J 34

5. MySQL

Mail (): .

Images (): , (.., ,


HTML ), , .

SQL-, , 28.1.
28.1 create_database.sql SQL- mlm
create database mlm;

use mlm;
create table lists
(
listid int auto increment not null primary key,
listname char(20) not null,
blurb varchar(255)
);
create table subscribers
(
email char(lOO) not null primary key,
realname char(100) not null,
mimetype char(l) not null,
password char(16) not null,
admin tinyint not null
);
#
create table sub_lists
(
email char(100) not null,
listid int not null

);

create table mail


(
mailid int auto_increment not null primary key,
email char(100) not null,
subject char(100) not null,
listid int not null,
status char(10) not null,
sent datetime,
modified timestamp
);
# ,
create table images
(
mailid int not null,
path char(100) not null,
mimetype char(100) not null
);
grant select, insert, update, delete
on mlm.*
to mlmglocalhost identified by 'password';
insert into subscribers values
('admin@localhost', 'Administrative User', 'H', password('admin'), 1);

28.

JJ

, SQL- ,
mysql -u root -p < create_database. sql
root. (,
- MySQL, ; root
.) , mlm .
, .
lists (email)
(realname). password (admin), ,
. mimetype
, .
HTML .
sublists (email) subscribers
listid lists.
mail , . (mailid),
, (email),
(subject) listid , . HTML- ,
. , : (status),
(sent) ,
(modified).
, images , HTML. , . mailid, ,
path MIME-
(mimetype), , image/gif.
SQL- , PHP-,
.


, .
index.php.
:
1. : ,
.
2 : HTML.
3. : . , Saction.
4. .

536

5. MySQL

. ,
, . 28.1.
index.php 28.2.

28.2 index.php Pyramid-MLM


<?
/**********************************************************************
* 1:
ft********************************************************************/
include ('include_fns.php');
session_start() ;
$buttons = array ();
// , -
//
$status = ' ' ;
//
//
if($emailSS$password)
{
$login = login($email, $password);
if($login = 'admin')
{
Sstatus .= "<pXb>".get_real_name($email) . "</b> logged in"
." successfully as <b>Administrator</bXbrXbrXbrXbrXbr>" ;
$admin_user = $email;
session_register("admin_user");
}
else if($login = 'normal')
{
$status .= "<pXb>".get_real_name($email) . "</b> logged in"
. " successfully. <brxbr>" ;
$normal_user = $email;
session_register("norroal_user");
)
else
{
$status .= "<p>Sorry, we could not log you in with that
email address and password.<br>" ;
}
)

if($action = 'log-out')
{
session_destroy0;
unset($action) ;
unset($normal_user);
unset($adrain_user);
}
* 2:
// ,
if(check_normal_user())
{
//
$buttons[0] = 'change-password';
$buttons[l] = 'account-settings';
$buttons[2] = 'show-my-lists';
$buttons[3] = 'show-other-lists';
$buttons[4] = 'log-out';
}
else if(check_admin_user())

28.
II
$buttons[0] = 'change-password';
$buttons[l] = 'create-list1;
$buttons[2] = 'create-mail' ;
$buttons[3] = 'view-mail';
$buttons[4] = 'log-out1;
$buttons[5] = ' show-all-lists' ;
$buttons[6] = 'show-my-lists';
$buttons[7] = 'show-other-lists';
}
else
{
II
$buttons[0] = 'new-account';
$buttons[l] = 'show-all-lists';
$buttons[4] = 'log-in';
)

if($action)
<

//
//

do_html_header("Pyramid-MIM - ".
format_action($action));
}
else
{
// ,
do_html_header("Pyramid-MLM");
}

display_toolbar($buttons);
// , ,
//
echo $status;
/*******.********.*.*****************************.***********.*********
* 3:
//
switch ( $action )
{
case 'new-account' :
<
unset($normal_user);
unset($admin_user);
display_account_form($normal_user, $admin_user);
break;
}
case 'store-account' :
<
if (store_account($normal_user, $admin_user, $HTTP_POST_VW?S))
Section = ' ' ;
if{!check_logged_in())
display_login_form ($action);
break;
}
case 'log-in' :
case ' ' :
{

if (! check_logged_in())
display_login_form($action) ;

break;
}
case 'show-all-lists' :
display_iterns("All Lists", get_all_lists(), 'information',
1
show-archive','');
break;

JJ

5. MySQL

case

'show-archive'

display_iterns("Archive For ".get_list_name($id) ,


get_archive($id), 'view-html',
break;

1
case

'information'

'view-text',

'');

display_information($id);
break;

>
\
//
if(check_logged_in(})
switch ( $action )
case 'account-settings' :
display_account_form($normal_user, $admin_user, get_eroail(),
get_real_name(get_email()) , get_mimetype(get_email()));
break;
case 'show-other-lists' :
display_iterns("Unsubscribed Lists",
get_unsubscribed_lists(get_email()) , 'information',
'show-archive', 'subscribe');
break;

1
case 'subscribe' :
subscribe(get_email(), $id) ;
display_iterns("Subscribed Lists", get_subscribed_lists(get_email()),
'information', 'show-archive', 'unsubscribe');
break;
case ' unsubscribe' :
unsubscribe(get_email(), $id);
display_items("Subscribed Lists", get_subscribed_lists(get_email()),
'information', 'show-archive', 'unsubscribe');
break;
case ' ' :
case 'show-my-lists'

display_iterns("Subscribed Lists", get_subscribed_lists(get_email()),


1
information' , ' show-archive' , ' unsubscribe') ;
break;
case

'change-password'

di splay_pas sword_f orm () ;


break; "
case 'store-change-password'

if (change_password(get_email(), $old_passwd,
$newjpasswd, $newjpasswd2))
echo "<:

Password changed. <brxbrxbrxbrxbrxbr>";

else
echo "<p>Sorry, your password could not be changed.";
display_password_form();

28.

53;/

break;

// ,
//
if (check_admin_user )
{
switch ( $action )
{
case 'create-mail' :
{
display_raail_form(get_email () ) ;
break;

case 'create-list' :

display list form (get email ( ) ) ;


break; ~

)
case 'store-list' :
{
if (store list($admin_user, $HTTP_POST_V3kBS) )
{
echo "<p>New list added<br>";
display_i terns ("All Lists", get_all_lists ( ) , 'information',
' show-archive ','');
)
else
echo "<p>List could not be stored, please try "
. "again . <brXbrXbrXbrXbr>" ;

break;
)
case ' send ' :
{
send($id, $admin_user) ;
break;
}
case 'view-mail' :
{
display_i terns ("Unsent Mail" , get_unsent_mail (get_email () ) ,
' preview-html ' , ' preview- text ' , ' send ' ) ;
break;

/*********************************************************************
* 4:
do_html_footer() ;

.
, , . .
, , do_html_header() output_fns.php
. , .

540

5. MySQL

. : , ,
, , , , , .
check_logged_in() check_admin_user().
user_fns.php.
check_normal_user() 28.3.
28.3 user_auth_fns.php ,
, .

function check_normal_user ( )
// , ,
// ,

global $normal_user ;
if (session_is_registered("nonnal_user") )
return true ;
else
return false;

function check_admin_user ( )
// , ,
// ,

global $admin_user;
if (session_is_registered("admin_user") )
return true ;
else
return false;

function check_logged_in ( )
{

return ( check_normal_user () || check_admin_user ( ) ) ;

, , , $normal_user $admin_user.
.
HTML,
do_html_footer() output fns.php
. .
28.2.
, store-mail, , create-mail,
. , upload.php. ,
.
, . 28.2, .. , ; , ; ,
.

28.

28.2

log-in

log-out

new-account

store-account

show-all-lists

show-archive

information

account-settings

show-other-lists

show-my-lists

subscribe

unsubscribe

change-password

store-changepassword

create-mail

create-list

store-list

view-mail


,
,

send

5. MySQL


, , , .
-, , ; -, ; -, . .
. 28.4 , .
, "
" " ".


New Account ( ),
new-account.
index.php:
case 'new-account' :
{
unset ($normal_user) ;
unset ($admin_user) ;
display_account_form($normal_user, $admin_user) ;
break;

, ,
, ,
. 28.5.
display_account_form()
output_fns.php. ,
,
.
,
. . HTML-,
.
.file

Edit

View

''

Fflvwiies

Fbwart

'

loois

jjtig

RsrfHtsh

Hofrg

3''"//*/{)(/|)(()

Pyramid-MLM

28.4



,


.

- JJ Account

.&Ti3ii Address. j

.^.. .. ;:: .;.!'t.

28.

28.5



.

submit () store-account,
:
case 'store-account'

if (store_account(normal_user, admin_user, HTTP_POST_VARS))


action = ' ' ;
if(!eheck_logged_in())
display_login_form(action);
break;
store_account() .
28.4.
28.4 store_account() mlm_fns.php
, , .
//
//
function store_account(normal_user, admin_user, details)
if(!filled_out(details))
echo "All fields must be filled in.
return false;

Try again. <brXbr> ";

else
if(subscriber_exists(details['email1]))
// ,
//
if(get_email()==details['email'])
query = "update subscribers set realname = 'details[realname]',
mimetype = 'details[mimetype]'
where email = '" . details [email] . "' ";

44

5. MySQL
if(db_connect() S& mysql_query($query) )
return true ;
else
echo "could not store changes.<>";
return false;
else
{
echo "<p>Sorry, that email address is already registered here.
echo "<p>You will need to log in with that address to change
. " Web settings . " ;
return false ;

else //

$<juery = "insert into subscribers


values ( ' $details [email] ' ,
'$details[realname] ' ,
' $details [mimetype] ' ,
password) ' $details [new_password] ' ) ,
0)";
if (db_connect() Si mysql_query ($query) )
{
return true ;
}
else
{
echo "Could not store new account. <brXbrXbrXbrXbrXbr>" ;
return false ;

, .
, ,
. , .
get_email(), .
, ,
.

, . 28.4,
Log In (), index. php Semail Spassword. , , :

28.

28.4 ()
//
//
if ($emaili$password)
{
$login = login ($email, $pas sword) ;
if($login == 'admin')
{
$status .= "<pXb>" .get_real_name($email) . "</b> logged in"
. " successfully as <b>Administrator</bXbrXbrXbrXbrXbr>" ;
$admin_user = $email ;
session_regis ter ( "admin_user " ) ;
}
else if($login == 'normal')
{
$status .= "<pxb>" . get_real_name ($email) . "</b> logged in"
." successfully. <brXbr>" ;
$normal_user = $email ;
session_register ( "normal_user " ) ;
}

else
{

$status .= "<p>Sorry, we could not log you in with that


email address and password. <br>" ;

,
login() user_auth_fns.php.
, , . 28.5.
28.5 login() user_auth_fns.php

_
function login ($email, $password)
// ,
//
// ,
// false
{
//
$conn = db_connect() ;
if ( ! $conn)
return 0 ;
$query = "select admin from subscribers
where email= ' $email '
and password = password (' $password' )";
// $query
$ result = mysql_query($query) ;
if (!$result)
return false ;
if (mysql_num_rows($result)<l)
return false;
if (mysql_result($result, 0, 0) = 1)
return ' admin ' ;
else
return ' normal ' ;

18 Sax. 216

5. MySQL

true
false . false , : 'admin' 'normal'. ,

. , false.
, 1 (true)
'admin'. 'normal1.
, , .
$admin_user, , $normal_user,
. ,
.

get_email(). 28.6.
28.6 get_email mlmjns.php

function get_email()
global $normal_user;
global $admin_user;
if (session_ia_registered("normal_user"))
return $normal_user;
if (session_is_registered("admin_user"))
return $admin_user;
return false;

' ,
, , .
. 28.6.

Pyramid-MLM - Log In
28.6

,

.

tfvt | ' ;
Lauri Thomson logged in successfully.

28.

, ,
.


, :

. 28.6.
.



. . 28.6 : Show My Lists (
), , , Show Other Lists ( ),
, .
. 28.4, ,
Show All Lists ( ),
.
, (
, , 10 ). .
, , show-mylists, show-other-lists show-all-lists. , . :
case 'show-all-lists' :
<
display_iterns("All Lists", get_all_lists(), 'information1,
'show-archive','');
break;
}
case 'show-other-lists' :
{
display_iterns("Unsubscribed Lists",
get_unsubscribed_lists(get_email()), 'information',
'show-archive', 'subscribe');
break;
}
case ' ' :
case 'show-my-lists' :
{
display_items("Subscribed Lists", get_subscribed_lists(get_email()),
1
information', 'show-archive', 'unsubscribe');
break;
}

, display_iteras()
output_fns.php, . -

548

5. MySQL

get_email()
. . 28.7.

! -a

L*'

/Hi

Ci* Pyramid-MLM - Show Other Lists


28.7
display_items()


,

.

PHP Tipshaet;

Pyramid Newsletter

Show Other Lists ( ).


display_items(), 28.6
28.6 display_items() output_fns.php

function display_iterns($title, $list, $actionl='', $action2='', $action3='')
global $table_width;
echo "<table width = $table_width cellspacing = 0 cellpadding = 0
border = 0>" ;
//
$actions = (($actionl! = '') + ($action2! = '') + ($action3! = ''));
echo "<tr>
<th colspan = ". (l+$actions) ." bgcolor='#5B69A6'> $title </th>
//
$items = sizeof($list);
if($items == 0)
echo "<tr>
<td colspan = ". (l+$actions)."align = center>No Items to
Display</td>
else
//
for($i = 0; $items; $i++)
if($i%2) //
// ( )
$bgcolor = '"#ffffff";

28.
else
$bgcolor = " ' #ccccf f ' " ;
echo "<tr
<td bgcolor = $bgcolor
width = ". ($table_width - ($actions*149) ) .">";
echo $list[$i] [1] ;
if($list[$i] [2])
echo " - ".$list[$i] [2] ;
echo "</td>";
II
for($j = 1; $j<=3; $j++)
{
$var = 'action' .$j ;
if($$var)
{
echo "<td bgcolor = $bgcolor width = 149>" ;
II /
// ,
if($$var == 'preview-html' | |$$var == ' view-html ' | |
$$var == 'preview-text' | | $$var = 'view-text')
display_preview button ($list[$i] [3] , $list[$i] [0] , $$var)
else
display_button ( $$var, "Sid=" . $list[$i] [0] );
echo
echo "</tr>\ n" ;
}

echo "</table>" ;

,
. :

Stitle , ;
, . 28.7, "Unsubscribed
Lists" (" "), "Show Other Lists".

$Iist , . ,
. ( ) get_unsubscribed_lists(), .
,
. :

$list[n][0] ,
. , .
.

$list[n][l] . , . , , .
28.7, PHP Tipsheet.

550

5. MySQL

$list[n][2] $list[n][3] . ,
, . View Mail (
) " ".
.
,
, , .
. 28.7 : Information (),
Show Archive ( ) Subscribe ().
Show All Lists
information, show-archive subscribe. display_button()
.
, Show
dispay_items() -. ,
,
. Show All Lists
get_all_lists(), Show Other Lists get_unsubscribed_lists(), a Show My Lists
get_subscribed_Iists(). .
mlinjhs.php.
get_unsubscribed_lists(),
. 28.7.
28.7 get_imsubscribed_lists() mlm_fns.php
,

function get_unsubscribed_lists ($email)


{
$list = array () ;
p

$query = "select lists. listid, listname,


email from lists left join sub_lists
on lists. listid = sub_lists. listid
and email=' $email' where email is NULL order by listname";
if (db connect () )
{
$result = mysql query ($query) ;
if (!$result)
echo "<p>Unable to get list from database . " ;
$num = mysql_numrows ($result) ;
for($i = 0; $i<$num;
array_push($list, array (mysql_result($result, $i, 0),
mysql result ($result, $i, 1)));
return $list;

, .
, .

28.

JJ 1

get_subscribed_lists()
, , , get_all_lists()
.
,
, . ,
MySQL
LEFT JOIN.

array_push().
, , , .


Information (), . 28.7,
'information', :
case 'information' :
{
display_information($id);
break;

display_information() . 28.8.
,

( ).
28.8.

Ffc < .* fj,te..


Step

tod,

H*

Hw*

Mai

Pyramid-MLM - Information
28.8

display_information()

.

Pyramid Newsletter
Company newsletter. Contains information relevant to employees. Investors, ana otlier Interested parties.
Number of subscribers: 1
Number of messages in archived ,

J 2i

5. MySQL

28.8 display_information() outputjns.php



function display_information ($listid)
{
if (!$listid)
return false;
$info = load_list_info($listid) ;
if ($info)

echo "<h2>". pretty ($info [listname] ) . "</h2>" ;


echo '<p>' . pretty ($inf [blurb] ) ;
echo '<p>Number of subscribers: ' . $inf [subscribers] ;
echo '<p>Number of messages in archive: ' . $inf [archive] ;

Web display _information() : load_list_info() pretty(). load_list_info() . pretty()


, , HTML ..
load_list_info(). mlm_fns.php, 28.9.
28.9 loadjist_info() mlmjfns.php

_
function load_list info ($listid)
{
if (!$listid)
return false ;
if (!db_connect())
return false;
$query = "select listname, blurb from lists where listid = $listid" ;
$result = mysql_query ($query) ;
if (!$result)
{
echo "Cannot retrieve this list" ;
return false ;
}
$info = mysql_fetch_array ($result) ;
$query = "select count(*) from sub_lists where listid = $listid" ;
$result = mysql query ($query) ;
if ($result)
{
$inf [' subscribers '] = mysql_result ($result, 0, 0) ;
}
$query = "select count (*) from mail where listid = $listid
and status = ' S E N T ' " ;
$result = mysql_query ($query) ;
if ($result)
{
$ info [ 'archive1 ] = mysql_result ($result, 0, 0) ;
}
return $info;

28.

553

lists,
subjists mail.


, ,
Show Archive, ,
.
show-archive, :
case 'show-archive' :
{
display_iterns("Archive For " .get_list_name($id),
get_archive($id), 'view-html1, 'view-text1, ' ' ) ;
break;
}

display_items() , . get_archive()
mlm_fns.php. 28.10.
28.10 get_archive() mlm_fns.php

function get_archive($listid)

//
//
// (_, )
$list = array () ;
$listname = get_list_name($listid);
$query = "select mailid, subject, listid from mail
where listid = $listid and status = 'SENT1 order by sent";
if (db_connect ())
{
$result = mysql_query($query);
if(!$result)
{
echo "<p>Unable to get list from database - $query.";
return false;

$num = mysql_numrows($result);
for($i = 0; $i<$num; $i++)

$row = array(mysql_result($result, $i, 0),


mysql_result($result, $i, 1), $listname, $listid);
array_push($list, $row);

}
}
return $list;

J J 1

5. MySQL

,
, , display_items().


, . 28.7,
, . , Show My Lists , , Unsubscribe ( ).
subscribe () unsubscribe (
), , , :
case 'subscribe' :
{
subscribe (get_email () , $id) ;
display_iterns("Subscribed Lists", get_subscribed_lists(get_email()),
'information', 'show-archive', 'unsubscribe');
break;
}
case 'unsubscribe' :
{
unsubscribe(get_email(), $id) ;
display_iterns("Subscribed Lists", get_subscribed_lists(get_email()),
'information', 'show-archive', 'unsubscribe');
break;
}
(subscribeQ unsubscribeQ), display_items() ,
.
subscribeO unsubscribeQ 28.11.
28.11 subscribe() unsubscribeQ mlm_fns.php

function subscribe($email, $listid)
{
if (!$email||!$listid||!list_exists($listid) ||!subscriber_exists($email))
return false;
// ,
//
if (subscribed($email, $listid))
return false;
if (!db_connect())
return false;
$query = "insert into sub_lists values ('$email', $listid)";
$result = mysql_query($query);
return $result;
}
function unsubscribe($email, $listid)
{
if(!$email||!$listid)
return false;

if(!db_connect())
return false;

28.

555

$query = "delete from sub_lists where email = '$email' and listid =


$liatid";
$result = mysql_query($query);
return $result;

subscribeQ subjists , ; unsubscribe() .


Account Settings ( ) account-settings. :
case 'account-settings' :
display_account_form($normal_user, $admin_user, get_email(),
get_real name(get_email()), get_mimetype(get_email())) ;
break;
, - display_account_form(), . , . ,
, store-account.


Change Password ( )
change-password, :
case 'change-password' :
display_password_form();
break;
display_password_fonn() ( output_fns.php) , .
. 28.9.

28.9

display_password_Jorm()


.

Pyramid-MLM - Change Password

3J

5. MySQL

Change Password , store-change-password. :


'store-change-password' :
{
if (change_password(get_email() , $old_passwd,
$new_passwd, $new_passwd2) )
<

echo "<: Password changed . <>" ;


}
else

echo "<p>Sorry, your password could not be changed.";


display_password_form() ;

>
break ;
}

,
change_password()
. change_password()
user_auth_fns.php. 28.12.
28.12 change_password() user_auth_fns.php

_
function change_password($email, $old_password, $new_password,
$new_password_conf )
// old_pas sword
// new_password
// true false
{
// ,
// new_pas sword true,
// false
if (login ($email, $old_password) )

if ($new_pasBword==$new_paasword_conf )
{
if (!($conn = db_connect ( ) ) )
return false ;
$query = "update subscribers
set password = password (' $new_password' )
where email = ' $email ' " ;
$result = mysql_query ($query) ;
re turn $ re sul t ;
}
else
echo "<p> Your passwords do not match.";

}
else
echo "<p> Your old password is incorrect.";

return false; //
. , , , , .

28.


Log Out ( ),
log-out. :
if($action

log-out')

session_destroy() ;
unset($action);
unset($normal_user);
unset($admin_user);
, ,
. , Saction ..
- ,
:

if ( ! check_logged_in ( ) )
display_login_form($action) ;
break;
.


- ,
, . 28.10.
Create List ( ), Create Mail ( ) View Mail (
, ). .

28.10



.

Admlnlttraav* logged In successTully- 33 Admlnlitrator

j5o

5. MySQL



Create List ( ), create-list,
:
case 'create-list' :
{
display_list_form(get_email());
break;

display_list_form() ,
.
output_fiis.php. HTML-,
. . 28.11.
Save List ( ),
store-list, index.php:
case 'store-list'

if(store_list($admin_user,

$HTTP_POST_VARS))

echo "<p>New list added<br>" ;


display_i terns ("All Lists", get_all_lists ()
' show-archive ' , ' ' ) ;

'information'

else
echo "<p>List could not be stored, please try
. "again .<>" ;
break;

,
, .
store_list(). 28.13.

28.11
Create List
,

(
)
.

Pyramid-MLM - Create List

ompany newsletter. Contains information relevant to employees


investors, and other interested parties.

28.

28.13 strore_list() mlmjns.php



function store_list ($admin_user , $details)
{
if (!filled_out($details) )
i
echo "All fields must be filled in. Try again. <brxbr>";
return false;
)
else
{
if ( ! check_admin_user ( $admin_user ) )
return false;
// -,
// ?
iff'db connect ())
{
return false;
}
$query = "select count (*) from lists where listname = ' $details [name] ' " ;
$result = mysql query ($query) ;
if (mysql_result($ result, 0, 0) > 0)

echo "Sorry, there is already a list with this name.";


return false ;

$guery = "insert into lists values (NULL,

'$details[name] ' ,
' $de tails [blurb] ' ) " ;
$result = mysql_query($query) ;
return $result;

,
: , , . , lists .


- : .
Create Mail ( ), create-mail:
case 'create-mail' :

<

display_mail_f orm (get_email ( ) ) ;


break;

, . 28.12.

560

5. MySQL

.'1=
.'

. -!!'
0 .

! ....... ..... 17V


'S
!.
..... ,-',! 1.-.-,., .,,.
1

28.12
Create Mail
(
)

4! Pyramid- - Create Mail

;::

|PyrBmid Newsletter _jj

|(4-$ [os'ti'm-^
imaaei [~

:. .:

- .

, ,
: HTML
, . ,

. .
, , . , .
Subject ()
.
, Browse (). , , HTML- (, ,
). , , HTML.
.
, , .
.
display_mail_form() 28.14.
28.14 display_mail_form() output_fns.php

function display_mail_form($email, $listid=0)
// html-
global $table_width;
$list = get_all_lists() ;
$lists = sizeof($list);

28.
<table cellpadding = 4 cellspacing = 0 border = 0 width =
<?=$table_width?
<form enctype='multipart/form-data' action'upload.php1 method='post'>
<tr>
<td bgcolor = "#cccccc">
List:
</td>
<td bgcolor = "#cccccc">
<select name = list>
<?
for($i = 0; $i<$lists; $i++)
{
echo "<option value = ".$list[$i][0];
if <$listid== $list[$i][0]) echo " selected";
echo ">".$list[$i][1]."</option>\n";
}
?>
</select>
</td>
</tr>
<tr>
<td bgcolor = "#cccccc">
Subject:
</td>
<td bgcolor = "#cccccc">
<input type = text name = subject value = "<?=$subject?>"
size = 60 X/td>
</tr>
<trXtd bgcolor = "#cccccc">
Text Version:
</toXtd bgcolor = "#cccccc">
<input type=file name='userfile[0]' size = 60>
</tdX/tr>
<trXtd bgcolor = "#cccccc">
HTML Version:
</tdXtd bgcolor = "#cccccc">
<input type=file name='userfile[1]' size = 60>
</tdX/tr>
<trXtd bgcolor = "#cccccc" colspan =2>Images: (optional)
$max_images = 10;
for($i = 0; $i<10; $i++)

echo "<trxtd bgcolor = ' #cccccc' >Image ". ($i+l) ." </td>";
echo "<td bgcolor = '#cccccc'>";
echo "<input type=file name='userfile[". ($i+2) ." ] ' size = 60X/tdX/
tr>" ;
}
<trxtd colspan = 2 bgcolor = '#cccccc' align = center>
<input type = hidden name = max_images value = <?=$max_images?
<input type = hidden name = listid value = <?=$listid?
<? display_form_button('upload-files'); ?>
</td>
</form>
</tr>
</table>

J U.Z

5. MySQL

, , ,
, file,
userfile[0] userfile[n]. , , , , .
PHP- , .
, , .
.


, ,
. upload.php 28.15.
28.15 upload.php ,
.

<?

// ,
//
// - , ,
$raax_size = 50000;
include ('include_fns.php');
session_start();
//
if(!check_admin_user())

echo "You do not seem to be authorized to use this page.";


exit;

}
//
Sbuttons = array();
$buttons[0] = 'change-password1;
$buttons[1] = 'create-list';

$buttons[2] = 'create-mail' ,$buttons[3] = 'view-nail';


$buttons[4] = 'log-out';

$buttons[5] = 'show-all-lists';

$buttons[6J = 'show-my-lists';
$buttons[7] = 'show-other-lists1;

do_html_header("Pyramid-MUM - Upload Files");


display_toolbar($buttons);
// ,
if(!$userfile_name[0]||!$userfile_name[l]||!$subject||!$list)
{
echo "Problem: You did not fill out the form fully. The images are the
only optional fields.
Each message needs a subject, text version
and an HTML version. " ;
do_html_f ooter () ;
exit;
}
if (!db_connect())
{
echo "<p>Could not connect to db";
do_html_f ooter () ;
exit;

28.
//
$query = "insert into mail values (NULL, '$admin_user',
'$subject',
'$list',
'STORED1, NULL, NULL)";
$result = mysql_query($query);
if(!$reeult)
do_html_footer();
exit;
// , MySQL
$mailid = mysql_insert_id();
if(!$mailid)
do_html_footer();
exit;
// ,
//
8 mkdir("archive/$list", 0700);
//
//
if(!mkdir("archive/$list/$mailid", 0700))
do_html_footer();
exit;
//
$i = 0;
while ($userfile[$i]SS$userfile[$i]!='none')
echo "<p>Uploading ".$userfile_name[$i]." - ";
echo $userfile_size[$i] ." bytes.<br>";
if ($userfile size[$i]=0)
{
echo "Problem: $userfile_name[$i] is zero length";
continue;
}

if ($userfile_size[$i]>$max_size)
{
echo "Problem: $userfile_name[$i] is over 10000 bytee";
$i-H-;
continue;
)
// ,
// getimagesize() Heb,
// , .
if($i>lct!getimagesize($userfile[$i]))
{
echo "Problem: $userfile_name[$i] is corrupt, or not a gif, jpeg or png"
$i++;
continue;
}
// 0 ( ) 1 ( html)
//
if($i=0)
$destination = "archive/$list/$mailid/text.txt";
else if($i = 1)
$destination - "archive/$list/$mailid/index.html";
else

J 4

5. MySQL
$destination = "artihive/$list/$mailid/" .$userfile_nan\e[$i] ;
$query = "insert into images values ($tnailid, 1
1

$result = mysql_query ($query) ;

" . $userf ile_name [$i] .

" . $userf ile_type [$i] .

// 4.03
/*

if ( ! is_uploaded_f ile ($userf ile [$i] ) )


{

//
echo "Something funny happening with '$userfile', not uploading.";
do_html_footer() ;
exit;

)
move_uploaded_file($userfile[$i] , $destination) ;

*/

// 4.02
copy ($userfile[$i] , $destination) ;
unlink ($userf ile [$i] ) ;

display_preview_button($list, $mailid, ' preview-html ' )


display_preview_button($list, $mailid, 'preview-text')/
display_button ( ' send ' , " Sid=$mailid" ) ;
echo "<brXbtXbrXbrXbr>" ;
do_html_footer() ;

28.15.
, ,
, - .
, Slist Smailid , .
. , .

, .
,
.
. .
Suserfile, $userfile_name $userffle_slze , . $userffle[0], $userffle_name[0] $userffle_size[0].
, .
,
, . ,
upload.php. . 28.13.

28.

!iLJ^^c^_^!L,I!!L.

565

p://webeetver/cnapt*f28/uploud.php

Pyramid-MLM - Upload Files


;

| ' -(

28.13



.

Uploading newsletter I .txt - 284 bytes


Uploading neiBlstttn .ntml - 1653 bytes.
Uploading pyramid.giT - 2913 bytes
Uploading graph gtf-10152 Bytes.

Txt


.
,
.
, View Mail ( ),
, . View
Mail view-mail, :
'view-mail'
{
display_iterns("Unsent Mail", get_unsent_mail(get_email()),
'preview-html', 'preview-text', 'send');
break;

, display_items(),
, preview-html, preview-text send.
, "Preview" , . 28.6 28.15, ,
display_preview_button(),
display_button().
display_button() GET; display_preview_button()
. ,
target=new HTML- .
HTML- . 28.14.

566

5. MySQL

Pyramid-MLM
Press Release

28.14

According to data released tftOiy, Pyramid MLM Pty Lid is not losing money at fast as stun* oth twnpenns,
Pyramid MLM pfr Ltd lost only 12 minion dollars IMS quarter.


HTML,
.

This loss Is onty 10% more than the same period la


Send ()
send, :
case 'send'

{
send($id,
break;

$admin_user);

send(), mlm_fns.php.
- . , HTML
MIME Mail.
28.16.
28.16 sendQ mlmjfns.php , ,
//
//
//
function send($mailid, $admin_user)
if(!check_admin_user($admin_user))
return false;
if(!($info = load_mail_info($mailid)))
echo "Cannot load list information for message $mailid";
return false;
$subject = $info[OJ;
$listid = $info[l];
Sstatus = $info[2];
$sent = $info[3];
$from_name = 'Pyramid MUi';
$from_address = 'return@address';
$query = "select email from sub_lists where listid = $listid";

28.

5 /

$result = mysql_query($query);
it (ISresult)
{
echo $query ;
return false;
)
else if (mysql_num_rows ($result)=0)
{
echo "There is nobody subscribed to list number $listid";
return false ;
}
else
{
include ( ' class . html . mime . mail . inc ' ) ;
$mail = new html_mime_mail() ;
//
$filename = "archive/$listid/$mailid/text.txt";
$fp = fopen ($filename, "r") ;
$text = fread($fp, f ilesize ($f ilename) );
fclose ($fp) ;
// HTML-
$filename = "archive/$listid/$mailid/index.html";
$fp = fopen (Sf ilename, "r") ;
$html = fread($fp, f ilesize ($f ilename) );
fclose ($fp) ;
// ,
$query = "select path, mimetype from images where mailid = $mailid";
if (db_c6nnect ( ) )
{
$result = mysql_query($query) ;
if(!$result)
{
echo "<p>anable to get image list from database . " ;
return false;
}
$num = mysql_numrows ($result) ;
for{$i = 0; $i<$num,- $i-H-)
{
//
$f ilename = "archive/$listid/$mailid/".mysql_result($result, $i, 0) ;
$rp = f open ($f ilename, 'r');
$image = fread($fp, f ilesize ($f ilename) );
f close ($fp);
// mimemail
$roail->add_htnu_image ($ image ,
mysql_result($result, $i, 0),
mysql_result($result, $i, 1));

// HTML- mimemail
$mail->add_html ( $html , $text) ;
// ,
// ,
$mail->build_message() ;
if($status = 'STORED')
{

// HTML-
$mail->send(get_real_name($admin_user) , $admin_user,
$from_name, $from_address, $subject) ;
//
mail (get_real_name ($admin_user) . " <".$admin_user. ">", $subject,
$text, "From: $from_name <$from_address>") ;
echo "Mail sent to $admin_user" ;

568

5. MySQL
$query = "update mail set status = 'TESTED' where mailid = $mailid";
if (db_connect() )

$result = mysql_query($query) ;

echo "<p>Press send again to send mail to whole list . <center>" ;


display_button ( ' send ' , " Sid=$mailid" ) ;
echo "</center>" ;

)
else if($status == 'TESTED')
{

//
$query = "select subscribers . realname , sub_lists . email ,
subscribers .mine type
from sub_lists, subscribers
where listid = $listid and
sub_lists . email = subscribers. email";
if (!db_connect())
return false ;
$result = mysql_query(Squery) ;
if (!$result)
echo "<p>Error getting subscriber list" ;
$count = 0;
//
while ( $subscriber = mysql_fetch_row($result) )
{

if <$subscriber[2]='H')
// HTML- ,
$mail->send($subscriber[0] , $subscriber[l] , $from_name,
$f rom_address , $subject) ;
else
// ,
mail($subscriber[0] ." <".$subscriber[l] . ">", $subject,
$text, "From: $from_name <$f rom_address>" ) ;
$count++;

)
$query = "update mail set status = 'SENT' , sent = now()
where mailid = $mailid";
if (db_connect ( ) )
(

$ result = mysql_query ($query) ;

echo "<p>A total of $count messages were sent.";


}
else if($status = 'SENT')
<
echo "<p>This mail has already been sent . " ;

.
,
. , . ,
"STORED" ("").
send() , "STORED",
"TESTED" ("") . -

28.
"TESTED" ,
. - "TESTED", "SENT"
(""), .
,
: .
: , PHP- mailQ, HTML-, HTML MIME Mail. mail()
,
HTML MIME Mail. ,
, .
:
include('class.html.mime.mail.inc');
$mail = new html.mime.mail ();

, , :
$mail->add_html_image($image,
mysql_result($result, $i, 0) ,
mysql_result($result, $i, 1 ) ) ;
, add_html_image(), , , 1-
.
, HTML-:
$mail->add_html($html, $text) ;
:
$mail->build_message() ;
, , .
,
, send() HTML MIME Mail mail(), MIME, :
if($subscriber[2]=='H')
// HTML- ,
$mail->send($subscriber[0], $subscriber[1], $from_name,
$from_address, $subject);
else
// ,
mail($subscriber[0]." <".$subscriber[1].">", $subject,
$text, "From: $from_name <$from_address>") ;
Small->send()
, .
! .

J /\)

5. MySQL


, . :

,
. , .

.

,
.

,
.

, . ,
, . ,
.


Web-, ,
.

29

Web-

Web-. ,
.
Web- .

,
Phorum.
Web-
. ,
,
.
.
Web-, blah-blah :

, .. , .

. -
, .

Book-O-Rama.

J / 2.

5. MySQL

, ,
. .., , ( ), .
, ,
, Slashdot:
http://slashdot.org

. ,
.

.
.


,
.
,
,
.
. 29.1.

1 1

1 1

1 3

29.1 ,
.

29. Web-

57J

, ,
, . . ,
, ..
,
. . ,
, , .
( ) ( ). (
,
.)
, :
1. ; MySQL.
2. .
MySQL,
.
,
.
, , PHP- tree_node. tree_node
.
. ,
tree_node, ,
tree_node, .. - , . , . 29.1.
: , ,
.
. , .

.

,
, .


. ( 5.)
,

.
.


, , , , . , , .

574

5. MySQL

.
,
. , ,
. ( .)

.

, .
. 29.2.

(
)
29.2
blahblah
.

. 29.1
29.1 Web-

index.php

,
.
,
.

new_post.php

, .

storej_new_post.php

, new_post.php.

view_post.php

treenode_class.php

treenode,
.

include_fns.php


(
),
.

data_valid_f ns. php

db_fns.php

discussion_fns.php

output_fns.php

HTML.

creaf e_database. sql

SQL

SQL ,
.

29. Web-

575


, , : , (); ;
; . , . , postid.
.
.
, , .
, , .. , .
:
postid:

parent: postid

poster:
title:

posted:

message:

.
, - , - , .
. ,
. , ,
. children
1, , 0, .
.
. , ,
. . , .
, . , .
, . , Oracle . MySQL, , ,
- .
. . ,
text MySQL. . , . ,
, .

576

5. MySQL

MySQL , . , ,
.
, ,
, .
, , , , .
, area , .
, .
SQL-, , 29.1.
29.1 create_database.sql SQL-,
create database discussion;
use discussion;
create table header
(

parent int not null,


poster char(20) not null,
title char(20) not null,
children int default 0 not null,
area int default 1 not null,
posted datetime not null,
postid int unsigned not null auto_increment primary key

);

create table body


(

postid int unsigned not null primary key,


message text

);
grant select, insert, update, delete
on discussion.*
to discussion@localhost identified by 'password';

, MySQL :
mysql -u root -p < create_database. sql

root. , , , -
.
, ,
. 29.3.
, postid ,
. , .

29. Web-

29.3



.

postid: 1

postid: 0

postid: 2

postid: 1


postid: 1

t/ Ni

postid: 2
postid: 3

postid: 1

postid: 4

postid: 2

postid: 5

postid: 2

5/7

If

| postid: 4

I postid: 3 I

^^A

postid: 5 I

, postid 1 .
.
0 ().


.
index.php. new_post.php store_new_post.php. .
, .
.
, ,
. 29.4.
, , .
; .
, . ,
.
, .
. , . , .
. 29.5.

29.4



""
.

19 . 216

J /

5. MySQL

,
. . , , .
, , . , .
, ,
.
, Expand () Collapse (), . Expand . 29.6.

1 .

:k

1 . -i)
, '

-_' 1 - '_>j

:."

Reirwsb

';<:*"'

!ki!u"

[ rv-nVii

:<2

,;;-,-

ehtlp://vmtis8lver/di4Jter29/mdex.php?Biipwid-6*6

I ^pipP Discussion Posts


29.5


"persistence"
(" ").

(NewPost; Expand j'Coli


EB PHP setuo? - FrecU 01-39

-" &1^?>&^-4' ^'.'^'!'. . 111


persistence? - archer- Q1.43 09/26/2000
"; .^J33 Efejjgrsi'isteQgjj?-;kaua,-,.QT:j.g,pgsg^pQp '
Re: flersistenqe? - newbig - 01:52 9/2/2000
-:':^1^^&-&^0$!2.

new article - - 01:54 Q9/2B/20DD

11
';':,:^^'

Slop

1
H i b . 1,

4
'..

'

U "''M. '
', >,.|
!!..!.",

3http://webseiver/chapler29/indBxphp?expand-eil

^^ Discussion Posts
!

29.6

NewPost; Expand Coili

PHP setup?-Fred-01 39 09/2


|.. . Re: PHP Setup?. Laurq -1

'2 ,,:..; !

Re: PHP ?-1.|.1:4

): v".R : e PHP^^nvi

i^fea^g'^tSf:^

using gd?- newtjjg- D1'.4IQ9/26/2QOl3

BJpersist^npe?- ar^rjer-Qi^'g.pg/gS^OJlQ"^ Hi
Re- persistence? - Laura - D1:43 Q9/2G/20DQ

/--." -'\H :.'U3X'-'"


- ; ' : ' ; ^".-^'"'-". ,"^
.LJ ;31^8-.1: ^~ Q'-'47 08f2B/j
:

Re: persistence?- Luke- Qi-.

Re persistence?- Barry - 05:07 /jSC

' !

29. Web-

. 29.5 29.6, , index.php. . 29.5


Internet- :
http://webserver/chapter2 9/index.php?expand=6#6

"
postid 6". # HTML,
.
Internet-
http://webserver/chapter29/index.php?expand=all

Expand expand all.


, , index.php, 29.2.
29.2 index.php

<?

include ('include_ns.php');
session_start() ;
// ,
if(!session_is_registered('expanded'))

$expanded = array () ;
session_register('expanded');

>

// , expand
// expand 'all',
// postid
if ($expand)

if($expand == 'all')
expand_all($expanded);
else
$expanded[$expand] = true ;

>
// , collapse
// collapse 'all1,
// postid
if($collapse)

i f($collapse=="all")
unset($expanded);
else
unset($expanded[$collapse]);

}
do_html_header("Discussion Posts");
display_index_toolbar();
//
display_tree($expanded);
do_html_f ooter () ;

JU

5. MySQL

:
Sexpanded, .
,
. , postid
, .
Sexpand, , .
Scollapse, , .
Expand Collapse
index. php
Sexpand Scollapse. Sexpanded
, .
Sexpanded , .
, Sexpand
Scollapse, Sexpanded. ,
Sexpand:
if ($expand)
{

if($expand == ' a l l ' )


expand_all ($expanded) ;
else
$expanded[$expand] = true;

Expand expand_all()
, , Sexpanded. (
.)
, postid Sexpand. Sexpanded.
expand_all() 29.3.
29.3 expand_all() discussion_fns.php
Sexpanded
_
function expand all (S$expanded)
<
//
//
$conn = db_connect() ;
$query = "select postid from header where children = 1";
$result = mysql_query ($query) ;
$num = mysql_numrows ($result) ;
for($i = 0; "$i<$num; $i++)

$expanded[mysql_result ($result, $i, 0)]=true;

,
:
select postid from header where children = 1

29. Web-

51

Sexpanded. .
,
.
, :
if ($collapse)
{

if ($collapse=="all" )
unset ($expanded) ;
else
unset ($expanded[$ collapse ] ) ;

Sexpanded , .
, .
,
, , .
display_tree ($expanded) ;

display_tree(), 29.4.
29.4 display_tree() output_fns.php

function display_tree($expanded, $row = 0, $start = 0)

//
global $table_width;
echo "<table width = $table_width>" ;
// ,
if ($start>0)
$sublist = true;
else
$sublist = false;
// ,
$tree = new treenode ($start, '', ", ", 1, true, -1, $expanded,
$sublist) ;
//
$ tr ->di splay ($row, $sublist) ;
echo "</table>" ;

. ,
view_post.php. , . ,
Sexpanded. postid, . , Srow, ,
.

3 2.

5. MySQL

, Sstart, , . postid , . , ,
0, .. ,
. Ssublist false .
0, , , Ssublist true . ( view_post.php.)
, treenode, . , , . ,
.

treenode
treenode 29.5. ( 6, , .)
29.5 treenode treenode_dass.php

<?
//
// ,
class treenode

// -,
// , ,
//
var $m_postid;
var $m_title;
var $m_poster;
var $m_posted;
var $m_chiIdren;
var $m_childlist;
var $m_depth;
function treenode($postid, $title, $poster, $posted, $children,
$expand, $depth, $expanded, $sublist)
{
// -, ,
// ,
$this->m_postid = $postid;
$this->m_title = $title;
$this->mjposter = $poster;
$this->m_posted = $posted;
$this->m_children =$children;
$this->m_childlist = arrayO;
$this->m_depth = $depth;
// , ,
// ,
//
if(($sublist||$expand) && $children)

{
$conn = db_connect () ;

29. Web-
$query = "select * from header where parent =
$postid order by posted";
$result = mysql_query ($query) ;
for ($count=0; $row = @mysql_fetch_array ($result) ; $count-M-)
{
if ($sublist| |$expanded[ $row[ 'postid' ] ] == true)
$expand = true;
else
$expand = false;
$this->m_childlist [$oount] =
new treenode($ row ['postid'] ,$row[ 'title'] ,
$row[ 'poster ' ] ,$row[ 'posted' ] ,
$row[ ' children ' ] , $expand,
$depth+l , $expanded, $sublist) ;

function display ($row, $sublist = false)


{
// ,
//
// $row ,
// ,
//
//
//
//
//

$sublist ,
.
$sublist - true.

"+" "-".

// ,
//
if ($this->m_depth>-l)
{
//
echo "<trXtd bgcolor = " ;
if ($row%2)
echo " ' #cccccc ' >" ;
else
echo '"#ffffff '>";
//
for($i = 0; $i<$this->m_depth; $i++)
{
echo "<img src = ' images/spacer, gif height = 22
width = 22 alt = ' ' valign = bottom>" ;
>
// "+", "-"
if ( !$sublist SS $this->m_children &S
sizeof ($this->m_childlist) )
// ,
// ,
{
//
//
echo "<a href = ' index. php?collapse=" .
$this->m_postid. "#$this->m_j>ostid'
Ximg src = ' images/minus. gif ' valign = bottom
height = 22 width = 22
alt = 'Collapse Thread' border = OX/a>" ;

53

584

5. MySQL
else if(!$sublist && $this->m_children)

//
echo "<a href = ' index. php?expand=" .
$this->m_postid. "#$this->m_postid'>
<img arc = ' images/plus .gif '
height = 22 width = 22
alt = 'Expand Thread' border = OX/a>" ;

>
else
{
//
//
echo "<img src = ' images/spacer .gif height = 22
width = 22
alt = ' ' valign = bottom>" ;
}
echo " <a name = $this->m_postid Xa href =
1
view_post . php?postid=$ this->m_postid ' >$this->m_title $this->m_poster - " . ref ormat_date ($this->m_posted) . "</a>" ;
echo "</tdX/tr>" ;
//
//
$row++;

}
// display
// ,
// ,
$num_children = sizeof ($this->m_childlist) ;
for($i = 0; $i<$num_children;
$row = $this->m_childlist[$i]->display ($row, $sublist) ;
}
return $row;

I ;

, .
treenode
. -:
var
var
var
var
var
var
var

$m_postid;
$m_title;
$m_poster;
$m_posted;
$m_children;
$m_childlist;
$m_depth ;

, treenode . ,
view_post.php. ,
,
.

29. Web-

JJ

,
- _, , - .

header .
$m childlist $m_depth. $m_chUdlist
. $m_depth

.
:
function treenode($postid, $title, $poster, $posted, $children,
$expand, $depth, $expanded, $sublist)
{

// -, ,
// ,
$this->m_postid = $postid;
$this->m_title = $title;
$this->m_poster = $poster;
$this->m_posted = $posted;
$this->m_children =$children;
$this->m_childlist = array();
$this->m_depth = $depth;

treenode display_tree()
, . :
$tree = new treenode ($start, '', '', '', 1, true, -1,
$expanded, $sublist);
, Spostid .
,
. -1, .
. .
, . . ,
- , :
if(($sublist||$expand) && $children)
{

$conn = db_connect();


:
$query = "select * from header where parent =
$postid order by posted";
$result = mysql_query($query);
$ra_childlist treenode,
, treenode:

586

5. MySQL

for
{

($count=0; $row = @mysql_fetch_array($result); $count++)

if($sublist||$expanded[ $row['postid'] ] == true)


$expand = true ;
else
$expand = false;
$this->m_childlist[$count]= new treenode($row['postid'],$row['title'],
$row['poster'],$row['posted'],
$row['children'], $expand,
$depth+l, $expanded, $sublist);

treenode
, .
. treenode, postid 1 .
treenode
,
.
, treenode ( display_tree()):
$tree->display($row,

$sublist);

displayQ , :
if($this->m_depth>-l)

.
. ,
, .
, .
(%)
( ):
//
echo "<trxtd bgcolor = ";if ($row%2)
echo "'#cccccc'>";
else
echo "'#ffffff'>";
- $m_depth ,
. , , , . :
//
for($i = 0; $i<$this->m_depth; $i++)
<
echo "<img arc = ' images/spacer .gif height = 22
width = 22 alt = ' ' valign = bottom>" ;

29. Web-

J /

, , :
//
if
//
//

"+", "-"
( !$sublist && $this->m_children && sizeof ($this->m_childlist) )
,
,
//
echo "<a href = ' index. php?collapse=" .
$this->m_postid. "#$this->m_postid'
Ximg src = ' images/minus . gif ' valign = bottom
height = 22 width = 22 alt = ' Collapse Thread ' border = Ox/a>" ;

>
else if(!$sublist SS $this->m children)
{
//
echo "<a href = ' index. php?expand=" .
$this->m_postid. "#$this->m_postid'Ximg src = ' images/plus .gif
height = 22 width = 22 alt = 'Expand Thread1 border = Ox/a>" ;
}
else
{
// ,
//
echo "<img src = ' images/spacer .gif ' height = 22 width = 22
alt = ''valign = bottom>" ;
}

:
echo " <a name = $this->m_postid Xa href =
'view_post.php?postid=$this->m_postid'>$this->m_title $this->m_poster - " .reformat_date($this->m_posted) . "</a>" ;
echo "</tdX/tr>" ;

:
//
//
$row++;
,
treenode, :
// display
// ,
// ,
$num_children = sizeof ($this->m_childlist) ;
for($i = 0; $i<$num_children;
$row = $this->m_childlist[$i] ->display ($row, $sublist) ;
}
return $row;

, , .
, . .

5. MySQL

. . , , ,
, .


display_tree() .
, viewjost.php postid, , .
, , . 29.7.
Die

Y<'w

FavnUi.4

I'H'i;

Help

1'-.

:;'0:1

i lump

Hisjaiy.

) http://wsbse[vef/chfspter29/viewj305tphp?postid-6

_Index_j
29.7


.

How do 1 make a variable carry over from page to page?


Archer

Re: persistence? - Laura - OV13 D9/2MOOO

Re: persistence? - Luke - 01:51 03/26/2DOQ


>2 09/2B/2QQQ

' U"

, .
, , . Ssublist.
viewjost.php, 29.6.
29.6 view_post.php
//
include ('include_fns.php') ;
//
$post = get_post($postid);
do_html_header($post["title"]);
//
display_post($post);
// - ,
// 1
if($post['children ])
echo "<>" ;

29. Web-
display_replies_line();
display_tree($expanded, 0, $postid);
}

do_html_footer();

: get_post(), display_post() display_tree().


get_post() .
29.7.
29.7 get_post() discussionjns.php -

function get_post($postid)
{
//
if(!$postid) return false;
$conn = db_connect() ;
// 'header1
$query = "select * from header where postid = $postid" ;
$result = mysql_query ($query) ;
if (mysql_numrows ($result) !=1)
return false;
$post = mysql_fetch_array ($result) ;
//
$query = "select * from body where postid = $postid" ;
$result2 = mysql_query ($query) ;
if (mysql_numrows ($result2) >0)
{

$body = mysql_fetch_array ($result2) ;


if ($body)
{

$post [' message '] = $body[ 'message' ] ;

}
}
return $post;

postid, ,
, .
display_post() output_fns.php. ,
HTML-, .
, view_post.php , -
, display_tree()
.. - .


, .
: -, New Post (

590

5. MySQL

) , -, Reply
() view_post.php.
new_post.php,
. . 29.8 , new jost.php
Reply.

hp7/webseiver/ctiaptet23/ne<_postphp?pMent-5

29.8

,

can someone explain to me how I can use gd to


dynamically create buttons?

-, Internet-:
http://webserver/chapter29/new_post.php?parent=5

, parent, postid . Reply


New Post, Internet- parent=0.
-, ,
">",
.
-, "Re:".
, .
29.8.
29.8 new_post.php

include ('include_fna.php');
if(!$area)
$area = 1;
if (!$error)
if (! $parent)
$parent = 0;

29. Web-

5,71

if(!$title)
$title = "New Post";

}
else
{
//
$title = get_j>ost_title($parent) ;
// Re:
if(strstr($title, "Re: ") == false )
$title = "Re: ".$title;
// , -
Stitle = substr($title, , 20);
// ,
$message = add_quoting(get_post_message($parent));

>
)
do_html_header("$title");
display new_post_form($parent, $area, $title, $message, $name);
if ($error)
echo "Your message was not stored.
Make sure you have filled in
all fields and try again. " ;
do_html_footer () ;

,
- . , .
(Sparent postid ), :
//
$title = get_post_title($parent);
// Re:
if(strstr($title, "Re: ") == false )
$title * "Re: ".$title;
// , -
$title = substr($title, 0, 20);
// ,
$message = add_quoting(get_post_message($parent));

get_post_title(), get_post_message() add_quoting()


discussion_fns.php. , , 29.9, 29.10
29.11.
29.9 get_post_title() discussionjns.php

function get_post_title($postid)
{
//
if(!$postid) return "";
$conn = db_connect() ;
// 'header'
$query = "select title from header where postid = $postid";

j;7 L

5. MySQL
$result = mysql_query($query);
if(mysql_numrows($result)!=1)
return "" ;
return mysql_result($result, 0, 0) ;

29.10 get_post_message() discussion_fns.php



function get_post_message($postid)
{

//
if(!$postid) return "";
$conn = db_connect();
$query = "select message from body where postid = $postid";
$result = mysql_query($query);
if(mysql_numrows($result)>0)

return mysql_result($result,0,0);

, , .
29.11 add_quoting discussionjns.php
">"
function add_quoting($string, $pattern = "> ")
// ,
//
return $pattern.str_replace("\n", "\n$pattern", $string);

add_quoting() ,
, >.
Post (), store_new_post.php. , , . 29.9.
Re: using gd? Laura 08:28
09/26/2000. index.php.
store_new_post.php. 29.12.
29.12 store_new_post.php
<?
include ("include_fns.php");
if($id = store_new_post($HTTP_POST_VARS))
{

include ("index.php");

else
{

$error = true;
include ("new_post.php");

29. Web-

New Post; [Expand I Collapse;


29.9

.

3 PHP seiup? - Fred - QMS 9


:

" '.'' :

..' ': '.

Re: using ad? - Laura - P9:3B P9/2B/2QOP

existence? - - 07 09'2b/?0!JD
te--01- Qflfet

caivs modulg - big coder- QJ:55 Q9/25/20GQ

, .
store_new_post(). . , . new_post.php, .
store_new_post() 29.13.
29.13 store_new_post() discussion_fns.php

function store_new_post($post)
//
$conn = db_connect() ;
// ,
if(!filled_out($post))
return false;
$post = clean_all($post);
//
if($post["parent"]!=0)
$guery = "select postid from header where postid =
"'.$post[ 'parent'] ." '";
$result = mysql_guery($query);
if(mysql_numrows($result)!=1)
return false;

// ,
$query = "select header.postid from header, body where
header.postid = body.postid and
header.parent = ".$post['parent1]." and
header.poster = '".$post['poster']."' and

594

5. MySQL
1

header.title = '" .$post['title ]."' and


header.area = ".$post['area' ] . " and
1
body.message = '".$post['message ]."'";
$result = mysql_query($query);
if (!$result)
return false;
if(mysql_numrows($result)>0)
return mysql_result($result, 0, 0);
$query = "insert into header values
('".$post['parent']."',
'".$post['poster']."',
"'.$post['title']."',
0,
1
".$post['area']."',
now() ,
NULL
$result = mysql_query($query);
if (!$result)
return false;
// ,
//
$query = "update header set children = 1 where postid *
".$post['parent'];
$result = mysql_query($query);
if (!$result)
return false;
// . ,
// ,
// , , .
$query = "select header.postid from header left
join body on header.postid = body.postid
where parent = '".$post["parent"]."'
and poster = '".$post["poster"]."'
and title = '".$post["title"]."'
and body.postid is NULL";
$result = mysql query($query);
if (!$result)
return false;
if(mysql_numrows($result)>0)
$id = mysql_result($result, 0, 0) ;
if($id)
$query = "insert into body values ($id, '".$post["message"]."')";
$result = mysql query($query);
if (!$result)
return false;
return $id;

29. Web-

, . ,
,
.
Web-.

,
,
, .

, .

- .


.
Phorum Web-
. ,
. Phorum ,
.
:
http://www.phorum.org
phpslash. , Slashdot. Perl, PHP-. :
http://www.phpslash.org


30 PDF- , .
,
.

30



(PDF)


, .
,
, .
, ,
.
:
PHP-,
(Rich Text Format, RTF).


(Portable Document Format, PDF).
PHP- PDFlib PDF-.


, . -

30. PDF

5 7

, .
, .
.
,
. :
1. .
2. ,
.
3. .
4. .
5. .
6. .
7. .
8. .
9. .
10. .
, ,
,
, , .


, . , ASCII-, HTML,
Microsoft Word - , RTF, PostScript PDF.
,
.


.
.
, , . , .
,
5- 6-. . ,
.
, ,
. .

Js

5. MySQL

ASCII
ASCII . . , .
.
, ASCII-, . . .
.
.

HTML
Web HTML.
Hypertext Markup Language ( )
. , , , , , ,
( ) .
, ,
.
HTML- : , ; ; . , HTML-
,
.


, ,
. Internet
. , ,
Microsoft Word .
Word, , .
Windows, Word, Word
http://www.rnicrosoft.com/office/000/viewers.htm

Microsoft Word .
Word .
, . ,
, Word .
, Word ,
. ,

30. PDF

599

. , ,
.


, RTF-, , Word, . -
. - ,
. -, - , , .
RTF Microsoft Word.
.
HTML-.
, , .
.

http://msdn.microsoft.com/library/apacs/rtfspec.htm

RTF- Save As RTF ( RTF) . RTF- , , .


, , Word. , ,
RTF- Word , .
Word RTF- . , ,
, .
, RTF- , Word - ;
; ; ;
.
, . , RTF , .
.
RTF- , .

5. MySQL

PostScript
PostScript, Adobe,
. ,
. , , , .
. , ,
, Web-.
PostScri pt- , , , . PostScri pt- , PostScript.
.
PostScript- . .
PostScript
:
.
, .
UNIX PostScript-, Windows, , ,
GSview, Ghostscript PostScript. . ,

.
Ghostscript :
http: //www.ghostscript.com/
:
http : //www . cs . wise . edu/ -ghost/

PostScript ,
.


, , PostScript,
.
(Portable Document Format, PDF), Adobe,
,
.
, Adobe, PDF "
- . PDF
Adobe , ,
-

30. PDF

0(J 1

, . PDF-
, , , , , Adobe Acrobat Reader".
PDF :
http://partners.adobe.com/asn/developer/technotes.html

Web- .
, PDF .
PDF- ,
, . .
. .
PDF , PDF- .
PDF- , Adobe Acrobat Reader Windows, UNIX Macintosh. .pdf , ,
.
PDF- , , ,
. PDF-.


,
( ) , .
: PDF- RTF-.
,
.


,

,
, .

, Web.
.

. HTML- ,
PHP- . , 1.

OU,Z

5. MySQL


RTF- PDF-
Web- ,
. PHP- PDF-,
PDF PHP-. (
.)

RTF-
RTF-
. Microsoft Word.
CD-ROM .
,
Word,
.

PDF-
PDF- . Adobe Acrobat. PDF- .
.
Microsoft Word. , Acrobat Adobe Distiller. Distiller
, . ASCII, . , PDF- , .
Acrobat
http:/www.adobe.com/products/acrobat/

Internet, .
PDF- psZpdf, , , PostScript-
PDF-. , . ,
. psZpdf Ghostscript.
, PDF- ,
PostScript-. , UNIX
a2ps dvips.
Windows PostScript- , Adobe Distiller, . PostScript. ,
Apple LaserWriter IINT. PostScript ,
Adobe:
http://www/adobe.com/support/downloads/5672.htm

30. PDF

03

PostScript-
Print to File ( ),
Print ().
Windows- ..
PostScript-., ,
.ps.
GSview PostScript- PDF ps2pdf.
, PostScript- . , PostScript- ps2pdf .
PDF-, , Adobe. $9,99

PDF-. ,
, . PDF- . .

http://createpdf.adobe.com/

, ,
.
, FTP, ps2pdf Net Distiller:
http://www.babinszki.com/distiller/

PDF-
PDF- . , .
, .
PHP- PDFlib, :
http://www.pdflib.com

, ClibPDF, :
http://www.fastio.com/

. API
PDF-. PDFlib, ,
, .
, . , , .

604

5. MySQL

, PDFlib , ,
phpinfo(). pdf , PDFlib, .
PDFlib TIFF,

http://www.libtiff.org/
JPEG,
ftp://ftp.uu.net/graphics/jpeg/
UNIX configure make. with-pdflib.
Windows PDFlib
,
Web. , , Windows
http://php.weblogs.com/easywindows

http://www.php 4win.de


, .
. , , , :
RTF- .
PDF- .

PDF- PDFlib.

RTF-

30.1




.

RTF-

PDF-

PDRib

30. PDF

605

, ,
.
30.1 , Certification

index.html

HTML- HTML-,

score, php

rff.php

pdf.php

PDF-

pdflib.php

PDF-
PDFlib

signature.tif

,
PDFlib

PHPCertification.rtf

RTF-

RTF-

PHPCertificafion.pdf

PDF-

PDF-

RTF-


index.html . HTML-,
, . , .
, HTML- .
name . ,
, , . , .
30. 1 .
30.1 index.html HTML-, _
<html>
<body>
< align = center>
<img src = "rosette.gif" alt = "">
Certification
<img src = "rosette.gif" alt = ""X/hl>
<p>You too can earn your highly respected PHP certification
from the world famous Fictional Institute of PHP Certification.
<p>Simply answer the questions below:
<form action = score. php method = post>
<p>Your Name <input type = text name = name>
<p>What does the PHP statement echo do?
<liXinput type = radio name = ql value = 1>
Outputs strings.
<liXinput type = radio name = ql value = 2>
Adds two numbers together.
<lixinput type = radio name = ql value = 3>

606

5. MySQL
Creates a magical elf to finish writing your code.

<p>What does the PHP function cos() do?


<lixinput type = radio name = q2 value = 1>
Calculates a cosine in radians.
<liXinput type = radio name = q2 value 2>
Calculates a tangent in radians .
<liXinput type = radio name = q2 value 3>
It is not a PHP function it is a lettuce.
<p>What does the PHP function mail do?
<lixinput type radio name = q3
Sends a mail message.
<liXinput type = radio name = q3
Checks for new mail.
<liXinput type e radio name = q3
Toggles PHP between male and

value = 1>
value = 2>
value * 3>
female mode.

<p align = centerXinput type = image src


border = 0>
</form>
</body>
</html>

"certify-me.gif"

index.html Web- . 30.2.


, index.html,
.
score.php, 30.2.

Certification
You too your ttighl.? respected PHP certification from the wortd
ftmoui Piewn) Institute of PHP

30.2
index.html


.

Simple answer the quenioni below


Yen.
Wh dcei the PHP lUtemcnt echo da?
l. Outputs ling*.
1. r Mbmmibnitoilte

I.
2
3.

Cdculat*coerofaiiflt
^ Calculate! > tangent n tadtani.
f ItttnotkPHPfutictiotiicistlettuce

WhttdocttbePHP&mcuQn najlO W
I.
3.
3

t" Sendi lualraeifage


Cherkjfcf new mill
Toale PHP between mik Mid fcmile mode

30. PDF

0 7

30.2 score.php

<?
//
if($ql=="||$q2==' '||$q3==' '||$name==' )
{
echo "<hlXp align = centerXimg = 'rosette,gif' alt = ' '>
Sorry:
<img see = 'rosette.gif alt = ' 'X/hl>";
echo "<p>You need to fill in your name and answer all questions";
}
else
{
//
Sscore = 0;
if (Sql == 1) // ql 1
$score++;
if($q2 == 1) // q2 1
$score++;
if($q3 == 1) // q3 1
$score++;
//
$score = $soore / 3 * 100;
if($score < 50)
{
/I
echo "<hlXp align = centerXimg src = ' rosette. gif' alt = ' ' >
Sorry:
<img src = 'rosette.gif' alt = ' 'X/hl>";
echo "<p>You need to score at least 50% to pass the exam" ;
}
else
{
// ,
//
$score = number_format($score, 1);
echo "<hlXp align = centerXimg src = 'rosette.gif' alt = ' '>
Congratulations
img src = 'rosette.gif' alt = 'TX/hl>";
echo "<p>Well done $name, with a score of $score%,
you have passed the exam. ";
// ,
//
echo "<p>Flease click here to download your certificate as
a Microsoft Word (RTF) file. ";
echo "<form action = 'rtf.php' method = get>";
echo "<center>
<input type = image src = 'certificate.gif border = 0>
</center>";
echo "<input type = hidden name = score value = r$score'>";
echo "<input type = hidden name = name value = '$name'>";
echo "</form>" ;
echo "<p>Please click here to download your certificate as
a Portable Document Format (PDF) file. ";
echo "<form action = 'pdf.php' method = get>";
echo "<center>
<input type = image src = 'certificate.gif border = 0>
</center>";
echo "<input type = hidden name = score value = '$score'>";

DUO

5. MySQL
echo "<input type = hidden name = name value = '$name'>";
echo "</form>" ;
echo "<p>Please click here to download your certificate as
a Portable Document Format (PDF) file generated with PDFLib. ";
echo "<form action = 'pdflib.php' method = get>" ;
echo "<center>
<input type = image src = 'certificate.gif border = 0>
</center>";
echo "<input type = hidden name = score value = '$score'>";
echo "<input type = hidden name = name value = '$name'>";
echo "</form>" ;

,
.
,
. . 30.3.

'.'*.''. V ;.
* '

30.3
score.php

,
,

Susp

".a

*~^'

dJ V: a

iiJ

:J

-i-;

' .

Congratulations
WeD done Luke WeBing, with a score of ., you have passed the exam.
Please click here to download your certificate 83 a Microsoft Word (RTF) file.

Please cSckhercto download your certificate as a Portable Document Format (PDF) file.

Please click here to download your certificate as a Portable Document Format (PDF) Ele generated wubPDFUb

. RTF PDF-. , .

RTF-
RTF-, ASCII ,
.
RTF-:

{\rtfi

{\fonttbl {\fO Arial;}{\fl Times New Roman;}}


\fO\fs28 Heading\par
\fl\fs20 This is an rtf document. \par

30. PDF

609

, : Arial,
), Times New Roman, . Heading,
fo (Arial) 28 (14 ). \ . This is an rtf document,
(Times New Roman) 20 (10 ).
,
, , . ,
, ,
. .
, . 30.4, ,
.
, NAME
. .
, . , . , , , .
NAME, Name, score
mm/dd/yyyy. , NAME, Name, .
, , .
rtf.php 30.3.

,.....,..
BL- 9 is tt 9 - -' -

PHP Certification
30.4

,

.

ha* demonstrated that they an certifiable by parsing a rigorous exam


consisbng of three multiple choice questions.
Name obtained a score ofscore>:
The test was t and overseen by the
ttofuJInrtltut* of PHP Certification

n mm/dd/yyyy'>.

4: I

20 . 216

| v

1U

5. MySQL

30.3 rtf.php -

RTF-
<?

___________

//
if ( !$name I I !$score )

echo "<hl>Error :</hl>This page was called incorrectly";

else

// ,
/ /
header ( "Content-type: application/msword" ) ;
header ( "Content-Disposition: inline, f ilename=cert . rtf ") ;
$date = date( "F d, Y" ) ;
//
$filename = "PHPCertification.rtf";
$fp = fopen ( $filename, "r" ) ;
//
$output = fread( $fp, filesize( $filename ) ) ;
fclose ( $fp ) ;
//
$output = str_replace ( "NAME", strtoupper ( $name ) , Soutput ) ;
$output = str_replace( "Name", $name, $output ) ;
$output = str_replace( "score", $score, $output ) ;
$output = str_replace( "mm/dd/yyyy" , $date , $output ) ;
//
cho $ ou tpu t ;

,
, .
RTF-, HTML-, . ,
Save As... ( ),
RTF-.
MIME- HTTP- PHP- header() :
header ( "Content- type: application/msword" );
header! "Content-Disposition: inline, f ilename=cert . rtf ") ;

, Microsoft Word
( RTF- , ).
,
cerf.rtf. , .

30. PDF

01

, RTF- Soutput str_replace() , .


Soutput = str_replace( "Name", $name, $output );

Name
Sname.
. . 30.5.

30.5
rtf.php

RTF.

PHP Certification
This is to certify that
LUKE WELLING
has demonstrated that they are certifiable by passing e, rig
consisting of three multifile choice question*.
Luke Veiling obtained a score rf 1..
The test was set and overseen by the
Ptetionallnstitute afPHP Certification
n November 25, JO.
Authoniedby:

. str_replace()
, , , , Soutput . , . ,
. RTF- " ".

PDF-
PDF-
. , PDF- . ,
, , :
N) -13 () -10 (>) -6 (>

Na) -9 (m) 0 () -18 (


<) -11 (<) 1 <sc) -17 () -6 () -6 (>) -11 (>
<) -11) 1 () -12 () 0 (/d) -6 (d) -19 (/) 1 () -13 () -13 (

, , RTF, .
.

612

5. MySQL

. ,
, , . PDF-
. ,
, ,
, , .
, . Adobe Acrobat PDF-, HTML- . PHP-
PDF (Forms Data Format ), , . FDF- , PHP- FDF: , fdf_create() ; fdf_set_value() ;
fdf_setfile() .
MIME-, vnd.fdf, Acrobat Reader .
, . -, , Acrobat. -,
, , .
, , , . PDF- , . FDF-
. , , ,
, .
PDF- Adobe:
http://www.adobe.com/support/techdocks/16196.htm

,
FDF :
http://www.php.net/manual/ref. d.php

PDF- .
PDF- , ,
,
, , . pdf_replace()
.
, PDF RTF-. 30.4.

30. PDF

013

30.4 pdf.php
PDF-

<?

set_time_limit ( 180 ); //
function pdf_replace ( $pattern, $replacement, $string )
{
$len = strlenf $pattern );
$regexp = ' ' ;
for ( $i = 0; $i<$len; $i++ )
{
$regexp . = $pattern [$i] ;
if ($i<$len-l)
$regexp .= " (\) \-{0,l) [0-9]*\ () {0,1} ";
}
return ereg_replace ( $regexp, $replacement, $string ) ;
>
if (!$name| | !$score)
{
echo "<hl>Error :</hl>This page was called incorrectly";
}
else
{
// ,
//
header ( "Content-Disposition: filename=cert.pdf") ;
header ( "Con tent- type: application/pdf " );
$date = date I "F d, Y" ) ;
//
$filename = "PHPCertification.pdf";
$fp = fopen ( ^filename, "r" ) ;
//
$output = fread( $fp, f ilesize ( $filename } );
f close ( $fp ) ;
//
$output = pdf_replace ( "NAME" , strtoupper ( $name ) , $output ) ;
$output = pdf_replace ( "Name" , $name , $output ) ;
$output = pdf "replace ( "score", $score, $output ) ;
$output = pdf~replace( "mm/dd/yyyy" , $date, $output );
//
echo $output;

PDF-. ,
. 30.6, , . , PDF-, . 30.6, , RTF-, .

30.5
,
- , .
,
str_replace(), RTF- .

14

5. MySQL

/webtstvfet/cheptef30/pdi phptscore-l QO.fjaname4irtieWBl1ingS,x-26y-10

30.6
pdf.php

PDF.

PHP Certification
This to certify that:
LUKE WELLING
luts tlentymtiatcii U they are >rttfiabic by passing a itgocuus exam
consisting cif !.hm> -.iiapli- rftnlrt* <{u

I (: ti-st WHS sd and ov . by


I f W J i u i c rtf

, ,
.
. .

PDF- PDFI/b
PDFlib PDF- Web. , , , ,
. , C++, Java, Perl,
Python, Tel ActiveX/.
, PDFlib . PDFlib. Web- PDFlib ,
" , , ",
.
, , ,
( ) , , . ,
API ,
http://www.php.net/manual/ref.pdf.php

, PDFlib,
PDFlib-manual.pdf PDFlib.

Hello World PDFlib


PDFlib, Hello World, 30.5.

30. PDF

01J

30.5 testpdf.php Hello World, PDFlib



//
$fp = fopen("hello.pdf", "w") ;
if(!$fp)
echo "Error: could not create the PDF file";
exit;
// pdf-
$pdf pdf_open($fp) ;
pdf_set_inf($pdf, "Creator", "pdftest.php");
pdf_set_info($pdf, "Author", "Luke Helling and Laura Thomson");
pdf_set3info($pdf, "Title", "Hello World (PHP)");
// US letter 11" x 8.5"
// 72
pdf_begin_page($pdf, 8.5*72, 11*72);
pdf_add_outline($pdf, "Page 1");
pdf_aet_font($pdf, "Helvetica-Bold", 24, "host");
pdf_set_textjpos($pdf, 50, 700);
//
pdf_show($pdf,"Hello,world!");
pdf~continue_text($pdf,"(says PHP)");
//
pdf end_page($pdf);
pdf~close($pdf);
fclose($fp);
//
echo "download the pdf <a href = 'hello.pdf'>here</a>";

,
, :
Fatal error: Call to undefined function: pdf_open() in
/home/book/public_html/chapter30/pdftest.php on line 6

, PDFlib .
, PDFlib. PDFlib .

.
,
$fp = fopen("hell.pdf", " w " ) ;

. , , ,
Web-.

616

5. MySQL

$pdf = pdf_open($p) ;

PDF-, .
pdf_open() , .
pdf_open(),
PDF.
pdf_set_info() ,
, , , , , .
, . , .
pdi_set_info($pdf, "Creator", "pdftest.php");
pdf_set_info($pdf, "Author", "Luke Welling and Laura Thomson");
pdf_set_inf($pdf, "Title", "Hello World (PHP)");

PDF- . ,
pdf_begin_page(). ,
pdf_open(), pdf_beginjage() .
,
, .
,
PDFlib . , 4 ,
595 842 , U.S. letter 612 792 . ,
pdf_begin_page($pdf, 8.5*72, 11*72);

, U.S. letter.
PDF- . PDF, .
pdf_add_outline() . Acrobat Reader, .

pdf_add_outline($pdf,

"Page 1") ;

, Page 1,
.
, . ,
PDF-, .
14 :
Courier
Courier-Bold
Courier-Oblique
Courier-BoldOblique

30, PDF

01

Helvetica
Helvetica-Bold
Helvetica-Oblique
Helvetica-BoldOblique
Times-Roman
Times-Bold
Times-Italic
Times-Boldltalic
Symbol
ZapfDingbats
, ,
. , :
pdf_set_font($pdf, "Helvetica-Bold", 24, "host");

.
host. winansi, builtin, macroman,
ebcdic host. :
winansi ISO 8859-1 , Microsoft, .
macroman Mac Roman. , Macintosh.
ebcdic EBCDIC, AS/400 IBM.
builtin , .
, .
host macroman Mac, ebcdic , EBCDIC, winansi .
, .

PDF- HTML- . . .
, PDF . (, [0, 0]) .
612 792 , (50, 700)
.
,
pdf_set_text_pos($pdf, 50, 700);

5. MySQL

, , ,
. pdf_show().

pdf_show($pdf,

"Hello,

World!");

"Hello, World!"

pdf_continue_text(). , "(says PHP)":
pdf_continue_text($pdf, "(says PHP)");

.
pdf_end_page():
pdf_end_page($pdf);
PDF- pdf_close(). .

pdf_close($pd);
f close ($fp) ;

Hello World.
.
echo "download the pdf <a href = 'hello.pdf' >here</a>" ;

,
PDFlib, .
, ,
, . .
PDFlib .

PDFlib
PDFlib, .
, ,
, , Microsoft Word.
, ,
, .
30.6.

30.6 pdflib.php PDFlib


<?

if(!$name||!$score)
{
echo "<hl>Error:</hl>This page was called incorrectly";

}
else

30. PDF

19

// ,
//
header( "Content-type: application/pdf" );
header( "Content-Disposition: filename=cert.pdf");
$date = date( "F d, Y" );
// pdf-
$pdf = pdf_open () ;
//
// US letter 11" 8.5"
// 72
$width = 11*72;
$height = 8.5*72;
pdf_begin_page($pdf, $width, $height) ;
//
$inset = 20;
//
$border = 10; //
$inner = 2;
//
//
pdf_rect($pdf, $inset-$inner,
$inset-$inner,
$width-2*($inset-$inner),
$height-2*($inset-$inner));
pdf_stroke($pdf) ;
// $border
pdf_setlinewidth($pdf, $border);
pdf_rect($pdf, $inset+$border/2,
$inset+$border/2,
$width-2*($inset+$border/2),
$height-2*($inset+$border/2));
pdf_stroke($pdf) ;
pdf_setlinewidth($pdf, 1.0);
//
pdf_rect($pdf, $inset+$border+$inner,
$inset+$border+$inner,
$width-2*($inset+$border+$inner),
$height-2*($inset+$border+$inner));
pdf_stroke($pdf) ;
//
pdf_set_font($pdf, "Times-Roman", 48, "host");
$startx = ($width - pdf_stringwidth($pdf, "PHP Certification"))/2;
pdf_show_xy($pdf, "PHP Certification", $startx, 490);
pdf_set_font($pdf, "Times-Roman", 26, "host");
$startx = 70;
pdf_show_xy($pdf, "This is to certify that:", $startx, 430);
pdf_show_xy($pdf, strtoupper($name), $startx+90, 391);
pdf_set_font($pdf, "Times-Roman", 20, "host");
pdf_show_xy($pdf, "has demonstrated that they are certifiable ".
"by passing a rigorous exam", $startx, 340);
pdf_show_xy($pdf, "consisting of three multiple choice questions.",
$startx, 310);
pdf_show_xy($pdf, "$name obtained a score of $score"."%.",
$startx, 260);

620

5. MySQL
pdf_show xy($pd, "The test was set and overseen by the ",
$startx, 210);
pdf_show_xy($pdf, "Fictional Institute of PHP Certification",
$startx, 180);
pdf_show_xy($pdf, "on $date.", $startx, 150);
pdf_show_xy($pdf, "Authorised by:", $startx, 100);
//
$signature = pdf_open_image_file($pdf, "tiff",
"/htdocs/book/chapter30/signature.tif"
pdf_place_image($pdf, $signature, 200, 75, 1);
pdf_close_image($pdf, $signature);
pdf_setrgbcolor_f ill ($pdf, 0, 0, .4); //dark blue
pdf_setrgbcolor_stroke($pdf, 0, 0, 0);
//
pdf_moveto($pdf, 630,
pdf lineto($pdf, 610,
pdf~lineto($pdf, 632,
pdf~lineto($pdf, 646,
pdf_lineto($pdf, 666,
pdf_closepath($pdf);
pdf_fill($pdf);

// black

1
150);
55);
69);
49);
150);

// 1
pdf moveto($pdf, 630, 150);
pdf~lineto($pdf, 610, 55);
pdf~lineto($pdf, 632, 69);
pdf_lineto($pdf, 646, 49);
pdf_lineto($pdf, 666, 150);
pdf_closepath($pdf) ;
pdf_stroke($pdf) ;
//
pdf_moveto($pdf, 660,
pdf_lineto($pdf, 680,
pdf_lineto($pdf, 695,
pdf_lineto($pdf, 716,
pdf_lineto($pdf, 696,
pdf_closepath($pdf);
pdf_fill($pdf);

2
150);
49);
69);
55);
150);

// 2
pdf_moveto($pdf, 660, 150);
pdf_lineto($pdf, 680, 49);
pdf_lineto($pdf, 695, 69);
pdf_lineto($pdf, 716, 55);
pdf_lineto($pdf, 696, 150);
pdf_closepath($pdf);
pdf~stroke($pdf) ;
pdf_setrgbcolor_fill($pdf, .8, 0, 0);

//red

//
draw_star(665, 175, 32, 57, 10, $pdf, true) ;
//
draw_star(665, 175, 32, 57, 10, $pdf, false);
pdf_end_page($pdf) ;
pdf_close($pdf);

30. PDF

21

function draw_star($centerx, $centery, $points, $radius,


$point_size, $pdf, $filled)
$inner_radius = $radius-$point_size;
for ($i = 0; $i<=$points*2; $i++ )
$angle= ($i*2*pi ( ) ) / ($points*2) ;
if ($i%2)
$x = $radius*cos($angle) + $centerx;
$y = $radius*sin($angle) + $centery;
else
$x = $inner_radius*cos($angle)
$y = $inner_radius*sin($angle)

$centerx;
$centery;

if ($i=0)
pdf_moveto($pdf, $x, $y) ;
else if($i==$points*2)
pdf_closepath($pdf);
else
pdf_lineto($pdf, $x, $y) ;
if ($filled)
pdf f i l l ( $ p d f ) ;
pdf_stroke($pdf);

. 30.7. ,
, , ,
. ,
, -

30.7
pdflib.php



PDF-.

622

5. MySQL

, .
, ,
, .
, ,
.
pdf_open() :
spdf = pdf _open () ;

: ,
, . .
,
,
Swidth Sheight, : Sinset, Sborder Sinner.
Sinset
, Sborder , a Sinner
.

API, PDFlib .
19, , ,
gd PDFlib.
.
pdf_rect(), PDF-,
. ,
.
pdf_rect($pdf,

$inset-$inner,
$inset-$inner,
$width-2*($inset-$inner),
$height-2*($inset-$inner));

pdf_rect() . , pdf_stroke();
pdf_stroke($pdf);

.
1 . pdf_setlinewidth()
Sborder ( 10):
pdf _setlinewidth($pdf, $border);


pdf_rect() pdf_stroke(), .
pdf_rect($pdf,

$inset+$border/2,
$inset+$border/2,
$width-2*($inset+$border/2),
$height-2*($inset+$border/2));
pdf_stroke($pdf);

30. PDF

23

, 1 :
pdf_setlinewidth($pdf,

1.0);

pdf_show_xy() .
(Sstartx) . ,
,
. , pdf_stringwidth().

pdf_stringwidth($pdf, "PHP Certification");

"PHP Certification" .
,
.
$signature = pdf_open_image_file($pdf, "tiff",
"/htdocs/book/chapter30/signature.tif");
pdf_place_image($pdf, $signature, 200, 75, I);
pdf_close_image($pdf, $signature);

TIFF-, , TIFF-. . , , ,
pdf_place_image(). . . 1:1 , 1,
.

PDFlib . Windows- , .
,
.
( ) ,
( ) -:
pdf_setrgbcolor_fill($pdf, 0, 0, .4);
pdf_setrgbcolor_stroke($pdf, , , 0);

// -
//

, ,
:
pdf_moveto($pdf, 630,
pdf_lineto($pdf, 610,
pdf lineto($pdf, 632,
pdf~lineto($pdf, 646,
pdf3-ineto($pdf, 666,
pdf closepath($pdf);

150);
55);
69);
49);
150);

624

5. MySQL

, ,
, pdf_stroke(), pdf_fiU().
, . draw_star()
, , , PDF-, ,
.
draw_star() , .
, $point_size ,
. , cos()
sin() , .
, .
, .
, .

,
, ,
, , . HTTP- content-type:
header( "Content-type: application/msword" );

header( "Content-type: application/pdf" ) ;

, . , Internet Explorer - .
, ,
. . ,
GET POST
.
PDF-,
, "Hello, World!"
PDFlib.
, : Netscape, Internet Explorer.
PDF-, Internet Explorer, Acrobat Reader.
Adobe
http://www.adobe.com/support/techdocs/3d76.htm

PDF-
Active Server Pages, .

30. PDF

\) J


, ,
, .
,
, , , , .


, PDF ( FDF),
Adobe :
http://www.adobe.com

4 MySQL
Internet

4
MySQL

Apache, PHP MySQL


Web-. Apache, PHP
MySQL . ,

UNIX Windows NT.
:
CGI

Apache, SSL, PHP MySQL UNIX


Apache, PHP MySQL Windows

: phpinfo()

MySQL Internet
Information Server
MySQL Personal Web
Server

Web-, ,
Web-. ,
,
(Secure Socket Layer, SSL)
.
, (DB), . Apache,
MySQL , , , , .

628 6.
CG1
, HTML
, , . CGI.
. CGI-
Apache PHP- . , , CGI-, , Perl .
, . , CGI, CERT CA-96.11 (CERT Advisory CA-96.11) :
http://www.cert.org/advisories/CA-96. 11.interpreters_in_cgi_bin_dir.htrol

CGI , PHP- Web- cgi-bin, CERT . , ( ), cgi-bin, ,


. ,
.
:
, CGI.

- Web- , CGI. enable-force-cgi-redirect


doc_root user_dir.

, .
CGI,
PHP- Web-.
/usr/local/bin UNIX :\ PHP-DIR\ Windows.
,
CGI-. , UNIX- /usr/local/bin/php

#!

/usr/local/bin/php

, , . , CGI PHP- , , Perl.



UNIX CGI Windows.

. 4 MySQL

Apache, PHP MySQL UNIX


Apache, PHP MySQL UNIX.
, . Web-, (Secure
Socket Layer, SSL). ,
.
http://curl.haxx.se/: Client URL

http://pspell.sourceforge.net/:
(Portable Spell Checker Libraries)

http://www.pdfljb.com/pdflib/jndex.html: PDF

PHP-.
,
. .

, . , .
Red Hat Linux 6.2,
, UNIX-.
, , .
Apache (http://www.apache.org/): Web-
Mod_SSL (http://www.modssl.org/):

OpenSSL (http://www.openssl.org/): Open Source Toolkit (


Mod_SSL)

RSARef (http://ftpsearch.lycos.com/): ,
MySQL (http://www.mysql.com/):
(http://www.php.net/):
, , ,
(root) , :

Perl ( )

gzip gunzip
gcc GNU make
,
.
root :

cgi-bin
Web-

630

6.

, , root.
, tar- . , . /tmp/download. ,
root.
:
# /usr/local/apache
#

/usr/local/mysql

/usr/local/ssl

, prefix.
, ! , root
$

SU

. , ',
# cd /tmp/download/

:
#

gunzip - mysql-3.22.xx.tar.gz

tar xvf -

, :
#

cd mysql-3.22 .

MySQL. configure
, configure help.
configure . , config.cache.
t

./configure --prefix=/usr/local/mysql

configure , ( ):
#

make

,
( configure --prefix) :
#

make install

mysql,
. new-password -, new-password
root.
# scripts/mysql_install_db
# cd /usr/local/mysql/bin
# ./safe_mysqld &
# ./mysqladmin -u root password 'new-password'

MySQL .
:

. 4 MySQL
#

631

/usr/local/mysql/bin/mysqlshow -p

.
I Databases
I
+ ------------------- +
I mysql
|
+ ------------------- +
MySQL .
, ,
. . ,
:
i mysql -u root -p
.
reysql> show databases ;
+ ------------------- +
|

Database

|
I

myeql
test

2 rows in set (0.00 sec)


. root (, , su).
Apache,
. , , Apache.
, .
cd /tmp/download
gun zip - apache_l . 3 . x . tar . gz | tar xf cd apache_l .3.x
. /configure --pref ix=/usr/local/apache
cd ..

, .
:
# gun zip - php-4.0.x. tar.gz
f
cd php-4.0.x

| tar xvf -

configure , configure help. ,


MySQL, Apache, PDFLib, cURL PSPELL.
, . , , (
(\)), , .
f ./configure with-mysql=/usr/local/myeql \
with-xml with-apaehe=. ./apache_1.3.x \
with-curl=/usr/local/curl \
with-pspell=/usr/local/pspell \
enable-shared-pdflib enable- track-vars

632

6.

( )
:
# make
# make install
ini- lib:
# php.ini-dist /usr/local/lib/php.ini
, . , , max_execution_time
php.ini :
max_execution_time = 60 ;

Apache mod_SSL
mod_SSL Apache.
, rsaref-2.0. , RSA, Web. , ,
Lycos
http://ftpsearch.lycos.com
Google
http://www.google.com
rsareflO.tar.Z. ,
UNIX.
rsaref. ,
, .
# mkdir rsaref-2.0
# cd rsaref-2.0
# gunzip - ../rsaref20.tar.Z | tar xvf OpenSSL,
RSAref.
#
#
f
#
#

cd rsaref-2.0
-rp install/unix local
cd local
make
mv rsaref.a librsaref.a

# cd ../..

OpenSSL.
CSR . prefix .


-L'pwd'/../rsaref-2.0/local/rsaref -fPlC.
f gunzip c openssl-0.9.x.tar.gz | tar xvf # cd openssl-0.9.x
# ./config prefix=/usr/local/ssl \
-L'pwdV../rsaref-2.0/local/rsaref -fPIC

. 4 MySQL

33

, :
#
#
#
#

make
make test
make install
cd ..

mod_SSL Apache.
#
#
#
#

gunzip -c mod_ssl-2.6.x.tar.gz | tar xvf od mod_ssl-2.5.x-1.3.x


./configure with-apache=../apache_l.3 . x
od . .

, Apache . --enable-shared=ssl mod_SSL DSO


( ), 'libssl.so'. DSO Apache INSTALL htdocs/manual/
dso.html Apache. Internet- , , DSO
mod_SSL. , Apache DSO .
# cd apache 1.3.x
# SSL_BASE=~ /openssl-.. \
RSA_BASE=../rsaref-2.0/local \
./configure \
--enable-module=ssl \
--activate-module=src/modules/php4/libphp4.a \
--enable-module=php4 \
--prefix=/usr/local/apache \
--enable-shared=ssi
[... ...]

( SSL_BASE RSA_BASE .)
Apache
.
# make

, :
+
Before you install the package you now should prepare the SSL
certificate system by running the 'make certificate' command.
For different situations the following variants are provided:
% make certificate TYPE=dummy (dummy self-signed Snake Oil cert)
% make certificate TYPE=test (test cert signed by Snake Oil CA)
% make certificate TYPE=custom (custom cert signed by own CA)
% make certificate TYPE=existing (existing cert)
CRT=/path/to/your.crt [KEY=/path/to/your.key]
Use TYPE=dummy when you're a vendor package maintainer,
the TYPE=test when you're an admin but want to do tests only,
the TYPE=custom when you're an admin willing to run a real server
and TYPE=existing when you're an admin who upgrades a server.
(The default is TYPE=test)
Additionally add ALGO=RSA (default) or ALGO=DSA to select
the signature algorithm used for the generated certificate.

,.
I
j
1
j

634

6.

I Use 'make certificate VIEW=1' to display the generated data.


| Thanks for using Apache & mod_ssl. Half S. Engelschall
| rseeengelschall.com www.engelschall.com

I
I

.
, .
# make certificate TYPE=custom
Apache :
# make install

, :
You now have successfully built and installed the
Apache 1.3 HTTP server. To verify that Apache actually
works correctly you now should first check the
(initially created or preserved) configuration files
/usr/local/apache/conf/httpd.conf
and then you should be able to immediately fire up
Apache the first time by running:
/usr/local/apache/bin/apachectl start
Or when you want to run it with SSL enabled use:
/usr/local/apache/bin/apachectl staztssl
Thanks for using Apache. The Apache Group
http://www.apache.org/

Apache .
httpd.conf srm.conf, .
httpd.conf /usr/local/apache/
conf. addtype 4 .
.

httpd.conf
> # 4. :
> AddType application/x-httpd-php .php
> AddType application/x-httpd-php-source .phps

Apache.
SSL, . , SSL.

configtest:
# cd /usr/local/apache/bin
# ./apachectl configtest
Syntax OK
# ./apachectl start
./apachectl start: httpd started

. 4 MySQL

635

Hey, it worked /
The SSL/TLS-aware Apache webserver was
successfully installed on this website.
If you cart see this page, then me people who own 1
ifrwer software and the A; ; -:ht ^ :o Ofrtai
add content to this dtfectory and replace this placet
content.
' .
:';

.1

,

Apache.

lave just installed the ;Aj?t!c|x*..'


successfully. They now have to
or else point the server at their real

ATTENTION!
If'you are seeing this page instead of the site you expected, please contact the
administrator of the site involved. (Try sen-ing mail to <)>
Although this site is running the Apache software it almost certainly has no other
connection to the-Apache Group, so please do not send mail about this site or its
contents to the Apache authors. If you do. your message will be ignored
The Apache online -.-i-x-si
Especially also read the r.

:M has been included with this distribution


r
I t ser Manual carefijlly

are allowed to use the images below on your SSL-awAre Apache Web server
Thanks for using Apache, mod_ssl and OpenSSLI

, Web- , . .
^
IP-. .

?
.
test.php, . /usr/local/apache/htdocs. ,
prefix,
. httpd.conf.
<? phpinfo() ?>

. .2.

SSL?
SSL.
SSL:
f /usr/local/apache/bin/apachectl stop
# /usr/local/apache/bin/apachectl startssl

Web- https:
https : //yourserver . yourdomain . com

http://yoursever.yourdomain.com:443

636

6.

IS

ystem

.2
phpinfoQ


.

unknown

""

' ..... ''"-' >"-*

aw

Build Date

- \, j 2"-1
'

Configure Command
Apach

Server API
Virtual Directory
Support
r..ii<tii;uiatl<inHla
(php.lnl| I'alh

1,,-,,'h- .J

ZEND OFBUG
Ihrmd Safety
n mdkes USH of ihs / '.wlptiruj language eitgins
.I.CoDy.Bf.r. i l:M;.iv4;iBi

IP-, :
https://...

http://...:443

, . . VeriSign
Thawte, ,
(Certification Authority, CA). ,
,
. Web-
.
Internet Explorer ,
Netscape, - ,
. ,
SSL-.
. , Netscape,
. ..

Apache, PHP MySQL Windows


Windows ,
CGI (php.exe) ISAPI (php4isapi.dll).
Apache MySQL , UNIX. Windows ,
.
, , .
C:\TEMP\DOWNLOAD.

. 4 MySQL

MySQL Windows
MySQL. MySQL Setup.exe. , MySQL
C:\mysql.
.
MySQL , mysqld , MySQL.
C:\mysql\bin\mysqld --help. , MySQL 'D:\programs\mysql', mysqld
'D:\programs\mysql\bin\mysqld basedir D:\programs\mysql1.
MySQL 'C:\my.cnf, MySQL. 'C:\mysql\my-xxxxx.cnf 'C:\my.cnf .

Windows 95/98
MySQL Windows 95/98 MySQL:
mysqld:
mysqld-opt: Pentium
Intel x86 .
mysqld Windows :
:\mysql\bin\mysqld-opt

MySQL . , , , '\mysql\mysql.err', , . MySQL


C:\mysql\bin\mysqladmin -u root shutdown

Windows NT/Win2000
MySQL NT Windows 2000
. MySQL NT/Win2000 mysqldnt . :
C:\mysql\bin\mysqld-nt -install

MySQL

NET START mysql
NET STOP mysql
^
mysql, mysql-nt.

(Services
Control Manager, SCM) ( (Control Panel)) NET START MySQL. SCM . .4.

638

6.

(startup parameters) SCM


MySQL. mysqld-nt ,
mysqladmin, SCM NET STOP MySQL.
MySQL :
:\mysql\bin\mysqlshow
C:\mysql\bin\mysqlshow -u root mysql
C:\inysql\bin\mysqladmin version status proo
C:\mysql\bin\mysqladrain - root shutdown

Windows.
MySQL : mysql test. mysql
. test , MySQL.
Web- MySQL
http://www.mysql.com.
Apache Windows.

Apache Windows
Apache 1.3 , Windows NT 4.0
Windows 2000. 86
(, Intel). Apache Windows 95/98, . ,
TCP/IP. Win95 Win98
Winsock 2.
( , ) Apache Windows .-. Apache.
apache_l_3_x_win32.exe
.
Windows ( . .5) .

Cotrcutet Bromei
DHCP
Sieclwy Repfca(o<
EvewLog
pjvMcii WS.FTP Queue

NAVAM
NAVAutofratea
NLDOan

'

You CV,chttte rw It. h.uf if* h Web SW I tfcWre

Staled
Started
Started

Manual
Automatic
Automatic

_*J.

.4 (Services Control
Manager) ,
.

.5
Apache.

. 4 MySQL

3 >7

Apache. ( C:\Program Files\Apache


Group\Apache.)
Start. (Apache Web Server no .)

. Typical () , . Minimum () . ,
Custom ().
Apache conf. httpd.conf ,
.
Apache Windows
Apache:

Windows
Window NT Windows 2000.
Apache
. , , Windows 95 Windows 98. , 1.3.13
Win 95 Win 98 Apache . ,
.
Apache , .
Apache .
Apache
Apache , Start Apache as
console App ( Apache ) Start ().
, . , Apache .
Shutdown Apache as Console App ( Apache ) Start (), ( 1.3.3 ):
C:\Program Files\Apache Group\Apache> apache -k shutdown

MySQL, Apache ,
, Control-C Control-Break
, . ( 1.3.3 .)
Apache
Apache , . , Apache
.
Apache ( Apache),
Install Apache as Service (NT only) ( Apache ( NT))

640

6.

Start (). Services () ( Control Panel ( )), Apache Start (). Apache
. , Stop ().
Services () Apache
,
NET START apache
NET STOP apache

, MySQL NT
Windows 2000.
Apache NT Win2000
error.Iog,
. Apache Event
Log ( ).
,
Apache. Apache , , :
apache -n "service name" -k start
apache -n "service name" -k restart
apache -n "service " -k shutdown

-, -k Apache, . , .
Apache 80 ( Port (), Listen () BindAddress
( )). ,
URL:
http://localhost/

, . , Apache. , error.log logs. Internet, URL:


http://127.0.0.1/

IP- localhost.
( 80), URL :port_number.
, Apache HE TCP/IP.

Apache Windows UNIX


Apache Windows UNIX:
Apache Windows , ,
UNIX. Apache: , .
.
.

. 4 MySQL

641

, ,
Windows, UNIX. , Apache UNIX, ,
. ; , ,
Apache.

Apache Windows . Apache , \modules. -


LoadModule ( ). ,
(status) ( access.:
LoadModule status_module modules/mod_status.so


http://httpd.apache.org/docs/mod/mod_so.htmltfloadmodule

1.3 Apache Windows . CGI-,


, . CGI Apache, Windows. Apache 2.0 .
, NT/2000 CGI
.
Windows Apache SSL,
. , ,
Apache.org, OpenSSL.org ModSSl.oig, ,
UNIX. ,
.

Windows
Windows. Apache. : 3,
4 ,
DLL-. CGI . , DLL- (), Windows.
SYSTEM (Windows 9x) SYSTEM32 (Windows
NT), Windows.
MSVCRT.DLL ( ) PHP4TS.DLL.
, .
, ,
Windows-.

21 . 216

642

1. php.ini-dist '%WINDOWS%' 'php.ini'. '%WINDOWS%'


C:\WINDOWS Windows 9 C:\WINNT NT.
2. php.ini extension_dir , DLL- , doc_root Web- (.. ,
).
3. php.ini ,
. extension=php_*.dll. , . , MySQL
4 .
, httpd.conf conf Apache. CGI. :

ScriptAlias /php/ ":/---php/"

AddType application/x-httpd-php .php


AddType application/x-httpd-php .phtml
Action application/x-httpd-php "/php/php.exe"

, AddType Apache, . Apache


.php .phtml -.
, , .htm .html -.
:

AddType application/x-httpd-php .html


AddType application/x-httpd-php .htm

,
, Web- Apache http://www.apache.org.


Apache , .
test.php, :
<? phpinf()

?>

Apache,
http://localhost/test.php

http: //Bani-ip-aflpec/test.php

, Apache , ,
, . .2. MySQL
. PHP-, MySQL / .

O4 3

. 4 MySQL

MySQL Microsoft IIS PWS


, MySQL IIS
ISAPI (php4isapi.dll). , MySQL
, .
, DLL-, (MSVCRT.DLL PHP4TS.DLL) Windows. ,
test.php , .

Microsoft IIS
Microsoft Internet Information Server:
1. php.ini-dist, php.ini-optimized Windows
'php.ini' ( ) .
2. Microsoft Management Console ( Microsoft) (
Internet Services Manager Windows NT 4.0 Option Pack
Control Panel, Administrative Tools ( , ) Windows 2000).
3. Web- Properties
(). ISAPI Filters ( ISAPI) ISAPI.
. .6.
php4isapi.dll, 4.
4. Home Directory ( ) Configuration
() Application Mappings (
). php4isapi.dll , .php, Method exclusions ( )
Script engine ( ).
5. IIS, 'net stop iisadmin' .

^ Ooeumsntj J: OceelMji Security - ):;. HTTpiHeaden |: '-'


j ; Opetato | Pakmaxx
ISAPIFtaj .(; (fi'"

i FtaliMatedhaiaaieactivetothisWebcilia^FiiiaicWeemcutffdinthe

State

! F*Hame::

A.6

ISAPI.

Cancel

Hi*

644

6.

6. IIS 'net start w3svc'.


7. test.php Web-.
test.php, , :
<?php p h p i n f o ( ) ; ?>

, , . .2.

Microsoft PWS
1. php.ini DLL- , .
2. PWS-php4.reg,
php4isapi.dll.
, :
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\w3svc\parameters\
Script Map] ".php"="C:\\Program Files\ \PHP\\php4isapi.dll"

3. PWS Manager ( PWS) , , Properties ().


Execute () .
! PWS .


MySQL Web-, Omni, HTTPD Netscape Enterprise Server. , Web-
MySQL :
http://www.MySQL.com

http://www.php.net


Internet

Internet, , , PHP-. . , , MySQL,


, Web- .

,
, .
http://www.systransoft.com.

,
PHP.Net http://www.php.net .
,
.
ZEND.Com http://www.zend.com
ZEND, 4.0.
- , , . .
PHPWizard.net http://www.phpwizard.net

,
,
phpMyAdmin,
MySQL. ,
.
PHPBuilder.com http://www.phpbuilder.com . . , ,
.

646

6.

DevShed.com http://www.devshed.com -, PHP, MySQL, Perl .


.
- Code Exchange http://px.sklar.com . . .
The PHP4 Resource http://www.php-resource.de , . "" . .
WeberDev.com http://www.WeberDev.com "Berber's PHP sample
page", . MySQL
, NT. . ,
, , .
HotScripts.com http://www.hotscripts.com , .
, PHP, ASP Perl.
PHP-. , , .
PHP Base Library http://phplib.netuse.de , 3.
, 4, . , .
Center http://www.php-center.de - ,
, , .
PHPInfo.net http://www.phpinfo.net MySQL, , , , .
Homepage http://www.php-homepage.de , : , , . .
PHPIndex.com http://www.phpindex.com - , . ,
, , .
WebMonkey.com http://www.webmonkey.com Web-, , .. , , , .
The Club http://www.phpclub.net Club
: , , , ,
, .
The PHP Classes Repository http://phpclasses.upperdesign.com
, . ,
. .
The PHP Resource Index http://php.resourceindex.com - ,
. , .

. Internet

47

PHP Developer http://www.phpdeveloper.org PHP-: , , .


Evil Walrus http://www.evilwalrus.com .
Oodie.com http://www.oodie.com , .
e-gineer http://www.e-gineer.com , ,
.
Source Forge http://sourceforge.net . Source Forge ,
CVS, .

, MySQL SQL
The MySQL site http://www.mysql.com Web- MySQL.
, . ,
MySQL. MySQL.
SQL Tutorial http://w3.one.net/~jhoffinan/sqltut.htm
SQL .
The SQL Course http://sqlcourse.com SQL . SQL. http://www.sqlcourse2.com.
DatabaseCentral.com http://databasecentral.com . , ,
, , .. !
The SQL Pro http://www.inqiury.com/techtips/thesqlpro ? ! , SQL.

, Apache
Apache Software http://www.apache.org , ,
. .
Apache Week http://www.apacheweek.com , , Apache .
Apache Today http://www.apachetoday.com Apache.
.

Web
Web- (Philip and Alex's Guide to
Web Publishing) http://www.arsdigita.com/books/panda/
Internet.
Samoyed.

- 36
% 192
& 42
&& 44
. 35, 39
= 39
== 43
?: 45
@ 45, 326
" 46
I 111
II 44

198
256
163
163
163
163
163
325
33
39
388
Web- 166
47
76
140, 141
262
247, 254, 265, 266, 411
HTTP 274
272
272
418

211
221
211
211
415
214
352
246, 264
GD 341
51, 136
72
221, 262

111
135
MySQL 263
HTML 29
108
108

571. .

198

338
338
60
193
42
30, 140
30
256
571. ,
RFC 317
390
478

FTP 478

649

413
432
432
434

432
66
65, 400
254
271
39

36
MySQL 181
362
265
76. .
140
42
140
469
54

(CSS) 392
108, 140, 141
143
149
141
148
142
141
143
treenode 582
76, 160. .
161
160
387
386
385
392
384
387

CREATE TABLE 177


DESCRIBE 180
GRANT 172, 216
mysql 170

mysql jnstall_db 170


REVOKE 175

SHOW 180
32
385
Web- 234
Zend Technologies 393
68
35
38
142

35
44

75
76
78
80
83
76
76
529
480

148
mod_auth_mysql 279

108
141, 146, 148
148

39, 131
193
193. .

(equi-join) 193
194
140
-
139
39

break 58
continue 58

650

CREATE TABLE 178


DESCRIBE 225
describe user 217
do. .while 57
each 79
else 51
elseif 52
EXPLAIN 225

for 56
if 50, 51
include!) 123
INSERT 189
LOAD DATA INFILE 231
require!) 118
return 135
SELECT 199
SHOW 224
SHOW GRANTS 224
switch 52
while 55
31, 39
PHP 31
39
, 50
40
39
46
44
338
45
44
40
43
& () 42
40
45
68

392
229
229
214
FTP HTTP
63
68

(ODBC) 215

396
410
404
161
" " 161
" " 161
" " 161
317, 525
211
51
396
396, 398
408
396, 402
408
396
396

GPG 293
129
222, 268, 427
428
427
268
270
129

133
133
146
131

34
131
131
38
36
34
411
141
258
258
105
112
441
455
141
317

218
44
68
516
229
384
37
171, 216
174
174
222
FIL 222
PROCESS 222
RELOAD 222
SHUTDOWN 222
175

Certification 605
PHPBookmark 414
Shopping Cart 445
Warm Mail 503
47
31
Term SSH 325
396
288, 316, 361, 501
RP 316, 323
HTTP 288, 316, 361
IMAP 317, 501
NNTP 501
POP 317
POPS 501
Secure Socket Layer 260
SMTP 317, 501
TCP/IP 288
391
196

P
455
416
262
108
61
263
115, 137

651

361
362
361

Apache 260, 274


Microsoft IIS 260
376
259
234
401
Book-0-Rama 444
CVS 388

MySQL 171
NASDAQ 318
388
73
(SSL) 287

500
427

Web- 381
343
391
511
571
344
111
529
104
(IDE) 389
42
33, 35, 97
100
112
104
97
97, 98
40
184
141
74, 158
161

652

284, 378
checkout.php 463
delete_story.php 495
index.php 451
page.php 487
pdflib.php 621
PHP 284
publish.php 498
resizejmage.php 482
search.php 496
show_book.php 454
show_cart.php 456, 457, 462
story, php 492
story_submit.php 494
view_post.php 589
378

378

69
307
67
70
70

71
361

50

97
50
myisamchk

229

511

60, 302
72
60
302
66
65
68
71
70
61
69
67
71

352
353
352
571

.htaccess 275
book_scjns.php 451
content.html 275, 277
creditcardnumbers.txt 291
footer.inc 121
header.inc 121
home.php 120
index.html 605
login.php 469
page.inc 151

394

BLOB 185
ENUM 186
SET 186
185

598
ASCII 598
HTML 598
PostScript 600
RTF 599
(PDF) 596


183
183

480
97, 98

36
37


GIF 342
JPEG 341
PNG 341
WBMP 342

159, 165, 177


229
217
177
165

341

65
571
387
125, 198
PHP-MySQL 214
134
48
307
339
MySQL 198
129
320
259

add_bm() 433
add_quoting 592
addslashesQ 207, 290, 377
array_count_values() 92
array_reverse() 87
array_walk() 91
asortf) 85
basename($path) 309
basenamef) 311
calculate_items() 461
calculate_price() 461
change_password() 556
check_authjjser() 510
check_valid_user() 425, 426
checkdate() 336
chgrpf) 312
chmodf) 312
chownf) 312
copy() 312
countf) 92
currentf) 90
datef) 33, 333
DATE_FORMAT() 337
db.connect() 423
dbjesult_to_array() 452
defined 38

delete_account() 515
delete_bm() 436
dirname($path) 309
display!) 151
display_account_form() 513
display_account_select() 518
display_account_setup() 512
display_book_form() 473
display_books() 454
display_button() 509

display_cart() 458
display_categories() 451, 452
display_formj)utton() 509
display Jterns!) 548
display_list() 518
displayJist_form() 558
display_mailjorm() 560
display_passwordjorm() 555
display_tree() 581
dl() 378
do.html_header() 417
draw_star() 624
eachf) 79, 81, 90
emptyf) 49, 50
end() 90
ereg() 112, 113
eregif) 112, 113, 319
errorjeporting!) 407
escapeshellcmd() 290
eval() 375
exec() 313
expand_all() 580
explode!) 89, 102, 322
extract!) 93, 94
fclosef) 66
feof() 68, 70
fgetc() 70
fgetcsvf) 68, 69
fgets() 68, 69, 70
fgetssf) 68
(ile() 69
fileatimef) 311
filegroup!) 311
filemtime!) 311
fileowner() 311
fileperms!) 311
filesize!) 71, 311
filetypef) 311
filled_out() 421
flock 72
fopen() 61, 62, 63, 64, 65, 68, 69, 319
fpassthru() 69
fread() 70
fseekf) 72
ftell() 71
ftp_connect() 326
ftpjget!) 328
ftp_nlist() 330
ftp_size() 329

653

654

fwritef) 65
get_account_list() 516
get_accounts{) 513
get.archive() 553
get_attribute() 144
get_categories() 451, 452
get_category_name() 454
get_current_user() 378
get_email 546
get_extension_funcs() 377
get_loaded_extensions() 377, 378
get_magic_quotes_gpc() 375
get_post() 589
get_post_message() 592
getjandomj/vordQ 430
get_story_record() 493
get_unsubscribed_lists() 550
get_writerjecord() 491
gethostbyname() 321, 322
getlastmodf) 378
getmxrr{) 321
gettype() 48, 49
headerf) 346, 363
highlightjilef) 379
highlight_string() 379
htmlspecialcharsf) 290
internetf) 285
isset() 50
ksortf) 85
ImageColorAllocate)) 344
ImageCreatef) 344
ImageDestroyO 347
ImageRIIO 345
ImageFilledRectangleO 358
ImageGetnFBBoxO 351
ImageJPEGO 346
ImagePNGO 347
ImageStringf) 345
ini.get() 378, 379
ini_set() 378, 379
insert_order() 465
load_list_info() 552
loginf) 425, 545
Istatf) 311
mail() 96
mkdirf) 309
rnktimef) 335
myMultiplyf) 92
myPrintf) 92

mysql_affected_rows() 214
mysql_connect() 209, 400
mysql_create_db() 214
mysql_db_query() 210
mysql_drop_db() 214
mysqljetch_array() 210
mysqljetch_object() 211
mysqljree_result() 214
mysql_num_rows() 214
mysqljiumrowsO 210
mysql_pconnect() 208, 213
mysql_query() 209, 210, 213
mysql_result() 211
mysql_select_db() 210
next() 90, 91
n!2br() 98
notify_password() 431
number() 47
number_of_accounts() 516
open_mailbox() 519
opendirf) 308
parse_url() 322
passthruQ 313
pos() 90
prevf) 90
query_select() 494
readdir($dir) 308
readfile() 69
recommend_urls() 438
register!) 422
rename)) 312, 313
resetf) 79, 90
reset_password() 429
retrieve_message() 522
rewindf) 71, 72
rewinddir(Sdir) 308
rmdirf) 309
sendf) 566
send_message() 526
serialized 376
session_get_cookie_params() 363
session_register() 365
session_start() 364, 370
set_attribute() 144
settypef) 49
show_source() 379
shufflef) 86
sort() 83, 85
srtok() 103

statf) 311
store_account() 543
store_account_settings() 514
store jiew_post() 593
stripjagsf) 290
strcasecmpl) 104
strchrf) 105
strcmpl) 104
stripslashesf) 101, 210
stristrf) 106
strnatcm() 104
strnatcmpf) 104
strorejist() 559
strposf) 106
strrchrf) 106
strrposf) 106
strstr{) 105, 399
strtok() 102, 103
subscribed 554
substrl) 103, 107
system!) 313
tempnamf) 298
touch)) 312
trimf) 97, 207
umaskf) 309
UNIXJIMESTAMPO 337
unlink!) 71, 298, 312
unserialize() 376, 377
unsubscribe!) 554
usort() 85, 86, 91
valid_email() 421
X

344, 350
388. .
- 259

655

571. .

do..while 57
for 56
while 55
258
259

516

256, 292
257
258

143

30
SGML 30
XML 30
(Data Manipulation
Language) 188
(Data Definition Language)
188
(SQL) 187


Active Server Pages (ASP) 31
Cookie- 362
FTP- 478
PHP 33
- 30
PHP- 31
- 34
SGML (Standard Generalized Markup Language) 30
Web- 571
XML (Extensible Markup Language) 30

PHP.

ISBN 966-7393-81-,
384.

. , HTML-. ,
,
Web-, , Web .
.
.
, ,
.

Internet- .

ISBN 966-7393-80-1,
448.

.
. , , ,
Web-.
:
, Web-,
Internet-, , , . .

.

HTML.

Web-

HTML Web- . Web- Web-,

ISBN 966-7393-95-,
, 464 .
. Web- Ducks In A Row (http://www.ducks.htmlbook.com). . HTML 4, . CD-ROM .

1.

11

2.

12.

3.

13.

4. Web-

14.

5.

15.

6.

16.

7.

17.

8.

18.

9.

19. HTML-

10.

Python.

ISBN 966-7393-54-2
175x250 , 336 ., .



Python ,
, ,
.
, :

,


(, Linux
UNIX). , Python, Python , .
: ,
.
(,
CGI (
C++), , mod_python Apache).
, , (Perl).
, ,
Delphi, COM+, MFC, Java, - :
- (
.

). , , , ,
(,
.
map, filter, reduce, zip), (lambda).
,
.
,
- ,
, . ,
.
AVL . -
, ,
' ,
. PLEX . , ,
. , .
.

Python.

ISBN 966-7393-97-6
175x250 , .

Python
, Web.

.
Python , Microsoft Windows, UNIX/
Linux Macintosh.
Python C++
.
, JPython ,
Java.
Python
, . :
OLE, COM, DCOM
ActiveX Windows ( win32com,
Python for Delphi .);
CORBA, ILL), ADO, DCOM
( CORBA IDL Parser, Fnorb, OMF, Hector

-);

,
Java, ( JPython .);

,
,
Python

,
, MFC, Tk, KDE, Motif
( Pythonwin, wxPython,
PyKDE, PyOpenGL .);
- ( Zope, MetaKit, shelve);
,
,
;
, , XML, SGML, HTML,
XDR.
, "Python. ". , Web.
, ,
Python:
, ,
, .

JavaScript

ISBN 966-7393-62-3
210x270 , 464 ., .

SAMS

JavaScript Web.
Web-, Web-, Web-.
"JavaScript. "

Web-. JavaScript
"" Web- ,
,
.
. ,
JavaScript , ,
. , ?
,
, , Perl
Python. ,
,
JavaScript.

, .

,
.. .


JavaScript ,

,

,
-
.


JavaScript .
HTML,
, , , Web-.
JavaScript
, , Web-
.

JavaScript HTML.
, , ,
.
/
JavaScript.
.

Web-.

-.


Internet
ISBN 966-7393-70-4
150x210 , 448 ., .

PUE
Internet , .
,
, Internet
.
Internet .


Internet? ,
, . ( , )
" " , Internet? , ,
, , , Internet.

, : , Internet .

, , Internet.

.

,
Internet,
.

, ,
Internet .
, Internet.



,
Internet

, , .
,
, .

. ,
. , . ( ) .

. ,
.

Internet. ,
,
, .
Internet . , , ,
.

Flash 5

ISBN 966-7393-61-5
175x250 , 496 ., .

Flash , ,
. ,
, , ActionScript,
Flash 5
, , , ,
, Web,
.
' Flash 5 * Flash 5, , , , ,
.
5- ,
Flash ,
Macromedia, , ActionScript, Flash .
Flash 5, , . , , , , . , Web- Flash,
, no Flash.


,
Flash, , , Web, , ,
Web- -.

Flash, Macromedia,
FreeHand, Fireworks, Dreamveawer, Generator Director.

,
Web- Flash .
, ActionScript, Flash-, .
, , Flash
.

no Flash, , , ,
, Flash .

Internet-
Delphi 2
ISBN 966-7033-20-1
150x210 , 640 ., .

PUB
, Internet Delphi.
Internet,
,
.


Internet, CGI

Web-,

Internet


Internet , .
, . - - ,
Delphi.
Web-.
,
Internet, CGI
Web-,
Internet

CD-ROM ,
,
.

4
C++" '

C++
/ /
/
ISBN 966-7393-89-5

,
: , ? ?
?
?
: , .
, , " ", , .
, .
,

( ) . , - .
(, ), "", "", "" .
"" "" (,
!)... , ? ,
? , , -



,

"". ,
,

( ,
, - )?
?
: () , ,
.
, . , .

,
"". , ,
. ( , ).

Windows 2000 API.



ISBN 966-7393-74-7
175x250 , 1088, .

SAfAS
Windows
( , "windows"
""). Windows

: , , , ,
, , , ( -'
, , , ,
).
,
, , , , .
,
.

. , (
,
, ), .
, , .
:
(APIapplication programming interface)
Windows -

-
-8


,

. "Windows 2000 API. ".


,
Windows 95. API , Windows 2000, ,
.
Windows, API, .

API Win32,
Windows 2000 Windows 98 Microsoft. API,
, . API Win32, , API Win32,
API,
Windows 2000.


, , ,
.

ISBN 966-7393-45-3
150x210 , .

SriBEX

- , , , , .
, ,
, .
( 1998 ""), - , .
Intel, AMD, Cyrix . ,
,
,


, , .
, .
,
- ,

.


-
,

!



-

Intel, AMD, Cyrix .
Intel 8088 AMD486DX
Pentium 4, Tualantin Athlon, , , , .
.
. ,
BIOS ,
Windows 95 Millenium
2000.
.
. , .
, ,
, .

+.

ISBN
175x270 , .

$AMS
+ DMA
- , . + , ,
.


,
no COM+.
- +,
.
Windows
DNA .
+
. , , ,
. . , . ,
+,
. , , , ,
? - , , " " +. ,
? , ! +,
, , -
,
.


. ,
"Windows DMA +",
() Microsoft DNA.

DNA.
, .
, "
+",

, ,
, .
+.
, "
", Microsoft Transcation Server
+. , ,
.
, " ", MSMQ
+,
,
.

@
( - )
@. , ,
.
.
, -,
www.diasoft.kiev.ua.
:
;
, ;
;
;
.
, , ,
, , - , (
), , , ..
www.diasoft.kiev.ua

,
, , ,
.
, .
(
). ( , ,
) ,
, . , , .

, 5%
( + 1000 ).
; .
10% .
,
www.diasoft.kiev.ua.

1.
2. , , ( ) ?_

3. ...
4. .
5.
6. , , e-mail, web-
"

"

: , 03055, -55, / 100, .

""

/7\

-
- , . 105
. , . "'

""

' "
""

12-54,216-35-64
; 03055, \ 100
Dks@diasoft.kiev.ua
>@diasoft,kiev.ua

-; 49008, \ 466

e-mail: diasoff@mail.dnepr.net
.
' ,

i
\':\ t. (0572)47-20-67
e-mail: books@rail.kharkov.com
j i - .'
' ',. .: . '
i; ./. (0322)39-87-08:/ :::

j : .(0482) 68-73-99
> , e-mail: kvant@eurocom.od.ua
{'; e-mail: kvant@tekom.odessa.ua

.(095) 726-80-67

[ e-mail: diasoft_msk@rosmail.ru

I T.(812) 317-97-56 vrM :


I e-mail:

"",.,46
.224-22-91
".
.,51
.227-25-86
"", - , 29
.274-52-35
" ",- , 2
.219-26-17

" "
., 1
(0562) 33-09-55
"
.. 40
(0562) 744-86-72

" ". 147


(0622) 55-74-49

"-"
. 1
(0564) 29-81 -21

", ..
.72-54-06
"",
, 4,5, .39-8708

"'.., 58
.53-62-30

" " ,.,6


.47-80-20
" 3", . ,37,
.12-55-27

"" ,.,55
.124-92-02
"6-6",.,6
.928-87-44
" ",
-,40,. 137-60-38
' ",
. , 8
"" . -,78
.152-45-11
"", ...
.145-52-00 .
" " .2- ,54
.978-50-47, 978-55-07
" ", . , 2S
.238-11-44, 238-00-32
-
" '. -,28
.318-64-16
",
.,2,.164-65-65
"", -.189
.443-01-47

" XXI"
- ., 92,
.. ,
.64-31-05, 64-27-97

1) - ,
2)
3) ,
e-mail
4)
e-mail.

0 - ,
2
)
3
) ,
e mal1
'
4
)
e-ma.l.
*
! 5) ,
, 5)

, , .
.
.
, .
7 .
.

2001

: _
/

:

:.

- ;_

:
, ,.
:/

E-mail:

- :
.:03055/ 100, ./(044)212-1254,216-3564-!1:
books@diasoftkiev.ua
stepanb@akcecc.kiev.ua

www.diasoft.kiev.ua

- "' '-'


. !
. .

4756 .. ! !: 1
5616 , Mpj 1-7.
6700 , Hi . 2- .
4043 ., .
5611 , , ,
5164 i Linux
4683
5228 .
4020 ., , 8

5
9
15,9

19
30
39
25
29
34

79
95

195
150
195
169

160 84x108/16
208 70x100/16
672 70x100/16
584 84x108/16
544 70x100/16
400 84x108/16
544 60x84/16
720 70x100/16
548 84x108/16

9
Windows
5612 A., Ti Windows Me
2759 .
Windows 98.
306 .
Windows NT 3.51. ( + CD-ROM
5511 Microsoft Windows 2000 Professional.
5003 . Windows 2000. :
44 .
OS/2 Warp

4
16
25
5
49
75
5

79
150
135
245
395
28

0
304 70x1(10/16
608 84108\16
592 60x84/8
832 70x100/16
640 84x108/16
352 60x84/16

95
120
170
145
195
195
215
290
250
470
480

401 70x100/16
400 70x100/16
288 70x100/16
688 84x108/16
400 84x108/16
688 70x100/16
488 54x108/16
672 84x108/16
830 84x108/16
864 60x84/8
496 84x108/16

Linux, Unix
4653
5453
5758
3926

Red Hat Linux 6.0.


.
Red Hat Linux Windows
Linux IP Stacks
( + CD-ROM )
Unux 5.2. + 2 CD-ROM
5164 < Linux
5641 Unux. .
4844 Linux (+ CD)
5717 .
Red Hat Linux .
936 . Unix ( + ).
1557 P., Xopj Unix .
4318 ,) UNIX Internet . ( + CD-I

19
24
29
29
39
39
39
59
40
80
95

5462
4982
4754
5804
3850
5063
5056

.
C++.
.
,' C++ ^
. .
Visual Basic 6.
. Visual C++ 6 . ( + CD-ROM )
. Visual ++ 6 MFC. . ( + CD
. Delphi 4. ( )
. Delphi 6. .
. Delphi 5. .
. Delphi 4. ( + CD-ROM )
. Delphi 2. ( + CD-ROM ).
. Delphi
. Borland C++ Builder 3. ( + CDKylix 1.0. .

., Power Builder 6.0. ( + CD-ROM


. Windows 2000 API. ( + CD-RO
Internet- Delphi 2 ( + CD-ROM ).
.
.
PHP.
Python.
., .
, Apache Server .) + CD-ROM )
JavaScript
A., Ban JavaScript. ( + CD-ROM j

29
29
53
59
29
23
75
9
19
25
29
35
49
45
19
35
64
9
29
29
31
49
19
56

14S
179
275
295
165
150
390
45
95

Adobe Photoshop 6.0. -


2472 . / Adobe Photoshop 5 ( + CD-ROM )
5803 .. Adobe Photoshop 6.0.

4
19
19

20
95
96

3621

5845
5419

2757
242
93
2758
5799
1057
5571

650
5720
5149
6721

5258
5165

5355
5512

145
120
225
95
180
320
45
150
150
155
269
95
289

656 84x108/16
432 84x108/16
584 84x108/16
736 84x108/16
480 84x108/16
496 70x100/16
720 84x108/16
192 84108\16
576 70x100/16
592 70x100/16
400 84108\16
736 60x84/8
512 60x84/16
800 84108\16
288 70x100/16
816 60x84/8
1088 70x100/16
640 60x84/16
448 70x100/16
336 70x100/16
384 70x100/16
480 84x108/16
304 70x100/16
464 84108\16

, CAD-.
32 84x108/16
491) 84108\16
304 70x100/16

5587 Art Adobe Illustrator 9.0. ( + CD-ROM )


CorelDraw! 6 ( + CD-ROM )
169 .
551S . CorelDRAW 10
3D Studio MAX 3. ( + CD-ROM )
5002 .
3D Studio MAX 3 : , ]
4634
3D Studio MAX 4. > ( + CD-ROM
5802 .
3925 3D Studio 2. 3: ( +
2860 ., 3D Studio MAX 2. 2:
5080 . 3D Studio 3: .
649 . 3D Studio .. . 2- ( + CD-ROM )
570 . 3D Studio . 1 ( + CD-ROM )
2471 ., 3D Studio 2. 1 ( + CD-ROM ).
5069 Flash 4 . ( + CD-ROM )
5029 P. 4 ( + CD-ROM )
5262 . FLASH 5 + CD-ROM )
2101 i Adobe Web- .
4763 QuarkXPress 4 .
5163 PageMaker ( + CD-ROM )
AutoCAD 2000. (+ )
5064 .
4753 AutoCAD 2000. ( + CD-ROM
3924 . v AutoCAD 14. ( +

36
10
29
19
19
29
29
29
29
37
60
61
19
23
29
39
39
29
29
34
49

180
100
170
95
95
150
145
145
145

180
150
150
190
215
150
180
169

368 70x100/16
608 60x84/16
880 70x100/16
480 70x100/16
456 84x108/16
480 70x100/16
408 84x108/16
368 84108\16
720 84x108/16
432 84x108/16
752 84x108/8
848 84x108/16
448 70x100/16
336 70x100/16
496 70x100/16
650 60x84/8
424 84x108/16
704 60x84/16
784 70x100/16
688 84x108/16
767 84x108/16


4303 Microsoft Office 2000.
5139 ., Lotus Notes Domino R5. ( +
5096 Access 2000.
942 .
Oracle 7.3. ( + CD-ROM )
4925 i OracleS. .!
Oracle 8/8i Server. .
5057
Oracle 8. ( + CD-ROM )
1493 AJS
5640 | MS SQL Server 2000.
2010 - {. Informix.
3947 . . 1: High-Performance Networking. :
3927 . . 2: Networking Essentials.
1295 . Microsoft BackOffice 2. ( + CD1032 , Web-.
Internet
5510
40 ., Internet
802 . i World Wide Web.
314 ., ( + CD-ROM )
4849 .

29
79
75
42
75
75
160
49
60
30
65
9
9
16
5
9
15
45

145
390
390
195
470
390
245
300
180
250
45
45
125
28
45
215

552 84x108/16
656 84x108/16
544 84x108/16
736 84x108/16
800 84x108/16
576 84x108/16
864 60x84/8
688 70x100/16
800 60x84/8
432 60x84/8
432 84x108/16
800 60x84/8
460 60x84/8
448 60x84/16
384 60x84/16
544 84x108/8
352 60x84/16
368 60x90/8