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

-

, MySQL
JavaScript
CSS

[^

- - - -
-- - -
- -

2013


.................................. ............................... 21
.............................................................25
1. -... 26
2. ,
.................................. ...........................39
3. ...................................................62
4.
............... ............................................90
5. ...................................... 118
6. ................................................. 145
7. ............... 160
8. MySQL............................ .................188
9. MySQL...............................................230
10. MySQL ..................254
11. ............................................. 281
12. Cookie, ........................ 298
13. JavaScript.......................................... 318
14.
JavaScript.................................................... 338
15. , JavaScript................. 356


................................................................................... 21
...................................................... 21
, ...................................... 21
..........................................................................22
............................................................. 22
, ...................................... 23
........................................................... 24
.................................................................................24
............................................................................. 25
1. - ... 26
HTTP HTML: , -.................................27
.................................................. 27
, MySQL, JavaScript CSS.................... 29
...............................................................31
M ySQL......................................................... 32
JavaScript......................................................33
CSS...............................................................34
- Apache........................................................................... 35
.................... 36
, ......................................................... 36
.................................................................... 38
2. ,
.................................................................................39
WAMP, MAMP LA M P ......................................................... 40
WAMP Windows.................. '..............................40
......................................................... 47
W AM P........................................................... 49

Mac OS X .................................................50
MySQL...................................................................53
MySQL ...................... 54
............................................................... 54
LAMP Linux...................................................................56
............................................................. 57
...................................................................... 57
FTP.................................................................57
.................................................... 59
ID E ..........................................................................60
.................................................................... 61
3. .................................................................62
HTM L.................................................................... 62
.................................................................63
, .................................................... 64
.................................................................................65
.................................................. 65
...............................................................66
........................................................67
........................................................................... 71
....................................... 74
......................................................... 77
.................................................................. 79
........................................................................... 80
echo print.................................... 81
...............................................................................82
...............................................83
.................................................................... 88
4.
................ .............................................................. 90
.................................................................................... 90
......................................................... 92
.................................................................................... 93
................................................ .93
................................................ 95
........................................................... 96
......................................................................................100
i f .................................................................... 100
e lse ................................................................ 102
e lse if.............................................................. 103

switch...............................................................104
? ....................................................................... 107
.................................................................... 108
w h ile......................................................................109
do...while................................................................ 110
fo r......................................................................... I l l
................................................ 113
continue........................................................... 114
........................................... 114
.................................................... 115
....................................116
................................................................ 117
5. ................................................ 118
...............................................................................119
....................................................... 120
....................................................... 121
......................................................... 123
........................................................... 123
.................................. 125
......................... 125
......................................................... 126
include.............................................................126
indude_once................................ 126
require require_once....................127
........................................................... 127
...............................................................................128
.................................................................... 129
.............................................................130
...............................................................131
............................................................. 131
.................................................................... 134
.............................................................135
........................................................... 136
......................................................... 137
5 ....................... 138
.................................................................... 140
................................................................ 143
6. ...............................................................145
....................................................... 145
......................................... 145

10

......................................................147
, array................ 148
foreach...as......................................................................... 149
. . . .............................................................151
.............................. 154
is_array.............................................................................154
count...............................................................................154
sort.................................................................................. 154
shuffle...............................................................................155
explode.............................................................................155
extract............................................................................. 156
compact........................................................................... 157
reset................................................................................ 158
end.................................................................................. 158
................................................................ 159
7. ................... 160
printf....................................................... 160
......................................... 162
.............................................................. 163
sprintf.............................................165
.............................................................. 165
, ........................................... 167
checkdate....................................... 167
....................................................................... 168
........................................... 168
................................................................ 168
.............................................. ................170
......................................................... 171
........................................................... 171
................................................................ 172
........................................................... 172
....................173
.............................................. 175
-.............................................175
....................................................................... 181
XHTML........................................................................................182
XHTML......................................................... 183
XH TM L.................................................................. 183
XHTML HTML......................................................183
HTML 4.01................................................ 185

i i

HTML5......................................................185
XHTML 1.0................................................ 185
XHTML.............................................186
................................................................ 187
8. M yS Q L......................................................... 188
MySQL.................................................... 188
, ................................ 189
MySQL .............................................. 189
....................190
....................... 193
MySQL................................................................ 195
.................................................................... 199
.................................................................................... 208
...............................................................209
MySQL.............................. 214
......................................................... 223
.................................. 225
MySQL........................................................................... 226
MySQL phpMyAdmin................................................ 226
Windows................................................ 226
Mac OS X ...............................................226
Lin u x.................................................... 228
phpMyAdmin...................................................228
................................................................ 228
9. M y S Q L ........................................................... 230
....................................................... 230
: ...........231
............................................................................. 232
.................................................. 233
.................................................. 235
.................................................. 238
...........................240
................................................................................ 241
................................................................. 241
............................................................... 241
............................................................. 242
.................................................. 244
................................................................................ 244
( ) .................................. 245
BEGIN............................................... 246

12

COMMIT......................................... 246
ROLLBACK....................................... 246
EXPLAIN....................................................247
.............................248
mysqldump..................................... 249
......................................... 250
..................252
CSV .. . ........................... 252
................................ 253
................................................................ 253

10.

MySQL ..................... 254


MySQL .................................. 254
........................................................................... 254
.............................................. 255
MySQL..................... .................................256
.................................................................. 261
$_POST.................................................................. 264
................................................................ 264
......................................................... 265
....................................................... 266
.............................................................266
MySQL....................................................... 267
.............................................................268
.............................................................268
............................................................. 269
........................................................... 270
........................................................... 270
........................................................... 271
.............................................................. 272
AUTOJNCREMENT.............................272
.................................. 274
SQL-....................................275
HTML-................................ 279
................................................................ 280

11. ......................................................... 281


........................................................................... 281
.................................................. 282
register_globals:
........................................................................... 284
..................................................... 284

13

.............................................286
......................................293
......................................................................294
................................................................ 297

12. Cookie,

.............................. 298
cookie ........................................................... 298
cookie................................................................ 300
cookie................................ ................................. 301
cookie...................................................................301
HTTP-.................................................................... 301
............................. 304
......................................... 305
.................................................................... 308
.................................................................... 309
............................................................... 312
..................................... ....................... 313
.............................. ....................................317

13.

JavaScript........................................................318
JavaScript H TM L.................................................................. 318
...................... 320
.................................. 320
JavaScript.................................................321
JavaScript........................................................322
......................................................... 324
............................................................................. 324
............................................................................... 325
......................................................... 325
......................................................... 326
............................................................................. 326
.................................................................................. 327
.................................................. 327
....................................... ............ 328
......................................................... 328
....................................................... 329
......................................329
.............................................................. 329
....................... ..................................329
.................................................................. 330
.................................................................................... 331
.................................................................331

14

......................................................332
......................................................... 333
........................................................... 335
DOM........................................................... 336
................................................................ 337

14.

Ja v a S c rip t........... .................................................... 338


................................................................................ 338
..................................................... 339
................................................................................ 340
................................................ 341
.............................................................341
....................................................... 342
with........................................................................... 345
onerror......................................................345
try...catch.............................................346
......................................................................................347
i f .................................................................... 348
switch.............................................................. 349
? ....................................................................... 350
....................................................................................... 351
w hile......................................................................351
do...while................................................................ 351
fo r......................................................................... 352
................................................ 353
continue........................................................... 353
. . ; ....................................................354
................................................................ 355

15.

, JavaS cript..................... 356


JavaScript....................................................................... 356
....................................................... 356
....................................................... 358
........................................... ............. 360
JavaScript....................................................................... 361
.................................................. .......... 361
.............................................................. 362
.............................................. .............. 363
prototype.................................................... 363
JavaScript.................................................................... 365
............................................................. 366

15

......................................................367
....................................................... 368
......................................... 369
................................................................ 373

16.


JavaScript ......................................................................... 374
, , JavaScript.. . . 374
validate.html ( )....................................375
validate.html ( )....................................377
................................................................ 380
, ......................... 380
..................................... 381
........................................... 382
............................................................. 383
......................................................384
........................................... 387
....................................................... 388
JavaScript.................. 389
......................... 389

-......................................................................... 390
................................................................ 395

17.

A jax.................................. 397
Ajax?........................................................................... 398
XMLHttpRequest......................................................398
Ajax POST-......................................400
readyState........................................................... 402
Ajax-....................................... 403
GET POST.................................................... 405
XML-................................................................ 407
XML......................................................... 409
XML? ...................................... 410
Ajax ....................................411
................................................................ 412

18.

C S S ............................................................. 413
....................................................414
........................................................... 415
()....................................415
..........................................................415

16

CSS...............................................................................416
.............................................416
.............................................416
.............................................. 417
...............................................................................418
................................................................ 418
..................................................... 418
....................................................419
.............................................................. 419
............................................................. 420
C S S ........................................................................... 420
.................................................................. 420
.............................................................420
.............................................421
.............................................. 422
, ....................... 423
................................................................ 424
.................................................. .
424
....................................................425
........................................................... 426
C S S ......................................................................... 426
....................................................427
...........................................427
....................................................428
<div> <span>..................................................... 430
.................................................................................. 431
................................................................ 433
font-family......................................................................... 433
font-style........................................................................... 434
font-size............................................................................. 434
font-weight..........................................................................435
........................................................... 435
......................................................................436
.......................................................................... 436
.................................................................... 437
................................................................ 437
............................................................................. 437
CSS.............................. ..................................................... 438
..................................... .
438
......................................................................... 439

17

....................................................... 440
.............................................440
....................................... 441
....................................... 441
..................................... 441
............................................................................. 443
......................................................................... 445
445
.................................................. .
....................................................446
................................................................ 446
........................................................... 448
........................................................... 449
......................................................... 451
................................................................ 451
19. CSS C S S 3.............. .............452
.................................................................... 452
.............................................. 453
box-sizing......................................................................454
CSS3.................................................................. 454
background-clip..................................................... 455
background-origin.................................................. 455
background-size....................................................457
......................................... 457
CSS3............................................................................. 459
border-color......................................................... 459
border-radius....................................................... 460
.................................................................... 463
.............................................463
.............................. 464
................................................................ 465
HSL......................................................................... 465
HSLA....................................................................... 466
R G B....................................................................... 466
RGBA . . . ................................................................. 467
opacity................................................................ 467
, ....................................................468
text-shadow......................................................... 468
text-overflow....................................................... . 468
word-wrap........................................................... 469

18

-........................................................................... . . 469
- Google........................................................... 470
........................................................................... 470
.................................................................................. 472
, ....................................473
.............................................. 473
.............................................................473
................................................ 473
..................................................... 474
................................................................ 476

20.

CSS JavaScript...........................................477
getElementByld................................ 477
....................................................................... 477
S ....................................................................... 478
....................................................................... 479
........................................................... 480
CSS JavaScript......................................... 481
.................................................. 482
................................................................ 482
JavaScript.................................................................. 485
th is........................................................... 485
.............................. 486
......................................... 486
....................................................... 487
...........................................................489
.................. 489
...........................................................490
setTimeout..................................... 490
-.............................................................. 491
setlnterval....................................... 491
.............................493
................................................................ 495

21.

...........................................496
...........................................496
-.............................................................497
functions.php....................................................................... 497
........................................................................... 497
header.php............................................................................. 499
setup.php............................................................................. 501
index.php............................................................................. 502

,
1990-,
. (
,
) ,

, .

, - (Tim Berners-Lee) (
)
(Hyper Text
Transfer Protocol (HTTP)). ,
(Hyper Text Markup Language (HTM L)).
, - -.
,
.
,
,

. ,

(bulletin board systems).
- , 1990-
-
, 5 . ,
- . , ,
, ,

HTTP HTML: , -

27

. ,
G IF -.
,
.
, ,
,
.

. ,
. , ,
, ,
.

HTTP HTML: ,
-
HTTP ,
, ,
, -.
,
, -.
(). ,
, ,
-, , .
,
, , . .

. ,
.
- ,

.
.


-
- - -
. (. 1.1).
.
1. http://server.com.
2. IP -, server.com.
3. server.com.

1. -

28

4. - server.com.

5. -, , - .
6. -
.
7. -.

-
server.com


server.com

index

. 1.1.

-
: , - Flash-
CSS.
, 2 IP -,
server.com. , ,
, IP -. , , -
, google.com. , , ,
-,
(Domain Name Service (DNS)),
IP -, .

, MySQL, JavaScript CSS

29

-
, ,
M ySQL (. 1.2).
1. http://server.com.
2. IP -, server.com.
3. server.com.
4. - server.com.
5. -, , - .
6. , , - ,
, P H P -,
.
7. -.
8. M ySQ L-,
, , MySQL.
9. M ySQL
.
10. - ,
, MySQL.
11. - ,
.
,
, ,
.
H T M L-
JavaScript, .
,
, .

, MySQL,
JavaScript CSS
Web 1.0,
Web 1.1,
, Java, JavaScript, JScript ( JavaScript
Microsoft) ActiveX, .
(Common
Gateway Interface (C G I)), , Perl (
), (

).

1. -

30

-
1

MySQL

. 1.2. ,

,
. Perl
,
MySQL
.
A JavaScript, ,
(Cascading Style
Sheets (CSS)),
Ajax- . Ajax (
JavaScript) -
- ,
.
, MySQL ,
?

, MySQL, JavaScript CSS

31

: ,
- . MySQL
, ,
- ,
.
MySQL, ,
Web 2.0.
JavaScript CSS,
-.


,
.
, .
, :
<?php
echo "Hello World. Today is " .d a te ('T ').". ":

?>
How are you?

<?php -
?>. ,
, HTML. How
are you? . P H P- date
, .
:
Hello World. Today is Wednesday. How are you?

PHP ,
PH P- , :
Hello World. Today is <?php echo dateC'l"): ?>. How are you?

,
, . , ,
, - ,
, ,

HTML.

,
vIJ*
, <?php,
------ ?>, .
example.php, .
%

32

1. -

, -
. HTML,
,
-,
PH P-, HTML.

MySQL
, ,
-,
HTML.
,
, .
,
,
. ,
, ,

- - .

. MySQL,
-
, .
,
, .
M ySQL ,
, . ,
, users (),
surname, firstname
email, .
, , :
INSERT INTO users VALUES ( 'Sm ith', 'John',

'jsmith@niysite.com'):

, ,
,
INSERT
. INSERT
(Structured Query Language (SQL)), 1970-
COBOL.
,
.
. ,
.
MySQL:
SELECT surname.firstname FROM users WHERE email='jsmith@mysite.com';

, MySQL, JavaScript CSS

33

M ySQL Smith, John ,


.
, MySQL

INSERT SELECT. ,

, , ,
, ,
.

MySQL, MySQL
. , ,
,
,
, .
, MySQL
,
.

JavaScript
, , JavaScript,
H TM L. ,
,
,
? . . (
, -,
). CSS ( ) JavaScript
-, ,
, .
JavaScript ,

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

34

1. -

, JavaScript,
:
<script type="text/javascript">
document, write ("Hello World. Today is " + DateO ):
</script>

- ,
scrip t, JavaScript,
Hello World. Today is,
, JavaScript
Date. :
Hello World. Today is Sun Jan 01 2012 14:14:00

m%
? *
3?'

: JavaScript, ,
, type="text/javascript"
JavaScript <script>.

, JavaScript ,

, H T M L-, -
. JavaScript
Ajax.
- . ( JavaScript
X M L Asynchronous JavaScript and XML,
.)
Ajax , ,
Web 2.0 ( (Tim O Reilly),
,
), -
, .
Ajax
, ,
, , .
17.

CSS
(CSS3) CSS
,
JavaScript. ,
HTML, , , , , ,
CSS, - .
CSS
<st.yle> </style>, -:

- Apache

35

<style>

P
{
te x t-a lig n :ju stify ;
font-family:Helvetica:

}
</style>

<>,

Helvetica.
18 ,
CSS
, .
HTML.
, , , hover
. ,
CSS- JavaScript
HTML.

- Apache
, MySQL, JavaScript CSS -
-. ,
- Apache. , -
HTTP,
.
, Apache H T M L-
, Flash-
MP3, RSS- (Really Simple Syndication
) . . , HTML -, ,
.
,
G IF -. ,
. :
, , ,
. ,
Apache ,
. G D (
Graphics Draw - ),
.
Apache .
-
, .
Rewrite, -

36

1. -

U R L -
, Proxy,
,
.

,
.



, ,
, , MySQL Apache

.
,
,
,

.
.
:
. -
,
.
,
.

,
, MySQL, JavaScript CSS
,
-: -, MySQL
, CSS JavaScript
-. JavaScript P H P -
-, - ( ,
).
, ,
, , ,
-
Ajax: ,
- .
Gmail (. 1.3).

file

dit

https://accounts.go...
View

Favorites

Tools

37

Google Accounts

Help

Your Google Account is


more than just Gmail.

Name

Samuel

Talk, chat, share, schedule, store, organize,


collaborate, discover and create. Use
Google products from Gmail to Google+ to
YouTube, view your search history, all with
one username and password., all backed up
all the time and easy to find at (you guessed
it) Google.com.

Smith

Choose your username


@gmail.com

samsmith

Someone already has that username. Try another?


Available.

smithsamuel169 ss1676073

Create a password

-- ---- ---

:....

<^100% ^ ,
. 1.3. Gmail Ajax

Ajax- .
1. H T M L -,
: , ,
.
2. HTM L JavaScript,

: -
.
3.
, JavaScript
P H P - - .
4. - JavaScript
, , .
5. JavaScript
, ,
, .
6. ,
, JavaScript
(,
/ )
.
7. ,
,
.

38

1. -


.
Ajax , HTML
, . , ,
,
.
Ajax
, .
,
Ajax.

, MySQL, JavaScript CSS (
Apache) . 2
, -
, .
.


1.
-?
2. HTML?
3. M ySQL SQL?
4. JavaScript ,
-.
?
5. CSS?
6.
( ), , -,
?
,
1.

-,
, ,
, ,
- .

.
(
) Refresh
() .
,

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

, 1. ,
, JavaScript CSS,
-,
.
Internet Explorer, Mozilla Firefox, Opera, Safari Google Chrome.
, ,

Apple iOS Google Android.

40

2. ,

WAMP, LAMP
WAMP, LAMP Windows, Apache, M ySQL ,
, Apache, M ySQL Linux, Apache, M ySQL .
,
-.
WAMP, LAMP ,
,
. ,
, .
.
,
-, ^
.
.
-
.

W/L/MAMP,
,

.
, , .

WAMP Windows
W A M P-,
. ,
Zend Server ( Community Edition
),
. - http://tinyurl.com/zendce (. 2.1).
(
5.6.0 SP1 Windows), -
. ,
: Linux, Windows OS X.
. ,
,
.
<4-*
V ?--

------------------------------------------------------------

, , , , . ,
, .
4

WAMP Windows

41

http://www.zend.com/en/prc & * X ] P 9 Zend Server CE Downloads ... X


i : File

Edit

View

Favorites

Tools

Help

j
ii

Zend Server CE Downloads


Zend Server Community Edition (CE) is the free edition of Zend Server,
our production-ready Web Application Server
Server

Server CE

Complete PHP stack that includes ZF

Yes

Yes

Opcode acceleration {Zend Optimizer*)

Yes

Yes

PHP application deployment

Yes

Page caching and job queue support

Yes

PHP monitoring and code tracing

Yes

Zend Server Cluster Manager support

Yes

Technical support, updates and hotfixes

Yes

IBM only,
for 1 year

Service Pack/Hotfixes Available


Use the latest patches to ensure a fully secure environment!

0 Linux

Windows

ti*-. Mac OS X

Product

Version

Format/Size

Notes

Zend Server CE (PHP 5.3)

5 6.0 SP1

i'EXE)

Release Notes

58 23 MB

ji

^100% . 2.1. Zend Server CE Windows - Zend

, ,
. 2.2.
Next () ,
(Setup ) (. 2.3).
Custom ( ),
MySQL.
(Custom Setup),
,
phpMyAdmin MySQL Server (. 2.4). Next
().
(. 2.5), - IIS,
- Apache,
.
Next ().
80 - 10081 Zend (. 2.6)
Next ().

2. ,

Zend Server Community Edition Installer

Welcome to the Zend Servei Community Edition 5.6 Installer


The Installation w iza id will irv-alH > n d 'ie 'v e i Coriimumiv Edition on youi com putet
co ntinue click Next

. 2.2. Zend Server CE

server

lrr,!s89w*l

"<eack

. 2.3. Custom ( )

WAMP Windows

Zend Server Community Edition Instetler

Custom Setup
S elect com ponents to install

Only w ith a m a^ ed :h c j b o x w il o e it. '.r*llei A(t.:-r mMallahon run th e Installer ag a in


to ad d c o m p o n e n t; not selected >hi- tune

- - -----

-----------------

: L J Z e n d J a v a B tia g e

- Description---->

; D D o i o (se p a ia te d ow nload)

Informix

0 O r a d e O C I D river
@ phpM yA dm in I sep arate d o w nload!
1 D l B M D B 2 R T C L (se pa ra te d o w n lo a d l

M S SQ L N a liv e Clien t (se pa ra te d o w n lo ad I

1 4 9 .4 0 M B of sp a ce required on the drive


2 4 0 4 9 9 7 4 M B of s p a ce availab le on th e drive

. 2.4. phpMyAdmin MySQL Server

Zend Server Community Edition Installer

. 2.5. - Apache

2. ,

44

Zend Server Community Edition Installer

Zv -

server

Number

Click Next tc>use the default settings or change the port values that your Webserver will listen
and that the Administration Interface uses respectively

(10081

Ins-fcaRStesJd

OK

Ne>:( >

cl-

Cancel

. 2.6.

, . 2.7,
Install ().
,
.
, , Finish ()
.
,
, . 2.8.
, .
(. 2.9). ,
, Next () ,
. 2.10. Finish ().
.

4
----

- , ( -),
, 8080 ( 8000) -
10082 Zend.
, -, Zend. ,
- http://localhost/index.htm, http://
localhost:8080/index.htm.

WAMP Windows

45

5.39
Common Extensions
Additional Extensions
Zend Optjmeef+
Zend Debugger
Zend Data Cache
Zend Page Cache
Zend Monitor
Zend Job Queue
Zend Session Clustering
Zend Code Tracing
Zend Deployment
Zend Framework 1.11.11
Zend Framework Base

<

r-

. 2.7. Install ()

Step 1 of 3 : End User License Agreement


Please read and accept the following terms before using Zend Server Community Edition
[=3

Zend Technologies Ltd.


End-User License Agreement
This End-User License Agreement (this "Agreement") is a legal contract between
you, as either an individual or a single business entity, and Zend Technologies
Ltd. and its affiliates ("Zend)
READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY
BEFORE DOWNLOADING OR INSTALLING ZENDS PROPRIETARY
SOFTWARE (THE 'SOFTWARE") OR OBTAINING A LICENSE KEY TO THE
SOFTWARE OR USING THE SOFTWARE. THE SOFTWARE IS FURTHER
DEFINED IN AN ORDER DOCUMENT (AN 'ORDER'). ENTERED INTO
BETWEEN YOU AND ZEND OR YOU AND A ZEND RESELLER. WHICH SETS
FORTH COMMERCIAL TERMS APPLICABLE TO YOUR PURCHASE OF THE
CnCQUAQL

-.............

.....

..

__

__

I have read and agree to the end user license agreement terms

^811111118!81811111!1811888181
<*U0Q% *
. 2.8. Zend Server CE,

46

2. ,

Step 2 of 3

Set Password

Enter P .v 'vA'or-i

................

Retype P;r,*v*or'J

.............,)

. 2.9.

...

...

Http://localhostl00Bl/ZendServer/Loginsl3=
ifile

Edit

View

Favorites

Toots

|| Zend Server Community Ed.-. * j

^
<

Help

Welcome to
Zend Server Community Edition!
Thank you for installing Zend Server Community Edition - you've made a great choice!
If you ever want to enhance your PHP environment with:
Automated deployment

Perfoimance optimization

Application monitoring

* Advanced debugging and analysis tools

Clustering and scalability

24x7 technical support

You can try the advanced features of Zend Server free for 30 days at any time!

" ^Modify me of new ZendSetver Community Edition releases arid other important!
jjp dates
Email Address I

. 2.10. Finish ()

Dashboard ( ),
(. 2.11).

WAMP Windows

47

. 2.11. Zend Server

,
http://1 Ihost:10081 (,
Zend , 10081,
, ).


, .
-,
(. 2.12). U R L -
:
http://local host
http://127.0.0.1

1 1host U R L -
, 1- 127.0.0.1,
- .
^--1

, 80 ( 8080),
J URL-
. : http://localhost:8080.
. , URL http://localhost/example.php, http://
localhost:8080/example.php ( , ).

2. ,

48

- sex

http://127jQ.0X'1'
File

fd it

Yiew

Fjrvorites

Jools

I Zend Server Test Page

**

Help

The PHP Company

zend

Zend Server Test Page


Zend Server is now up and running on M s s

r Once content is added this message will no longer be displayed

if you are this server's administrator.


You can now add content to your Web saver's document root. You can configure and control your Zend Server
installation through the Zend Server Admtrastrabon interface Ptease refer to the documentation or to your
installation's README Ole for more nformabon
If you need help getting started with Zend Server, ptease visit the on-frne resources oace.
For more information about Zend Server you are vreicome to visrt us at ww.v.zend.com

. 2.12.

,
- . ,
U RL , http://yahoo.com http://
localhost.
Zend Server
( 32- ,
64-):
:/Program F i 1es/Zend/Apache2/htdocs
:/Program F ile s (x86)/Zend/Apache2/htdocs

pt^r*%

, , 32- 64-,
d l, . , , 32- . ,
, 64- .

, , ,
Hello World. H T M L, , Windows-
(
, Microsoft Word, ,
):

49

WAMP Windows

<html>
<head>
<title>A quick test< /title>
</head>
<body>
Hello World!
</body>
</html>

,
, t e s t . htm.
, ,
, (*.txt).
,
U R L- (. 2.13):
h ttp ://1 !host/test.htm

Fife

fdit

http://localhost/te5thtm P <$ X
View

Favorites

Took

A quick test

ft?#

Help

Heflo World!

^ 100% .
. 2.13. -


WAMP. ,
, http://tinyurl.com/zendcedocs.

WAMP

- .
Zend Server ,
,
.

, ,
, W AM P-,
, .
, , :
EasyPHP: http://www.easyphp.org;
: http://apachefriends.org/en/xampp.html;

50

2. ,

WAMPServer: http://wampserver.com/en/;
Glossword WAMP: http://glossword.biz/glosswordwamp/.

Mac OS X
Zend Server OS X. h ttp ://

tinyurl.com/zendce (. 2.14).

support
monitoring and code tracing

Yes

Zend. Sfirver.Glygtef.Manager
support

Yes

Technical support, updates and

Yes

hotfixes

orty.
for 1 year

Use the latest patches to ensure a fully secure envronmend


Linux

Windows ! Itf* Mac OS X

IBM i

Note: Zend Server CE for the Mac OS X platform is meant for development use only, not production use.
Product

Version

Zend Server CE (PHP 5.3) 5.6.0

Format/Size

Notes

(OMG) 152.90 MB

Release Notes

. 2.14. Zend Server CE OS X - Zend

(
5.6.0 SP1 OS X), -
.
: Linux, Windows OS X.
.
,
.

Mac OS X

51

, DM G.
, ,
. 2.15. ,
READ ME. Zend Server ( Zend) Zend Controller
( Zend) Applications, Go (
) Finder, .

z e n d 'S e r v e r

Community Edition

Double click to install Zend Server

Zend Server

RTF
README

11
To Install Zend Controller, drag the
icon to your Applications folder

. 2.15. Applications ()

, Zend Server Applications.


, (. 2.16).
Continue (),
, Continue (), ,
. 2.17. ,
. Macintosh HD.
, Install ()
.
,
. ,
Install (). ,
Close ().

52

2. ,

Welcome to the ZendServer Installer

6 Introduction

The Installation Wizard will install Zend Server on your computer.


To start installing, click Continue.

Read Me

Destination Select
Installation Type
Installation
Summary

_.
_
Community Edition

Go Back

-----------------------------

[ Continue

' -----------------------------

I
>

. 2.16. Zend Server CE

Standard Install on MMaclntosh HD"

0 Introduction
Read Me

This will take 485.5 MB of space on your


computer.

6 Destination Select
6 Installation Type

Click Install to perform a standard installation of


this software on the disk "Macintosh HD".

Installation
# Sum mary

Change Install Location...

Community Edition

Co Back

Install

~)

. 2.17.

,
Applications Zend Server .
, , ,

Mac OS X

53

. 2.8. , . 2.8-2.10,
,
.
.

MySQL
, Zend Server ,
, , MySQL,
,
Terminal :
sudo nano /usr/1ocal/zend/bin/zendctl.sh

Nano,

, MySQL_EN=" fa l se" , false
true.
, :
case $1 in
"start")

, :
SO start-apache

, :
$0 start-MySQL

MySQL . ,
, :
"restart")

, :
$0 restart-apache

:
$0 restart-MySQL

MySQL, .
MySQL, ,
:
"stop")

:
SO stop-apache %

:
$0 stop-MySQL

54

2. ,

Ctrl+X
. , ,
Return .

MySQL
M ySQL -,
Terminal :
cd /Library/StartupItems/ZendServer_init/
sudo rm zendctl.sh
sudo In -s /usr/local/zend/bin/zendctl.sh ./

Mac , MySQL .
, :
sudo /Library/Startupltems/Zend5erver_init/zendctl.sh restart


U RL
, . 2.18:
http ://localh ost:10088
http://127.0.0.1:10088

localhost ,
1- 127.0.0.1. , : 10088
, - -:
.
: 10088 http://localhost ,
. , tes:

URL http://localhost:10088/test.php.

, Mac-
* -, (
- * ), /usr/local/zend/apache2/conf/httpd.conf.
Listen 10088 ( 40)
Listen 80.
, Terminal : sudo
/usr/local/zend/bin/zendctl.sh restart.
:10088 URL-.

, http://localhost
http://localhost:10088, index, html,
,
- . ,
U R L - , http://yahoo.com,
- http://localhost.

Mac OS X

55

. 2.18. -

Zend Server
:
/usr/local/zend/apache2/htdocs

, ,
. , , TextEdit (
, Microsoft Word,
, ) H T M L, :
<html>
<head>
<title>A quick test< /title>
</head>
<body>
Hello World!
</body>

</html>

, test.htm.

2. ,

56

U R L (. 2.19):
h ttp ://lo ca lh o st:10088/test.htm

. 2.19. , ,


.
, http://tinyurl.com/zendcedocs.
I
%

------------------------------------- !----------------------------------------------------------------------

URL-, ,
- tinyurl.com. , http://tinyurl.com/zendcedocs
, URL-, : http://files.zend.com/help/ZendServer-Community-Edition/zend-server-community-ed ition.htm.

LAMP Linux
, ,
Linux-. Linux,
LAM P .
Linux - MySQL,
, . ,
, ,
-, :
http://localhost

, , , Apache,
MySQL,
,
.
- , Zend Server
, http://tinyurl.com/zendce.

57

.

, ,
.


-,
MySQL, -.
,
. , ,

.
MySQL.

Telnet SSH. , -,
, ,
M ySQ L ( , ,
).


Windows Telnet SSH (
, SSH , Telnet)
PuTTY, http://putty.org.
SSH .
Applications, Utilities,
Terminal. , SSH
:
ssh mylogin @ server.com
server . , , a mylogin
, .
, ,
.

FTP
- FTP-.
, ,
.
FireFTP,
:

2. ,

58

- Firefox
, ;
, ;
FTP- ,
- .
&
: Microsoft Internet Explorer, a FireFTP
. , , -,
,
.

FireFTP - http://fireftp.mozdev.org,
Firefox, Download FireFTP ( FireFTP).
500 .
Firefox,
FireFTP Tools () (. 2.20).
t

> robmnixoncom -FireFTP - Mozifla Firefox


File Edit View History
' (?

Bookmarks Jools
j ^

Help

chrome//fireftp/coritent/fireftp.xul

disconnect ftfit Abort

P\

* Coogis

| Log/Queu<| loots )
- ' Change

-a&lpmj.net

>10
>11
12
>13
1>14
(15
)16
{Q17

Name

Ljl-php
p lO .p h p

Size

ak3lpmj.net

Date

> O io

2 KB ... Mar 19 2011


4 KB ... Mar 192011

(jll.p h p
Q l2 .p h p

2 KB

LJl3.php
p l4 .p h p

2 KB ... Mar 19 2011


2 KB . Mar 19 2011

t>CDU
12
> D i3

,. Mar 19 2011

2 KB ... Mar 19 2011

Ljl5 .p hp

3 KB

[Jl6.p h p

3 KB ... Mar 19 2011

L)17.php

2 KB ... Mar 19 2011

>C)20
>CJ4

Q ie .p h p
)l9 .p hp

2 KB ... Mar 19 2011


2 KB ... Mar 19 2011

2.php

2 KB .... Mar 19 2011


3 KB ... Mar 19 2011

>C)4

L)3.php

3 KB ... Mar 19 2011

>05

p4php
Q s .p h p
p 6 ,p h p

4 KB ... Mar 19 2011


4 KB ... Mar 19 2011

>06
>07

p 7 .p h p

3 KB ... Mar 19 2011


4KB ... Dec 32010

>09

Q e .p h p
-*-

4 KB ... Mar 19 2011


aj

O l8
> Q l9

7
t>CD8

>09

l E 3__

Lj20.php

... . .....

.. Mar 19 2011

>>16
17
18

@D

Q l 9

20

>08

l>Qe

__

Name

See ... Date

L jl.p h p

2KB _

Mar 19 2011

lO.php

4KB _

Mar 19 2011

[ j 11.php
p l2 .p h p
Q l3 .p h p

2 KB _. Mar 19 2011
2KB _ Mar 19 2011

P 14. php

2 KB ... Mar 19 2011

2 KB

L jl5.php

Mar 19 2011

L j l^.php

3 KB ... Mar 19 2011


3K6
Mar 19 2011

[ J 17.php

2 KB

p l8 .p h p

2 KB
2

L j 19.php
U 2.php

. Mar 19 2011
Mar 19 2011
Mar 19 2011

2 KB

Mar 19 2011

|_]20.php
Lj3.php

3
3KB

Q 4 .p h p

4 KB ..

Mar 19 2011
Mar 19 2011

p 5 .p h p

4 KB ..

Mar 19 2011
Mar 19 2011

L]6.php

3KB

Mar 19 2011

[_j7.php

4 KB ... Mar 19 2011

Q 8 .php

4 KB - Mar 19 2011
3*T> _ u .n u a iJ L

....

220 robinixon.com FTP server (Version 6.00LS) ready.

Log [.Queue I
Local listing: 62 object(sX 521 MB. Disk Space Available: 8 GB

Binary

. 2.20. FireFTP FTP Firefox

FTP- FileZilla,
http://filezilla-project.org Windows, Linux Mac OS X 10.5
.
, FTP-, .

59


HTML, , JavaScript CSS
, ,
,
, .

, .
, ,
.
,
Editra, Mac OS X,
Windows Linux/Unix (. 2.21). , -
http://editra.org Download () ,
.
*examples.php - file//C:\Users\Robin\Desktop\examptes.php - Editra vO.6.99
Fite |dit

View

Fgrmat

gettings

Toob

jjd p

$contents * 0file_get_contents($page);
if (!$contents) return FALSE;
$checksun. = iad5 ($contents) ;
if (file_exlats($datafile))

m
$rawfile
$data
$left
rigbt

=
=
*
=

file_get_contents($datafile);
explode("\n", rtrim($rawfile));
array_ap{nPU_Fln,
$data);
array_map ("",
$data);

$exists

= -1;

for ($j

0 ; $j < c o u n t ($left)

; ++$j)

{
if ($left[$]

$page)

{
$exists = $ j ;
if ($right[$3 J

>

$checks mu) return 0 ;

PHP

cpl252

CRLF

Line: 1569 Column: 33

. 2.21. Editra

Editra , ,
. , Editra
,
. Editra
, .

60

2. ,

IDE
,
,
(Integrated Development Environment, IDE),
,
,
.
. 2.22 phpDesigner
, ,
Code Explorer, ,
, .

-Rod Goto Insert Fownat CSS JavaScript f

\Q

? v d

fib

il foWa

Debug Project Tools Svn (St Highlighters View Window Help : Trial expires in 21 days

T-.. --. >yil ^ - SB -

>\\

j0DCphp]_:
CodeExpkiref
2847
2848
2849
2860
2851
2052
2853
2854
2855
2056
2857
2858
2859
2660
2861
2862
2063

4
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877

if (Stcolor)
if (Stsize)
(Slabela)
(Slegends)
(Scolors)
(Sbgfill)

if
if
if
if

Surl

h)

Stall
Stall
Stall
Stall
Stall

AutoBad<ljnfcs($f3ename)

6-
; S-

BBCode($rtmQ)
EloddUseyCootae{$act>on, $hande, Sexpre)

BBypassCapteheO
B-fiCapsContrQK$*e*t,Stype)
- A ChedcCapttha($captiha, $tofeen, $ea<U, $salt2)
Q C hed4r*s(Spagef Stmeout, $rurtrne)

"http://chart.apie.google.com/char t?j||!";
chart in-ag*

| E&- Q OoseSessonO
! ~
ConvertCurrency($aniount, $from, $to)
i S ] ) ComerGrf($CDmer, {border,

Siitage imagecreatefrompng ($url);


Sw * imagesx(Simage);
Sh = imagesy{$ireage);
Sijcage2 * imagecreatetraecolor (Sw + Sborder
2,
Sh + Sborder * 2);
Sclr * imagecolorallocate(Slmage,
hexdec(sobstr($bcolor, 0, 2 )),
hexdecfsubstr(Sbcolor, 2 , 2)),
hexdec(sobstr(Sbcolor, 4, 2)));
imagefilledreatangle ($itr.age2, 0, 0, Sv + Sborder ' 2
Sh + Sborder * 2, Sclr);
imagecopy($iuage2, Siitage, Sborder, Sborder, 0, 0, Sw, Sh);
imagedestroy(Simage);
return Sin>4ge2;

function CurlGetContenta(Surl, Sagent) // Recipe 72

\& Mjncoona tltMj


j
& AddUBerToOetStabte, Snrnax, jhroax, isaltl, $saj
B- Q Anayamfinder($*ofd, $ftename)

: e |]auitTrf($uito)

\ - 4 3 CreateC aptiha($siie, le n gth, $ fc o t $falder,


; - Q

CreateGoogteOrt{$W ie, ftc d o r, $tsae, $type,

j - Q
: ()- ^

CreateUst($ttHTBf start, $type, S b J e t)


DeateSesaorKShandk, (pass, $iam e, $onaJ)

CieateShortURl($uH, Vedrect, *, $Se)

! -

CuriGetContents($Lrl/ Sagent)

j -
j Q

OrectDryOaKSpath)
ttsptovBngMap($tat, $ong, Sroora, Sstyte,

I f flb r t o e d y o u T i* e V k ie o ( $ d , * {height,
; G9- Q EvakjateExpressondexpr}

FT.FNKSf, St, $b, $e)


: (- Q FetchFld<TStream($acnxr*t)
" 3 FetrhWloPage(Sentry)

|
!

. 2.22. IDE, phpDesigner,


PHP-

ID E ,
( ),

.
,
ID E ,
.

61

,
. ,
. . 2.1
P H P - U RL-,
.
2.1.
IDE

URL-

W in

Eclipse PDT

http ://eclipse.org/pdt/down loads/

Mac

Komodo IDE

http://activestate.com/Products/komodo_ide

$245

Linux

NetBeans

http://www.netbeans.org

phpDesigner

http://mpsoftware.dk

$39

$119

PHPEclipse
PhpED

http://phpeclipse.de
http://nusphere.com

PHPEdit

http://phpedit.com

$119

Zend Studio

http://zend.com/en/downloads

$395

ID E , ,
- ,
, .
, ,
.
IDE,
3,
H T M L , . ,
, ,
.


1. WAMP, LAMP?
2. 1- 127.0.0.1 URL- http://localhost?
3. FTP-?
4. -.
5. ,
?
,
2.

1 ,
,
-. ,
, 6.

(ID E ), 2. ,
,
.
ID E , ,
.
HTML,
- ( ,
).
- ,
HTML, JavaScript, MySQL CSS.
, ,
.
.
P H P -

.

HTML
P H P - .
- ,
P H P -. -
, - ,
P H P -
HTML. ,
.
,
-.

HTML

63

HTML. ,
H T M L-, index.html,
i ndex.php, , .


.
:
<?php

, , .
, .
, , :

?>
P H P - Hello World ,
3.1.
3.1.
<?php
echo "Hello world":

?>
.
, HTML
.

, ,
,
HTML.

, ,
, ,

.
, ,
, ,
, HTML
, - .
,
PH P - , ,
:

<?
echo "Hello w orld":

?>
P H P -,
, , , .

64

3.

, X M L
( ,
).
&
^*.*1*

, ?> .
,
( - ).

4
f

,
, ,
- http://lpmj.net, 2nd_eci t i on_
examples .zip, Download Examples ( ),
(. 3.1).
1
| |

Eil

Edit

http://lpmj.nrt/
View

Favorites

Xools

~ 8

x | 1 Learning PHP, MySQL & Ja...

l -

X L g J

Help

Learning , MySQL & JavaScript


REILLY

By Robin Nixon
Home I >

(O'Reilly 2009, ISBN 978-0596157135)

t I Buv Paperback / Kindle [ Download Examples

Find out for yourself why Learning PHP ; MySQL & JavaScript is the number-one best-selling blockbuster
that has been at the top o f the charts for over two years worldwide, is the first result returned on PHP by
Amazon US, UK and Canada, the first foreign language title on PHP returned on European Amazon websites,
and in the top 10 foreign books on PHP on Amazon Japan and China!
Learning PHP, MySQL A JavaScript will teach you how to create responsive, data-driven websites with
the three central technologies of PHP, MySQL and JavaScript - whether or not you know how to program. This
simple, streamlined guide explains how the powerful combination of PHP and MySQL provides a painless way
to build modern websites with dynamic data and user interaction. You'll also learn how to add JavaScript to
create rich Internet websites and applications, and how to use Ajax to handle background communication with
a web server.

Contents of 2nd Edition


1. Introduction to Dynamic Web Content

2. Setting Up a Development Server

PHP, MySQL
& JavaScript

3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.

Introduction to PHP
Expressions and Control Flow in PHP
PHP Functions and Objects
PHP Arrays
Practical PHP
Introduction to MySQL
Mastering MySQL
Accessing MySQL Using PHP
Form Handling
Cookies, Sessions and Authentication
Exploring JavaScript

. 3.1. , , http://lpmj.net

(,
example3-l. php). , examples. zip,
named_examples, , -

65

(
3.4, t e s t l . php).


.
,
,
. , ,
, .


. ,
,
:
//

,
. ,
, ,
:
// echo "X equals $";

,
:
$ += 10: // $ 10

, ,
,
3.2.
3.2.

<?php
/*
-: *.
6yze~
/ */

?>

/* */ .
,

,
.

3.

66

/* */ ,
, ,
. ,
PHP- , ,
.
,
.


, Perl,
Java. , ,
, .


,
:
$ += 10;

, ,
, . ,
,

Parse error.

$
$ .
, BASIC $
, , .
$ .
, P H P - , ,
. ,
, , ,
3.3.
3.3.

<?php
Smycounter = 1;
$mystring = "Hello":
Smyarray
= arrayC'One". "Two". "Three"):

?>

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

67

, ( ),
,
.
, .


, , . ,
( ) !
, .


, , username (
). Fred Smith
(. 3.2).
:
$username = "Fred Smith":

. 3.2. ,

, Fred Smith .
,
().
, .
, , ,
, .
:
echo $username:

3.

68

(
):
$current_user = Susername:
,
, ,
( , 2),
, 3.4
( 2)
t e s tl. php.
3.4. -

<?php // testl.php
$username = "Fred Smith":
echo Susername:
echo "<br />";
$current_user = Susername:
echo $current_user:
?>

:
http://localhost/testl.php
nr

--1 ------------------------------------------------------------~

- ( 2)
V? - , 80,
9?*' URL . ,
8080, URL :
http://localhost:8080/testl.php

.

Fred Smith,
echo Susername,
echo $current_user.


, .
, Scount 17
, , 17 ,
count:
Scount = 17:
(
); :
Scount = 17.5:

69

,
. Scount
- , echo.

. ,
Steam. ,

.
team
(. 3.3). :
Steam = array( ' B i l l . 'Joe',

'Mike'.

'C h ris'.

'Jim');

. 3.3.

.
:
;

.
.
, 4,
:
echo $team[3]; // Chris

3, 4 ,
P H P - , , ,
0 4.

70

3.


. ,
,
.
, ,
-, ,
, 3 4 3.
, , ,
(. 3.4).

. 3.4. ,


. . ,
, 3.5.
.
3.5. ^

<?php
Soxo = array (( . ,
a rra yC o '. ' ',
arra yC x '. ' ',

?>

' '),
).
" ));

, ,
. array !;
=
.
>4 PHP-, ^ ** :

71

, ( ) , , [1]
J o , [2]
*.' .
.

, ,

.
.
6.


P H P -
.
_ (
).
: a-z, A-Z, 0-9, _ (
).
.
,
(,
$user_name).

. $Hi gh_Score
$high_score.

, ,
, , , .
. ,
8:
echo 6 + 2 :

,

.


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

72

3.

3.1.

$j + 1

$ j- 6

$j * 11

$ j/4

( )

$j % 9

++

()

++$j

--

( )


.
=, +=, -= . . (. 3.2).
+=
, . , Scount
5,
Scount += 1;

Scount 6 ,
:
Scount = Scount + 1;
3.2.

$j = 15

$} = 15

+=

$j+ = 5
*
II

$j /= 16

$j = $j / 16

.=

$j .= $k

$j = $j $k

%=

/=

SP
II
SP

*=

II

00

CO 00
1 *
S?
II
II

CO
I1
I

-=

5:
+

, (.),
.


, ,
i f, .
, , ,
, -
. . (. 3.3).

73

3.3.

==

!=

!= 21

>

$j >

<

$j < 100

>=

<=

II
V

Lf)l 00
i

II
A

, = == .
, .

, , .


,
- . ,
. , :
12, 14 , , .
:
i f ($hour > 12 && Shour < 14) dolunchO:
do! unch,
. then
(), .
,
,
.
(
12, 14 ,
...). , -
TRUE FALSE,
,
.
. 3.4.
3.4.

&&

$j == 3 && $k == 2

and

$j == 3 and $k == 2

II
or
!

$ j< 5 11 $j > 10

$j < 5 or $j > 10

! ($j == $k)

xor

$j xor $k

74

3.

, && and;
11 . and or
, ,
, .
, and or,
, or ( 10):
mysql_select_db($database) or die("HeB03M0H0 "):

,
, TRUE,
, FALSE,
TRUE FALSE. ,
, . (ammonia),
(bleach) , ,
.
, .
:
$ingredient = Sammonia xor Sbleach:

, Sammonia
$bl each, TRUE, Si ngredi ent
TRUE. TRUE FALSE,
Si ngredi ent FALSE.


=
.
= .
,
. , :
$ += 10:

- ,
( 10), $.
:
$ -= 10:




, .
+= -= :
++$:

-$:

75

( i f)
:
i f (++$ == 10) echo $:

$
, , 10;
, .
(, ,
) , :
i f ($-- == 0) echo $;

. ,
$ .
TRUE, , ,
$ -1. echo: 0 -1 ?
, , ,
P H P -.
, ,

.
,
, , ,
, .
, : echo
-1, $
, i f , ,
echo.


, ,
(.).
:
echo " " . Smsgs . " .":

, $msgs 5,
:
5 .

, +=
, .= :
Sbulletin .= Snewsflash;

, $ b u lle tin ,
Snewsflash ,
$bul 1e ti
.

76

3.


,
. ,
,
():
Sinfo = ' $. : Svariable';

$i nfo ,
.
, Svari abl .
, ,
, :
echo " Scount

,
,
.
. ,
, .


,
, . ,
, (),
sis te r s, PH P - , .
, :
Stext = 'My s is te r's car is a Ford : /7

,
,
:
Stext = 'My s is te r V s car is a Ford':

,
, . ,
, ,
:
Stext = "My Mother always said V'Eat your greensV'.";

, ,
, ,
\t, \ \. ,
(
,
-):
Sheading = "";

77

, ,
, .
,
\t. ,
,
( \') (\\).


,
echo ( print), .
, ,
.
, 3.6.
, 3.7.
3.6. echo,
<?php
Sauthor = " ";
echo "
.
.
Sauthor.";

?>
3.7.
<?php
Sauthor = " ";
Stext = "
.
.
Sauthor.";

?>
,
<, here-document ( )
, , heredoc.
,
( ). 3.8.
3.8. echo,
<?php
Sauthor = " ";
echo < END

3.

78


.
.
- Sauthor.
_END;

?>
,
_END, , .

, , , H T M L-
, .
, END:

(
). ,
.

: heredoc- <<<_END..._END;/
\, , S Enter . ,
, heredoc
,
(\).

3.9 ,
.
3.9.
<?php
Sauthor = " ":
Sout = <_END

.
.
- Sauthor.
_END;

?>
Sout ,
. , ,
Sout =
.=.
, END,

Parse error.

79

END,
.
, END , ,
- .
, _SECTI0N1 _
OUTPUT . . , ,
; ,
.

,
, -,
HTML (
$author -
).
, , ,
,
. ,
, ,
.


. ,

,
.
, , ,
- , , .
( 3.10) 12 345 67 890
838 102 050, Snumber.
3.10.

<?php
Snumber = 12345 * 67890;
echo substr($number, 3, 1);
?>
, Snumber .
-
substr, Snumber ,
( , ).
Snumber ,
, substr
, 1.
. .
3.11 Spl ,

3.

80

,
,
78,5398175.
3.11.
<?php
$pi = 3.1415927";
Sradius = 5;
echo $pi * (Sradius * Sradius);

?>
,
. , ,
. , ,
, , echo.

, , ,

, ().
,
.
,
(,
-). :
define("R00T_L0CATI0N . "/us /1 1/www/");

,
( ):
Sdirectory = R00T_L0CATI0N;

, P H P -
, .
--1

%
? J *

:
$ ( ) define.


,
- .


,
, , .
, ,
.

81

,
.
. 3.5. , ,
.
3.5.

_LINE_

_FILE_

.
include, .
4.0.2,_FILE_
,

_DIR_

. include,
.
dirname(_FILE_).
,
. ( 5.3.0)

_FUNCTION_

. 5, ,
( ). 4

. ( 4.3.0)

_CLASS_

. 5, ,
( ). 4
.
( 4.3.0)

_METHOD_

. ,
( ). ( 5.0.0)

_NAMESPACE_

( ).
. (
5.3.0)

, ,
, :
echo " " . _LINE_ . " " . _FILE_:

-
, ( ).

echo print
echo
. ,

. , .
echo , :
pri nt. , print
, , a echo
.

82

3.

, echo print,
.
, , , pri nt,
.
, (TRUE)
(FALSE), pri nt,
echo ,
Parse error:
$b ? print "TRUE" : print "FALSE":

,
$, . ,
, , $
, , , , $
.

echo, , - pri nt.

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

,
( ),
,
. .
, , 3.12.
3.12.
<?php
function longdate($timestamp)

{
return dateC'l F jS Y", Stimestamp);

}
?>

Unix ( , ,
1 1970 ), P H P - date

83

,
1 2016.
,
. ,
, .
,
:
echo longdate(timeO):

Unix
1ongdate,
echo, -
time. ,
:
echo 1ongdate[i ' () - 17 * 24 * 60 * 60):

I ongdate Unix,
, 17 (17 24 * 60 * 60 ).

, ,
.


,
, , ,
. , , , ,
$temp ,
, -
.
.
,

.

. ,
.

. ,
Stimestamp.
, ,
.
,
longdate ( 3.13).

84

3.

3.13. longdate
<?php

function 1ongdate(Stimestamp)
{
$temp = dateC'l F jS Y", Stimestamp);
return ": Stemp";

}
?>
, date,
Stemp, ,
. ,
Stemp , .
, ,
, 3.14. Stemp
1ongdate.
3.14. Stemp
longdate
<?php
Stemp = ": ";
echo longdate(timeO);
function longdate(Stimestamp)

{
return $temp . dateC'l F jS Y , Stimestamp):

}
?>'
Stemp 1ongdate,
, longdate
.
. ,
(Noti : Undefi ned
variable: temp).
, , ,
, ,
, ,
.
3.15 3.16 ,
3.14.
3.15. Stemp

<?php
Stemp = ":
echo Stemp . longdate(timeO);
function longdate(Stimestamp)

85

return dateC'l F jS Y". Stimestamp);

}
?>
3.15 Stemp .
, .
3.16. :>5 : Stemp

<?php
Stemp = ":
echo 1ongdate($tenr. : ' T5());
function longcaie.S.eA*. Stimestamp)

{
return Stext . caie-." F jS Y". Stimestamp):

}
?>
3.16 : Stemp
1~~ . longdate
,
Stext, .
*

*&~

, , ,
,
*** . , , , :
, ,
, ,
, .


, ,
, , .
,
.
, ,
global. ,
-, , ,
.
Si s_l ogged_i n:
global $is_logged_in;


1,
0. ,
.

86

3.

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

, , , ,
.
.

4
----

------------------------------------------------------------

* ( ), .


,
.
,
.
, , ,
,
? ? ,
, , .
, 3.17,
.
3.17. ,

<?php
function test

{
s ta tic $count = 0;
echo Scount;
$count++;

}
?>

$count, .
,
.
, Scount
,
Scount .

87

, ,
- .
( 3.18).
3.18. v

<?php
s ta tic $int = 0:
sta tic Sint = 1+2:

i~

-e::-..
:5:::5

(
D5rse error))

s ta tic Sint = sqrtd--^ ' :


?>


4.1.0.
. .
.
,
.

(. 3.6).
, 6.
..

$GLOBALS

,
.

$_SERVER

, , .
-,
, - -

$_GET

,
HTTP GET

$_POST

,
HTTP POST

$_FILES

, HTTP POST

$_COOKIE

, HTTP
cookies
*

$_SESSION

$_REQUEST

, ;
S_GET, S_POST $_1

$_ENV

, environment

( )
, ,
, ,
.

88

3.


, .
,
, U R L - ,
-.
:
$came_from = $_SERVER[' HTTP_REFERRER ];
, .
, U R L- ,
$came_f .


,
,
-. S POST, $_GET
, Unix MySQL,
, ,
.

.
P H P - htmlentities.
HTML. , (< >)
& lt; &gt;,
, . .
$_SERVER ( ) :
$came_from = htm lentiti es($_SERVER['HTTP_REFERRER ]):

, .
4
, ,
.
,
, ,
.


1. ,
? ?
2. ?
3. ?
4. ?

89

5. ?
6. Svariable = 1 Svariable == 1?
7. ,
($current_user), (Scurrent-user)?
8. ?
9. ?
10.
(, )?
11. ++$j $j++?
12. && and?
13. : echo
?
14. ?
15. ?
16. echo pri nt?
17. ?
18. -?
19. ,
?
20. ?
,
3.

,
, ()
. 3
,
.
,
.

.

.
, . :.
,
, - : :
= 3(abs(2x) + 4)

:
$ = 3 * (abs(2*$x) + 4);

( $) .
( . 5!:*:
X IX ).
, , .
~_.
FALSE. , 21 > *(20 9) (
5 == 6 (5 6) (-_5). (, .
, 11.11

91

, AND, O R XOR,
.)
, TRUE FALSE
. ,
. ,
,
. , , ,
, , ,
, ,
.
4.1 : ,
, .
d, ( < />
H T M L
).
4.1.
<?php
echo "a:
echo "b:
echo "c:
echo "d:

?>

[" . (20 > 9) . "]<br />"


[" . (5 == 6) . "]<br />"
[" . (1 == 0) . "]<br />"
[ . (1 == 1) . "]<br />"

:
: [1]

: []
: []

d: [1]
, , : d:,
(TRUE), 1.
: : (FALSE) ,
FALSE NULL ().
, , 4.2.
4.2. TRUE FALSE
<?php // te st2 .php
echo "a: [
TRUE
"]<br />"
echo "b: [" . FALSE . "]<br /> ;

?>
:
: [1]

: []
, FALSE 0
-1, .

4.

92


, ,
, 73 Hello.
,
. ,
.
4.3 ,
, .
4.3.

<?php
Smyname = "Brian";
Smyage = 37;
"<br
echo "a: " . 73
"<br
echo "b: "
"Hello"
"<br
echo "C: " . FALSE
echo "d: " . Smyname ., "<br
echo "e: " . Smyage . "<br

?>

/>":
/>";
/>";
/>";
/>":

//
//
//
//
//

,
, ;,
FALSE :
:
b:
:
d:
:

73
Hello
Brian
37

,
, -
.

. 4.4
.
366 - $day_number $days_to_new_year,
, $days_to_new_year < 30
TRUE.
4.4.

<?php
$days_to_new_year = 366 - $day_number;
i f ($days_to_new_year < 30)

//

{
echo " !":

}
?>

//

93

, ,
,
(. 4.1).
4.1.

$ + $

$ + $

$ = $ + 23

12 9

$ < $

'Is -

$++

$ and $b

$ . $

.
, ($++)
(-$), .
, ,
, , ,
.
0 , ? : z. ,
i f,
,
. .


,
, .
,
4.5.
4.5.

1 + 2
2 - 4
5 + 2

+3 - 4 + 5
+5 + 3 + 1
-4 +1 + 3

94

4.

, , (
), 7,
.
( 4.6).
4.6. ,
L * 2 * 3 / 4 * 5
2 / 4 * 5 * 3 * 1
5 * 2 / 4 * 1 * 3

7,5. ,
,
4.7.
4.7. ,

1 +2 * 3 - 4 * 5
2 - 4 * 5 * 3 +1
5 + 2- 4 + 1 * 3

,
25, -29 12 .

,
, ,
, 4.8.
4.8. ,
1 + (2 * 3) - (4 * 5)
2 - (4 * 5 * 3) + 1
5 + 2 - 4 + (1 * 3 )

, ,
, , 4.9.
4.9.
1 + (6 ) - (20 )
2 - (60) + 1
5 + 2 - 4 + (3)


-13, -57 6 ( 25, -29 12,
).
, ,
, ,
, (
4.10).
4.10.
((1 + 2) * 3 - 4) * 5
(2 - 4) * 5 * 3 + 1
(5 +'2 - 4 + 1) * 3

95

, , 25, -29 12
.
. 4.2
.
4.2. , ( )

()

0
++ -!

* /%

+-

<< >>

<<=>> =

1-------|

&

( )

1
&&

II
?;

= += -= *= /= .= %= &= != = <<= >> =

and

xor

or


,
, .
.
.
,
. . 4.3 ,
.
4.3. ,

NEW
j

++ "


&

96

4.

4.3 ()

+-

(nt)

(double)

(string)

(array)

(object)

, 4.11,
0.
4.11.

<?php

$1evel = Sscore = $time = 0;


?>
,
,
.
S

--1 ------------------------------------------------------------


4 3?' , . ,
, , .



, TRUE, FALSE.
: , .


== ( )
. = (
). 4.12 ,
.
4.12.

<?php
Smonth = "";
i f (Smonth == "") echo " ";

?>

97

, TRUE FALSE,
, i f . ,
.
, ,
.
, , ,
. 4.13 $ $
, , -
i f .
4.13.
<?php
$ = "1000";
$b = "+1000":
i f ($ == $b) echo " I ;
i f ($ === $b) echo "2";

?>

, , ,
i f TRUE. ,
, 1000 , +1000.
, i f
,
. $ $
,
.
,
, ,

.
,
, !=.
4.14 4.13,
.
4.14.
<?php
$ = "1000";
$b = "+1000";
i f ($ != $b) echo "1":
i f ($ !== $b) echo "2";

?>
, , , i f 1,

$ $. 2, i f
$ $,
TRUE, .

98

4.


, ,
.
> (), < (), >= ( ) <= ( ).
4.15 .
4.15.

<?php
$ =2: $ = 3;
i f ($ > $b) echo "$
i f ($ < $b) echo "$
i f ($ >= $b)echo $
i f ($ <= $b) echo "$

$b<br />";
$b<br />";
$b<br />":
$< />";

?>
, $ 2, $
3, :
2 3
2 3

,
$ $, .
, .


,
. (. 4.4).
4.4.

AND

(TRUE),

OR

(TRUE),

XOR

(TRUE),

NOT

(TRUE),
, (FALSE),

4.16. ,
NOT !. ,
.
4.16.

<?php
$ = 1: $ = 0:
echo ($ AND $b)
echo ($ or $b)

"<br /> :
"<br />":

99

echo ($ XOR $b) . "<br />":


echo !$a
<br />";

?>
NULL, 1, 1, NULL. ,
echo TRUE.
( , NULL, , FALSE.)
, AND, TRUE,
, ,
$ NOT, TRUE
(, ) FALSE. ,
, $ $ ,
1 0.

, , AND OR
, && 11.
----- , , && 11.

i f OR
, ,
TRUE. 4.17
getnext , Sfinished
1.
4.17. , 0R

<?php
i f (Sfinished == 1 OR getnext0 == 1) exit;

?>
, getnext if,
, 4.18.
4.18. i f

... OR. getnext

<?php
$gn = getnextO;
i f (Sfinished == 1 OR $gn == 1) exit;

?>
getnext
$gn i f.

, getnext
4 ,
^
.

. 4.5
. , !TRUE FALSE, 1FALSE
TRUE.

100

4.

4.5. ,

XOR

AND

OR

TRUE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

FALSE

TRUE

TRUE

FALSE

TRUE

FALSE

TRUE

TRUE

FALSE

FALSE

FALSE

FALSE

FALSE

.
- .
-
,
- .
: i f , swi tch ?.
, , ,
, ,
( )
, .

if

. ,
,
.
i f , ,
, ,
TRUE.
,
. ,
TRUE,
(. 4.1).
i f , , , NULL
, ( ,
).
, TRUE, ,
, { }. ,
. ,
, , ,
, ,
, - -

101

. (, ,
, , ,
.)

. 4.1.

4.19 ,
, .
4.19. i f ,

<?php
i f ($bank_balance < 100)

{
Smoney
= 1000;
$bank_balance += Smoney;

}
?>
, $100 ( 100
). ,
$1000, . (
!)
$100 ,

( ).

, .
.
,
(,
). ,
,
.

102

4.

else
, TRUE,
,
- . else.
, . 4.2.

. 4.2. if else

i f . . .else TRUE,
.
FALSE, .
,
.
i f ... el se 4.20.

4.20. if ...e ls e ,

<?php
i f ($bank_balance < 100)

103

{
Smoney
= 1000;
$bank_balance += Smoney;

}
else

{
Ssavings
+= 50:
$bank_balance -= 50:

}
?>
, $100,
el se,
.
, i f , el se
, . (
. -, , , .)

elseif
,
. ,
el sei f . , el se,
, .
i f . . . e ls e if . . .else 4.21.
4.21. i f . . . e ls e if . . .else,
<?php
i f ($bank_balance < 100)

{
Smoney
= 1000:
$bank_balance += Smoney:

}
e ls e if ($bank_balance > 200)

{
Ssavings
+= 100:
$bank_balance -= 100:

}
else

{
Ssavings
+= 50:
$bank_balance -= 50;

}
?>
e ls e if i f
el se. , $200,
, ,
$100.

104

4.


(. 4.3).

else if...else, if...elseif...else.


, else ,
*
elseif, elseif
if.

elseif .
, , swi tch,
, , . .

switch
switch ,
, -

105

, , ,

. , : Home, About, News, Logi Li nks,
$page
, .
i f .. . e ls e if . . .else
, 4.22.
4.22. i f . . . e l s e i f

<?php
if
e ls e if
e ls e if
e ls e if
e ls e if
?>

(Spage
(Spage
(Spage
(Spage
(Spage

==
==
==
==
==

"Home")
"About")
"News")
"Login")
"Links")

echo
echo
echo
echo
echo

"
"
"
"
"

"
About
News"
Login
Links

, switch, 4.23.
4.23. switch

<?php
switch (Spage)

{
case "Home :
echo "
break;
case "About":
echo "
break;
case "News":
echo "
break;
case "Login":
echo "
break;
case "Links":
echo "
break;

Home":

About";

News";

Login":

Links":

}
?>
, Spage
switch. case.
, . ,

, , .
i

switch case .
break.
case switch .

106

4.

switch
, switch -
, break.
switch .
4.23 break
case, , TRUE,
, case. ,
$ News, , ,
case.
,
break , ,
case, . , break
.


switch
, ,
case. , , 4.23,
, 4.24.
4.24. default 4.23

default: echo " ":


break;

break , default

,
d efau lt ,
break,
.
break.


switch ,
endswitch ( 4.25).
,
, , - .
4.25. switch

<?php
switch (Spage):
case "Home":
echo " Home";
break;
// . .
case "Links"

107

echo " Links";


break;
endswitch;
?>

?
?
i f else. ,
, , .
3
pri nt echo, ,
pri nt, echo.
? , ,
: ,
TRUE, FALSE.
4.26 ,
.
4.26. ?
<?php
echo Sfuel <= 1 ? " " : " ";
?>

1 1 ( ,
Sfuel , ),
echo .
. ,
?, - ( 4.27).

4.27. ?

<?php
Senough = Sfuel <= 1 ? FALSE : TRUE;
?>
Senough TRUE
, 1 ,
FALSE.
? ,
i f , ,
, .
, ,
- .
, :
Ssaved = Ssaved >= Snew ? Ssaved : Snew;
1

1 () = 3,79 . . .

4.

108

, , :
Ssaved

=
Ssaved >= $new

?
$saved
$new;

//
//
//
//
//
//

$saved
$saved Snew

...
... $saved
...
... $new

,
.
Ssaved
$new. , ?, ,
, i f .
,
, ,
, , .



.
, - ,

.
.
, , . 4.4.
,
i f , , ,
.

109

while
4.26 ,
,
whi 1 ( 4.28).
4.28. while

<?php
Sfuel = 10;
while (Sfuel > 1)

{
// ...
echo " ";

}
?>
- ,
,
while. , ,
, ,
.

, if, while ,
.

4.29 whi 1,
12.
4.29. while 12

<?php
Scount = 1;
while (Scount <= 12)

{
echo " Scount. 12, " . Scount * 12 . "<b />";
++$count;

}
?>
Scount 1,
whi 1, Scount <= 12.
,
12. :
1,
2,
3.

. .

12. 12
12. 24
12. 36

110

4.

,
Scount, 12. ,

< />, .
, ,
Scount .
Scount , ,
12. , 2,
13.
, , whi 1,
, , .
++$count (
$count++) ,
.
1x12.
,
. 4.30.
4.30. 4.29
<?php
Scount = 0;
while (++$count <= 12)
echo " Scount. 12. " . Scount * 12 . "<br />":

?>

++Scount while
.
Scount () , ,
,
1 12. ,
Scount 0, 1,
, .
, 1, 2 12.

do...while
do... whi 1 whi 1,
, , ,
.
4.31 12,
.
4.31. do...w hile, 12
<?php
Scount = 1;
do
echo " Scount. 12. " . Scount * 12 . "<br />":
while (++$count <= 12);

?>

111

, $count
1 ( 0), ,
1.
4.29.
, do... whi 1 ,
, 4.32.
4.32. 4.31,
<?php
$count = 1;
do {
echo " Scount, 12. " . Scount * 12;
echo "<br />":
} while (++$count <= 12);

?>

for
for, ,
,
,
()
.
4.33
for.
4.33. / 12 for
<?php
for (Scount = 1 ; Scojrt <= 12 ; ++Scount)
echo " $coi>rt. 12, " . Scount * 12 . "<br />";

?>
, for,
. . for
:
;
;
.
: for ( 1 ;
2 ; ).
. Scount
1. (
Scount <= 12), ,
TRUE. ,
.
Scount 1.

4.

112


,
, .
for ,
( 4.34).
4.34. for 4.33

<?php
for (Scount = 1 : Scount <= 12 ; ++$count)

{
echo " Scount, 12, " . Scount * 12;
echo "<br />";

}
?>
, for, ,
whi 1. for
, .
,
, ,
. .
for
:
for (Si = 1. Sj = 1 ; Si + Sj < 10 ; Si++ . Sj++)
{
II

...

}
.
.
.

.
:
Si = 1. Sj = 1
Si + Sj < 10
$i++ , Sj++

// Si Sj
//
// Si Sj

, ,
, (
).
while
for?
. , whi 1
, , -
- , 1 ,
.

113


for ,
switch, break. ,
,
.
,
, , - ( 4.35).

4.35. , for

<?php
$fp = fopen("te x t.tx t".

'wb');

for ($j = 0 ; $j < 100 ; ++$j)

$written = fwrite($fp, "data");


i f (Swritten = FALSE) break;

}
fclose(Sfp):
?>
,
.
, ,
text. txt , $f
,
.
100 ( 0 99),
data . fwrite
Swritten ,
. , fwrite
FALSE.
fwrite Swritten
FALSE, ,
, .

i f (Swritten = FALSE) break;
NOT:
i f ( ! Swritten) break:
, ,
:
i f ( !fwrite(Sfp. "data")) break;
break ,
, , ,

114

4.

, break , ,
, :
break 2;

continue
continue break,

,
.
, ,

.
4.36 conti nue ,
, $j 0.
4.36. continue

<?php
$j = 10;

while ($j > -10)


{
i f ($j == 0) continue:
echo (10 / $j) . "<br />":
}
>
$j 10 -10
0 10 $j.
, $j 0,
continue,
.


,
.

. .
,
. 4.37,
,
.
,
4,66 6 .

115

4.37.

<?php
$ = 56;
$ = 12:

$ = $ / Sb:
echo $;

?>
, $
? ,
$/$
(int):
$ = (int) (Sa / Sb):

.
,
.
$, ,
$
.
,
. 4.6, ,
. ,
intval. ,
, ,
, .
4.6. ,


(int) (integer)
(bool) (boolean)
(float) (double) (real)

|


i

(string)

(array)

1
1

(object)




, - -,
. -
-,
, ,
cookie / , .

116

4.

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

-, cookie (
),
- P H P -,
. ,
.


,
, WordPress (. 4.5).
,
P H P -,
, .
,
,
. , -
WordPress, ,
, ,
.
WordPress,
-, ,
P H P -,
.
,
.
P H P -.
, ,
, .

Jjdit 5fiew Hiftoiy

117

bookmarks

loots t t d p

x <s*

T|

http://myblog.com/blog/wp-admin/edit.php

P | ^

Google

M yBlog |

Visit Sfafe)

Write
Posts

Manage
Pages

Comments

Links

Categories

Tags

Link Categories

Media Library

WordPress 2.6.3 is available! Please notify the site administrator.

Manage Posts
All P o sts
| Delete |

Search Posts

Published (123)

Show dates

Scheduled (I)

View all categories ( Filter |

8 .?<-

ho 7

C.itugories

Next

Status

9 hours from now

Eco peko: Organic


fashion for kids

Robin

Eco-friendly,
Organic, Retailing

Australia,
eko peko

(3

15 hours ago

How ethical is eco


fashion?

Robin

Ethical, Fairtrade

Color,
Colour

2008/ /05

Bamboo: The la test

Robin

Eco-friendly,

Bamboo

__Organic______

9;

Scheduled

Published

Published

. 4.5. WordPress, ,


1. TRUE FALSE?
2. ?
3. , ?
4.
?
5. ?
6. (===)?
7. .
8.
?
9. for , whi 1?
10. _^ ' ,
?
,
4.


,
, ,
. ,
el se el sei f .
,
,

.
. ,
,
- .
, ,
,
.

.
.

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

119


,
.
, . , ,
print:
pri n t("print ");

, .
, ,
:
Notice: Use of undefined constant fname - assumed 'fn am e '

fname, , ,
, . (
, fname
.)
^

, print , 4 , . , :

ib:

v print "print ";


,
( ,
).

, .
, phpi nfo,
:
phpinfoO;
. 5.1.

phpinfo ,
.
, .

5.1 ,
.
5.1.

<?php
echo strrevC' .dlrow o lle H "); //
echo str_repeat("Hip ". 2):
//
echo strtoupperC'hooray!"):
//
//

?>

5.

120


File

\
Edit

http://1ocalhost/info.php
View

Fgvorites

Tools

phpinfoQ

' 1r

ffi

fcielp

System

:.-

1:
L

*'-

11-

"

'

<U .

*
% -

. 5.1. , phpinfo

,
:
Hello world. Hip Hip HOORAY!

, strrev
, str_repeat Hip (
), strtoupper hooray!
.


:
function _{[ [, ... ]])

{
//

}
:
functi on;
,
, ,
;

121

;
,
( ,
).
,
print: PRINT,
P rin tn P rln T .

,
;
, .
return,
.
return - , ,
.


, -
,
.
5.1 P H P - strtoupper.
:
strtolower:
$lowered = strtolow er(" "):
echo $lowered;

, ,
, . (
, -Ann Jo-En-Lai.)
: u c first,
:
Sucfixed = u c fir s t ( " ");
echo Sucfixed;

:
,
s tr to l ower, u cfi rst.
strtolow er ucfi rst.
, ,
.

122

5.

print:
pri nt(5-8):
5-8 -3.
( ,
.) ,
:
pri nt(abs(5-8)):

.
1; 5-8, -3.
2. abs, -3 3.
3. , pri nt.
, ,
, .
:
ucfirst(strtolower( ", "))
strtol ower, ucfi rst,
( ,
):
,

( 5.2),
,
.
5.2. -
<?php
echo fix_names("WILLIAM", "henry", "gatES");
function fix_names($nl, $n2, $n3)
{
$nl = ucfirst(strtolower($nl)):
$n2 = ucfirst(strtolower($n2)):
$n3 = ucfirst(strtolower($n3));
return $nl . " " . $n2 . " " . $n3;
}
?>
Caps Lock,
, , ,
.
:
William Henry Gates

123


, .

.
. 3
, .

5.3.
5.3.

<?php
Snames = fix_names("WILLIAM", "henry", "gatES");
echo $names[0] . " " . $names[l] . " " . $names[2];
function fix_names($nl, $n2, $n3)

{
$nl = u c first(strto lo w e r($ n l));
$n2 = ucfirst(strtolow er($n2)):
$n3 = ucfirst(strtolower($n3));
return array($nl, $n2. $n3);

}
?>
, ,
-, ,
,
.


&, ,
, .
, ,
3.
, , ,
, ,
,

(. 5.2).
, , ,
.
, ,
. ,
.
, 5.3 : ,
(
5.4).

124

5.

. 5.2. ,

5.4.
<?php
$al = "WILLIAM":
$2 = "henry";
$ = "gatES";
echo Sal . " " . $a2 . " " . $a3 . "<br />";
fix_names($al, $a2, $a3);
echo Sal . " " . Sa2 . " " . Sa3;
function fix_names(&$nl, &Sn2, &Sn3)

{
Snl = ucfirst(strtolow er($nl));
Sn2 =.ucfirst(strtolower(Sn2));
Sn3 = ucfirst(strtolower(Sn3));

}
?>

,
. , , ,
&,
.
Snl, $2 $ ,
Sal, $2 $. , ,
, .
f i x_names
Snl, Sn2 $, Sal, $2 $.
:
WILLIAM henry gatES
William Henry Gates

125

, echo
Sal, Sa2 $.

.
, ,
.


, ,
. global
,
( 5.5).

<?php
Sal = "WILLIAM";
Sa2 = "henry";
Sa3 = "gatES";

5.5.

echo Sal . " " . Sa2 . " " . Sa3 . "<br />";
fix_names();
echo Sal . " " . Sa2 . " " . Sa3;
function fix_names()
{
global $al Sal = ucfirst(strtolower($al))
global $a2 Sa2 = ucfirst(strtolower($a2))
global $a3 Sa3 = ucfirst(strtolower($a3))
}
?>
,
.
, .

,
.
.


, 3.
,
. ,
, ,
. . , ,

126

5.


.
.
0 ,
,
.


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

. : i ncl ude () requi re
().

include
include
.
. 5.6 ,
1i brary.php.
5.6.
<?php
include "lib rary.p hp ";
//

?>

indude_once
include
, . , ,
1 ibrary. php . ,
, , , 1ibrary.
php. - 1i brary. php .
,
.
include_once
( 5.7).

127

5.7.
<?php
include_once "lib ra ry.p hp ";
//

?>
, i ncl ude i ncl ude_once,
, , .
, ,
, ,
i ncl ude.

---

----------------------------------------------------------------------------------------------

-, , include_once
4 * include. ,
-* .

require require_once
, include
include once, ,
. ,
.
, ,
require. ,
include_once, ,
, ,
requi re_once ( 5.8).
5.8.
<?php
require_once "lib rary.p hp ";
//

?>


.
- ,
function exists,
.
5.9 array_combine,
5.

128

5.

5.9.
<?php

i f ( f unction_exists( array_combine"))
{
echo " ";

}
else

{
echo " , ";

}
?>
,
, ,
, .
,
.
, ,
phpversion.
:
5.2.8


,

(
GOTO G0SUB), -
( )
.

,
, , .
, .
:
,
.
MySQL,
.
, ,
. User,
, ,
, . ,
,
User.

129


. , ,
, , , ,
.
,
.

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

. 5.3.

130

5.

. ,
.
.
:
.
, ,

, ,
. - ,

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


,
cl ass.
( ), . 5.10
User, : Sname $password (
publ ic .
5 ).
( $object).
5.10.
<?php
Sobject = new User:
print_r($object):
class User

{
public $name, $password;
function save_user()

{
echo " . ":

131

}
}
?>
pri ntjr .

, ( readable,
). Sobject
:
User Object

(
[name] =>
[password] =>

)
,
:
User Object ( [name] => [password] => )

, Sobject
, , name
password.


new,
: % = new .
:
Sobject = new User;
Stemp = new User('name\

password'):

User.
.
; ,
.


5.10 .
5.11
.
5.11.
<?php
Sobject = new User;
print_r(Sobject): echo "<br />" :
$object->name = "Joe";

132

5.

$object->password = "mypass":
print_r($object): echo "<br />":
$object->save_user():
class User
{
public Sname, Spassword;
function save_user()
{
echo " , ":
}
}
?>
,
: %->. : %>{).

,
($). $,
, ,
. , $object->$property ,
Sproperty (,
brown), $object->brown. Sproperty
, $object->NULL,
.
,
, 5.11
:
User Object
(
[name]
[password]
)
User Object
(
[name]
[password]
)

=>
=>

=> Joe
=> mypass
.

pri nt_r,
$object .
print r,
,
, ,
.

133

, save user
, , ,
.
j

^

^
,
, .
-?* .
%


, .
,
, ,
, .
,
.
, 5.12,
User,
name.
?
<?php
$objectl
= new UserO;
$objectl->name = "Alice";
$object2
= $objectl;
$object2->name = "Amy";
echo "objectl name = " . $objectl->name . "<br />";
echo "object2 name = " . Sobject2->name;

5.12.

class User
{
public $name;
}
?>
Sobjectl name Alice.
$object2, $objectl
name $object2 , .
:
objectl name = Amy
object2 name = Amy
? Sobjectl, $object2 ,
name, $object2,
, Sobjectl.
clone,

. 5.13.

134

5.

5.13.
<?php
$objectl
= new UserO;
$objectl->name = "Alice";
$object2
= clone $objectl;
$object2->name = "Amy";
echo "objectl name = " . $objectl->name . "<br>";
echo "object2 name = " . $object2->name;

class User
{
public $name;
}
?>
. , :
objectl name = Alice
object2 name = Amy


. ,
.
,
5.14.
5.14. -

<?php
class User
{
function User($paraml, $param2)
{
//
public Susername = "Guest";
}
}
?>
5.15 , 5
,
__construct ( construct
).
5.15. - 5

<?php
class User
{
function _construct(Sparaml. $param2)

135

{
//
public Jusername = "Guest :

}
}
?>

5
5 -
. ,
. 5.16 ,
-.
5.16. 5 -

<?php
class User

{
function _ de stru ct()

{
//

}
}
?>


, ,
. , , (__),

.
, Sthis,
. ,
, 5.17,
User, get_password.
5.17. Sthis

<?php
class User

{
public Sname. Spassword:
function get_password()

{
return $this->password;

}
}
?>
get_password Sthis
, password,

5.

136

. ,
-> Spassword $.
, ,
.
, 5.17, :
Sobject
= new User
$object->password = "secret"
echo $object->get_password()
secret.

5
5 ,
, .
,
5.18.
5.18.

<?php
User::pwd_string();
class User
{
static function pwd_string()
{
echo ", ":
}
}
?>
,
->
(::), .
, ,
.
5.21 .

$this->property

.


,
.
User 5.19 ,
, .

137

5.19.
<?php
Sobjectl
= new UserO;
$objectl->name = "Alice";
echo $objectl->name;
class User {}

?>

1 i ,
$objectl->name.
,
, name .
, ,
,
. , .
, ,
. ,
.
5.20.
5.20.
<?php
class Test

{
public
public
public
public

Sname
Sage
Stime
Sscore

= "Paul Smith";
=42;
= timeO;
= Sieve! * 2 ;

//

//

// -
// -

}
?>



.
, ( 5.21).
5.21.
<?php
Translate;:lookup();
class Translate

{
const
const
const
const
II

ENGLISH
SPANISH
FRENCH
GERMAN

=
=
=
=

0
1
2
3

...

function lookupO

5.

138

{
echo self::SPANISH:

}
}
?>
, s e lf
. , ,
,
, . , ,
, 1.
, .

5
5
.
publ i ().
var public

.
var public .
var ,
. .
protected ().

.
private ().
,
.
, ,
.
(public) ,

.
(protected) ,
,
.
(private) ,

.
5.22.
5.22.

<?php
class Example

139

{
var Sname
= "Michael": 11 He , public
public Sage = 23;
//
protected Susercount:
//
private function adminO //

{
// admin

}
}
?>


. ,
User ,
.


.
,
. , ,
, ,
User.
.
5.18, , ,

. , ,
,
.
5.23 Test,
.
5.23.
<?php
Stemp
echo
echo
echo

= new TestO;
"Test
A:
"Test
B:
"Test
C:

"
"
"

T e st;:$static_property "<br
/>":
.
Stemp->get_sp()"<br
/>":
.
$temp->static_property"<br

class Test

{
s ta tic $static_property = " ":
function get_sp()

{
}
}
?>

return s e lf::$static_property:

/>";

140

5.

,
:
Test :
Test :
Notice: Undefined property: Test: :$static_property
Test C:
, Sstatic property
, Test .
Test get_sp Stemp,
Test. Test ,
Sstatic_property Stemp.
, get sp
Sstatic property, self.

.

, .
:
, , ,
,
. extends.
5.24 Subscriber User
extends.
5.24.

<?php
Sobject
= new Subscriber;
Sobject->name
= "Fred";
$object->password = "pword";
$object->phone
= "012 345 6789";
Sobject->email
= "fred@bloggs.com";
$object->display();
class User
{
public Sname, Spassword;
function save_user()
{
echo " . ";
}
}
class Subscriber extends User

141

public $phone, Semail;


function
{
echo
echo
echo
echo
}

displayO
"Name:
"Pass:
"Phone:
"Email:

"
"
"
"

. $this->name
"<br />";
. $this->password . "<br />":
. $this->phone
"<br />";
. $this->emai1:

}
?>
User Sname Spassword,
.
Subscriber Sphone
Semai 1 , ,
$thi s.
, .
:
Name:
Pass:
Phone:
Emai1:

Fred
pword
012 345 6789
fred@bloggs.com

parent
,
,
.
.
parent, 5.25.
5.25.

parent

<?php
Sobject = new Son;
$object->test():
$object->test2():
class Dad
{
function testO
{
echo "[Class Dad] < />";
}
}
class Son extends Dad
{
function testO

142
{

5.

echo "[Class Son] < />";

}
function test2()

parent::test();

}
}
?>
Dad (), Son (),
,
test. , test,
. test
, Dad,
parent, test2 Son.
:
[Class Son]
[Class Dad]

,
self:
s e l f : :method ;



, -
. , ,
5.26, .
5.26.

<?php
Sobject = new T ig e r O ;
echo " .. .<br>";
echo ": " . $object->fur . "<br />";
echo ": " . $object->stripes:
class Wildcat

{
public $fur; //
fu n c tio n _constructO

{
}
}

$this->fur = "TRUE":

143

public Sstripes; 11
function__constructO
{
parent::__construct( ); 11
11

$this->stripes = "TRUE":
}
}
?>
.
Wi ldcat ( ) Sfur (),
, Tiger (),
$fur, $stripes ().
, :
...
: TRUE
: TRUE

Final

final. , 5.27.

5.27. final

<?php
class User
{
final function copyrightO
{
echo "
}
}
?>
,
, .
- .
6
.


1. , ?
2. ?
3. ?

144

5.

4. ?
5. ?
6. ?
7. ?
8.
?
9. ?
0. ?
,
5.

3 ,
.
,
, ,
.
,

,
.



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

.


, -
,
. ,
,
.
6.1.

146

6.

6.1.

<?php
$[]
$paper[]
$paper[]
$paper[]

=
=
=
=

"Copier";
"Inkjet";
"Laser";
"Photo";

print_r($paper);
?>
$
,
,
, .
pri nt_r ( ,
) .
:
Array
(
[0]
[1]
[2]
[3]

=>
=>
=>
=>

Copier
Inkjet
Laser
Photo

)
, 6.2,
. , ,
,
. ,
- ,
.
6.2.

<?php
$[0]
$paper[l]
$paper[2]
$paper[3]

=
=
=
=

"Copier";
"Inkjet";
"Laser";
"Photo";

print_r($paper);
?>
, ,
- print r,
6.3 ,
, -.
6.3.

<?php
$paper[] = "Copier";

147

$paper[] = "Inkjet";
$[] = "Laser";
$paper[] = "Photo";
for ($j = 0 ; $j < 4 ; ++$j)
echo "$ j; $paper[$j]<br>";
?>
:
0:
1:
2:
3:

Copier
Inkjet
Laser
Photo

,
, ,
. .


, ,
, . ,
.
.
, .
6.4 ,

.

6.4.

<?php
$paper['copier']
$paper['inkjet']
$paper[laser]
$paper['photo']

=
=
=
=

"Copier & Multipurpose";


"Inkjet Printer";
"Laser Printer";
"Photographic Paper";

echo $paper['laser']:
?>
(
, ) ,
- ,
echo, Laser Pri nter. (copi er, i nkjet . .)
, , (, Laser
Printer) .

X M L HTML. , H TM L-,
, - ,
:

148

6.

Shtm l['title'] = " -";


Shtml[ 'body] = " ... -
,
, .
, ,
, .

,
array
,
.
, , : ,

.
array. 6.5
, ,
.
6.5. array

<?php
$pl = ray("Copier", "Inkjet". "Laser". "Photo");
echo " pi: " . $pl[2] . "<br>";
$p2 = array('copier'
'inkjet'
'laser'
'photo'

=>
=>
=>
=>

"Copier & Multipurpose".


"Inkjet Printer".
"Laser Printer".
"Photographic Paper");
P
echo " p2: " . $p2[' inkjet'] . "<br>";
?>
$1 ,
. ,
0 3. echo :
pi: Laser
$2
.
=> . =>
=, ,
.
, .
echo :
2: Inkjet Printer

foreach...as

149

, $1 $2 , ,
,
(undefined index) (undefined
offset),
:
echo $ p l[ 'in k je t ]; //
echo $2['3 ']:
//

foreach...as
.
,
, ,
foreach. . .as. ,
- .
,
, . 6.6
, foreach
6.3.
6.6. ,
foreach.. .as
<?php
Spaper = array("Copier". "Inkjet", "Laser", "Photo");
$j = 0:
foreach ($paper as Si tern)

echo "$ j: $item<br>";


++$j:

}
?>
PHP foreach,
, as,
foreach
.
$i tern , Spaper.
, .
, 6.3.
, foreach .
6.7 6.5.
6.7. ,
foreach...as

<?php
Spaper = array('copier' => "Copier & Multipurpose".

150

6.

'inkjet' => "Inkjet Printer",


'laser' => "Laser Printer".
'photo' => "Photographic Paper");
foreach (Spaper as Sitem => Sdescription)
echo "Sitem: $description<br>";
?>
, ,
$j .
Spaper ,
Sitem Sdescription, :
copier: Copier & Multipurpose
inkjet: Inkjet Printer
laser: Laser Printer
photo: Photographic Paper
foreach... as
1i st each ( 6.8).
6.8.
each lis t

<?php
Spaper = array( 'copier'
'inkjet'
'laser'
'photo'

=>
=>
=>
=>

"Copier & Multipurpose".


"Inkjet Printer",
"Laser Printer".
"Photographic Paper");

while (list($item. Sdescription) = each(Spaper))


echo "Sitem: Sdescription<br>";
?>
whi 1,
, each FALSE. each
foreach: Spaper ,
,
. , each FALSE.
1i st (
, each),
, .
1i st 6.9,
1i Bob, 1i st,
$ $.
6.9. lis t

<?php
list(Sa, Sb) = array('Alice'. 'Bob');
echo "a=$a b=$b";
?>

151

:
a=Alice b=Bob

, .
foreach.. .as ,
, as,
each .



.
(
).

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

<?php
Sproducts = array(
'paper' =>
array(
'copier' => "Copier & Multipurpose".
'in k je t' => "Inkjet Printer".
'lase r' => "Laser Printer".
photo' => "Photographic Paper").
'pens' => array(
'b a ll'
=> "Ball Point".
' hi 1i t e => "Highlighters".
'marker' => "Markers").
'misc' => array(
'tape'
=> "Sticky Tape".
'glue'
=> "Adhesives".
'c lip s ' => "Paperclips") );
echo "<pre>";
foreach ($products as $section => Si terns)
foreach (Siterns as Skey => Svalue)
echo "$section:\t$key\t(Svalue)<br>";
echo "</pre>";

?>

152

6.

,
. , Spaper
,
Sproducts. : paper, pens
mi sc, ,
.
.
, bal 1
, -.
.

foreach.. .as.
,
.
, (
),
.
echo \t,
.
-, , ,
, <>.. .</>,
-

. , ,
:
paper:
paper:
paper:
paper:
pens:
pens:
pens:
mi sc:
misc:
mi sc:

copier
inkjet
laser
photo
ball
h ilite
marker
tape
glue
clips

(Copier & Multipurpose)


(Inkjet Printer)
(Laser Printer)
(Photographic Paper)
(Ball Point)
(Highlighters)
(Markers)
(Sticky Tape)
(Adhesives)
(Paperclips)

,
:
echo Sproducts['misc ]['glue']:
Adhesi ves.
,
, -
. 6.11
.


<?php
Schessboard = array(
array( ' r ', ' n ', b\ 'k\ 'q'.
array('p '. V - ;p;. 'P '. ;p;.
array( '.
arrayC '.
array(' ',
arrayC ' .
array( ' P' . 'P ' . p\ *P', p1.
array('R . N*, 'B\ 'K ' . Q".

6.11.

153

'b\ ' n' . r ' ) .


;p ;. V . P ).

'p*. p\ 'P').
' *. 'N', R'))

echo "<pre>";
foreach (Schessboard as Srow)
{
foreach (Srow as Spiece)
echo "Spiece ";
echo <br />";
}
echo n</pre>";
?>
,
. : rook (
), n knight (), b bishop (), k kin g (), q queen ()
paw n ().
foreach.. .as.
Srow,
,
Schessboard .
, .
,
(Spi ), (
). ,
. <> </>
:
rnbkqbnr


RNBKQBNR
,
:
echo $chessboard[7][4];

154

6.

Q ,
(
, , ).



1i st each ,
, .
http://tinyurl.com/phparrayfuncs.
, .

is_array
. ,
$f red ,
$f red. ,
, is_array:
echo (is_array($fred)) ? " " : " ";
, $f red ,
Undefined variable.

count
each foreach... as

, ,
, .
:
echo count($fred);
,
, :
echo count($fred. 1);

. ,
,
, .

sort
,
.
:

155

sort($fred):
,
,
. TRUE
FALSE .
. ,
, , :
sort($fred. SORT_NUMERIC);
sort($fred. SORT_STRING);
,
rsort:
rsort($fred, SORT_NUMERIC);
rsort($fred. SORT_STRING);

shuffle
, , ,
:
shuffle(Scards);
sort, shuff1
TRUE
FALSE .

explode
, ,
, ( ),
. 6.12
,
, , .
6.12.

<?php
Stemp = explodeC '. " ");
print_r($temp);
?>
(
):
Array
(
[0] =>
[1] =>
[2] =>

156

6.

[3] =>
[4] =>

)
, ,
. 6.13
.
6.13. , ***,

<?php
Stemp = explode('***'. "*********");
print_r($temp);
?>
6.13 :
Array

(
[0]
[1]
[2]
[3]

=>
=>
=>
=>

extract

. $_GET S P0ST,

, -
, .
GET, $_GET,
POST $_P0ST.
, ,
.

.
:
extract ($_GET);

, , q
Hi there,
$q, .
, -
,
. ,
,
:
extract($_GET. EXTR_PREFIX_ALL. Mtomget');

157


, ,
$q $f romget q.
$_GET $_P0ST ,
, 1
, ,

-.

compact
compact,
extract, .
6.14.
6.14. compact
<?php
$fname
Ssname
Saddress
Scity
Scountry

=
=
=
=
=

"Elizabeth";
"Windsor";
"Buckingham Palace";
"London";
"United Kingdom";

Scontact = compact( 'fname'. 'sname', address , 'c ity ', 'country');


print_r($contact);
?>
6.14
:
Array
(
[fname] => Elizabeth
[sname] => Windsor
[address] => Buckingham Palace
[city] => London
[country] => United Kingdom
)
, compact ,
$.
, compact .
,
, 6.15.
6.15. compact
<?php
$j
=23;
Stemp
= "Hello";
Saddress = "1 Old Street":

6.

158

= 61;

print_r (compact (explode (' ' . ' j temp address age')));


?>
expl ode
, compact, ,
, print r, .
, pri nt_r,
,
.
:
Array
(
[j] => 23
[temp] => Hello
[address] => 1 Old Street
[age] => 61
)

reset
foreach.. .as each
,
, ,
. ,
reset,
, .
:
reset(Sfred);
//
Sitem = reset(Sfred): //
// Sitem

end

, end, ,
,
:
end($fred);
Sitem = end(Sfred);
. ,
, .

.

159


1. ?
2. array?
3. foreach each?
4. ?
5. ?
6. expl ode?
7.
?
,
6.

.

, .
,
,
, -
.
, ,
.
XHTML,
, HTML, (
XML, , RSS).
,
-.

printf
print echo,
.
pri ntf,
. pri ntf ,
,
. ,
%6, 3
:
p rin tf(" % ". 3):
% %, 3 (11).
. 7.1
.

161

printf

7.1. , printf

,
arg

( arg,
123)

% (
)

arg

1111011

ASCII- ,
arg

arg

123

arg

1.23000+2

arg

123.000000

arg

173

arg

123

arg

123

arg

arg
7

pri ntf ,

%.
: . 33 , 21
:
p r in t f(" %s. 2d , % ",
'Simon', 33, 33):

- ,
, , ,),
.

printf HTML, .
, , , :
65 , 127 245 ,
.
:
printf("<font color='#TOX%X >npHBeT</font>". 65. 127. 245):

,
( ' (#),
. %,
. :

162

7.

<font color='#417FF5'></font>

printf
. ,
$r, $ $,
:
printf("<font color='#^X%X^X,>npnBeT</font>". $r-20. $-20. $b-20);


,
. , , ,
.
(, $123,42 12, $10,285).
,
, %
. 2:
^-: $*.2f". 123.42 / 12);

:
: $10.29

,
,
, . 7.1
.
7.1.

<?php
echo "<pre>"; // .
// 15 -
p r in t f( " $%15f\n". 123.42 / 12):
// 15 -
p r in t f(" $ 5 " . 123.42 / 12);
// 15 -
//
pri n t f( " $*15.2f\n". 123.42 / 12);
// 15 -
//
pri n t f( " $015.2f\n". 123.42 / 12);
// # 15 -

pri n tf ( " $r# 15.2f\n". 123.42 / 12);

?>

printf

163

$
10.285000
$00000010.285000
$
10.29
$000000000010.29
$########10.29

,
(. 7.2). .

f, .

, , .
,
, -,
. 15.
-
, .
% 0,
, -.
, .
, - ,
- , ,
: '#.
%,
.
7.2.

%
%
%

15
0

10.285000

15

.4

000000000010.29

15

.2

########10.2850


, ,

. 7.2.
7.2.

<?php
echo "<>": // .

164

7.

$h = House';
p r in t f(
p r in t f(
p rin tf(
prin tf(
p rin tf(

[*s]\n\
[*10s]\n\
C%-10s]\n".
[*010s]\n".
[*'#10s]\n\n"

Sh)
Sh)
Sh)
Sh)
Sh)

/
/
/
/
/
/






'#

Sd = 'Doctor House';
printf("[10.8s]\n",

Sd); //
//
Sd); //
printf("[X -10.6s]\n",
//
p rin tf( " [ - @10.6s]\n". Sd); //
//


8

6
,

?>
, -
H T M L- <>,

\. :
[House]
[
House]
[House
]
[OOOOOHouse]
[#####House]
[ Doctor H]
[Doctor
]
[Doctor@@@@]

-
, ,
, ,
-.
. 7.3 ,
.
7.3.

[House]

10

[House ]

[####Hous]

%
%
%

'#

.4

165

sprintf
,
. spri ntf.
, -
.
spri ntf ,
RGB 65,127,245,
Shexstri ng:
Shexstring = sprintfC'&XTOX", 65, 127, 245);
,
:
$out = sprintf(":
echo $out;

123.42 / 12);



Unix, ,
1 1970 .
time:
echo timeO;
,
,
7 24 60 60
:
echo timeO + 7 * 24 * 60 * 60;
,
mkti me. 946684800
2000 :
echo mktime(0, 0. 0. 1, 1. 2000);
( ):
(0-23);
(0-59);
(0-59);
(1-12);
(1-31);
(1970-2038 1901-2038 5.1.0 + 32-
).

7.

166

, 1970- 2038-? ,
Unix 1970 ,
. , ,
, 5.1.0, , 32-
, 1901 2038 .
, Unix ,
70 , ,
32- ,
19 2038 . ,
Y2K38 ( 2000 , ,
, ).
, .

date,
,
. :
date($format. Stimestamp):
Sformat ,
, . 7.4, $timestamp
Unix.
http://tinyurl.com/phpdatefuncs.
Thursday April 15th, 2010 - 1:38pm:
echo dateC'l F jS. Y - g:ia", timeO):
7.4. , date

01- 31

Sun

j
1

1 31

Sunday Saturday

, ,

1 7

(
j)

st, nd, rd th

, ,

0 6

0 365

01 52

January December

01 12

Jan Dec

1 12

28, 29, 30 31

167

0000 9999

00 99

1 - , 0 -

am pm

AM

, 12-

1 12

, 24-

1 24

, 12-

01 12

, 24-

01 24

00 59

00 59

,
, ,
,
. , date(DATE RSS) ,
RSS-.
.
DATE AT0M Atom. P H P - Y-m-d\TH:i:sP,
2012-08-1612:00:00+0000.
DATE COOKI cookie, - JavaScript.
P H P - 1, d-M-y H:i:s , Thu,
16-Aug-2012 12:00:00 UTC.
DATE RSS RSS. P H P - D, d Y H:i:s ,
Thu, 16 Aug 2012 12:00:00 UTC.
DATE_W3C , World Wide Web
Consortium. P H P - Y-m-d\TH:i:sP,
- 2012-08-1612:00:00+0000.
http://tinyurl.com/phpdates.

checkdate
, ,
, ?
, checkdate, TRUE,
, FALSE .

7.

168

, 30 ,
. 7.3 ,
. .
7.3.
<?php
$month = 9;
$day =31;
$ = 2012;

//
// 31-
// 2012

( 30 )

i f (checkdate(Smonth, $day, Syear)) echo " ";


else echo " ";
?>


MySQL (
) -.
, .
,
, , .
. ,
, ,
, . ,
Windows Mac OS X , Linux
Unix . ,
,
.


,
file exists, TRUE, FALSE
:
i f (fi 1e exists("te s tfile .tx t")) echo " ";


testfi 1 .txt ,
. , 7.4,
testfi 1 . php.
7.4.
<?php // te s tfi1 .php
$fh = f open ("te s tfile .tx t". V ) or die("Co3flaTb ");
$text = < END

169

1
2
3
JND;
fwrite($fh. $text) or d i(" ");
fclo se($ fh );
echo " 'te s tfile .tx t' ";

?>

,
: 'testfile.txt' .
, ,
, ,
.
.
, testfi 1 .txt ,
testfi 1 . php.
, :
1
2
3

.
1. fopen.
2. .
(fwrite),
(fread fgets) .
3. (fcl ose).
, ,
.
, -
. $fh
( ) ,
fopen. ,
, fwrite fcl ose,
$fh, .
Sfh , ,
.
.
fopen FALSE.
:
di ,
.
, -
( - ).

7.

170

, fopen.
w, .
, . :
, w fopen
( !).
. 7.5 ,
.
7.5. , fopen

;
. FALSE,

'+'

;
. FALSE,

;

. ,

'w+'

;

. ,

''

;
. ,

'+'

;
.
,


, ,
, 7.5, fgets ( s
string ).
7.5. fgets

<?php
$fh = fo p e n C te s t file .t x t" . ' ') or
, "):
Sline = fg ets($fh):
fclo se ($ fh ):
echo Sline:

?>
, 7.4,
:
1

171

,
f read, 7.6.
7.6. fread

<?php
$fh = fopen( "te s tfile .tx t". ' r ') or
die("a , "):
Stext = fread(Sfh. 3):
fclose(S fh):
echo Stext;

?>

fread ,
:

fread .
,
.


testfi le .txt, -uneii . 7.7 copyf i 1 . php,
.
7.7.

<?php // cop yfi1 .php


copy( 'te s tfi 1e .t x t . t e s t f ile 2 . t x t ) or d ie (" "):
echo " 't e s t f i le 2 . t x t '":

?>

,
testfi 12.txt. , ,
,
, 7.8.
7.8.

<?php // copyfi12.php
i f ( !copy( ' t e s t f i l e . t x t 't e s t file 2 .t x t ') ) echo " ";
else echo " t e s t f i 12.t x t ;

?>


, 7.9.
7.9.

<?php // movefile.php
i f ( !rename(t e s t file 2 .t x t '.

'te s tfile 2 .n e w '))

7.

172

echo " ";


else echo " 't e s t f i 12.new'";

?>
.
,
f i l e exists.


, 7.10,
uni i nk, .
7.10.
<?php // d e le te fi1e .php
i f ( !u n lin k(t e s t f i 1e2.new )) echo " ";
else echo " 'testfile2.new ' ";

?>

,
. ,
,

.

, ,
, ,
, f i 1e_exi sts
uni i nk.



, .
(. . 7.5) ,
,
, .
,
.
( 7.4 Sfh),
, .
, 7.11, update. php,
, .
7.11.
<?php // update.php
$fh = fopen("testfile.txt", ' r+') or die("Co ");
Stext = fgets($fh);

173

fseek($fh, 0. SEEKJND):
fwrite($fh, "$text") or ' ");
fclose($fh);
echo " 'te s tfile .tx t ";
?>
testfi 1. txt ,
' +',
. fgets,
( ).
f seek, ,
, ( Stext),
. :

1
2
3
1

, .
fseek, $fh,
, 0 SEEK_END. SEEK END
, 0 ,
. 7.11 0,
.
fseek :
SEEK_SET SEEK_CUR. SEEK_SET
, .
18:
fseek($fh, 18. SEEK_SET);
SEEK_CUR ,
.
18,
23:
fseek($fh, 5, SEEK_CUR);
,
( )
.
fseek
, .
. .


-
.

174

7.

, .
, ,
, .

, f 1ock.
,
. ,
,
,
, 7.12, 7.11.

7.12.

<?php
Sfh = fopen(te s tfile .tx t" . ' r+') or die(" "):
Stext = fgets(Sfh):
i f (flock(Sfh, LOCKJX))
{
fseek(Sfh, 0. SEEKJND);
fwrite (Sfh. "Stext") or ' "):
flock(Sfh, LOCKJJN);
}
fclose(Sfh):
echo " 'te s tfile .tx t' ":
?>
-
:
.

. 7.12 f 1ock
fwr i te.
f 1ock L0CK_EX
, Sfh:
flock (Sfh, LOCKJX):

, ,
LOCKJJN:
flock(Sfh, LOCKJJN):
,
. ,
:
.
, ,
i f? , f 1ock -

175

,
, , .
, flock
. ,
, . ,
, flock,
.
- ,
, ,
.

flock NFS
, . flock
ISAPI,
PHP-,
. , flock ,
FAT, Windows.



f i le_get_contents.
, 7.13.
7.13. file_get_contents

<?php
echo <pre>";

// .

echo fi 1e_get_contents("testfi 1e.tx t"):


echo "</pre>": //

?>

.
. 7.14
HTM L - O Reilly ,
-.
, . 7.1.
7.14. - O 'R e illy

<?php
echo f i 1e_get_contents("http ://o re i1l y .com" );

?>

-
- ,
, ,
.
, multipart/form-data,

176

7.

-. , ,
7.15, upload.php.
, ,
.
I

\Q

| httpy'/lolhost/amp!e7-14.php

; : file

yiew

drt
dit

Favorites

lo ok

- f t&

fcjelp

O REILLY

Your Account
.TSj Shopping Cart

Spreading the knowledge o f innovators.

Home

Shop

Radar News & Commentary

Answers

Safari Books Online

Conferences

Training

School of Technology

&

Popular Topics: Programming JavaScript IPhone Android Python HTML5 & CSS Microsoft Java Perl Linux Data

Community

Si

Search

; Search

Buy 2, Get the 3r FREE

All order s over $29.' qualify for FREE SHIPPING within the US

New & Top Python Titles

Shop Our Wide Selection


of Books & Videos

Save 50% - One Week Only


Ruthlessly Efficient. Infinitely Practical.
Python has it all: elegant yet pragmatic, simple yet pow erful,
high-level but it doesn't get bet ween you and your code. It's th t
naturai choice of program m ers w h o put p ro d u c tiv ity first. This
week only save 50% on the top Python titles from O'Reilly.

Programming
Entity FrameworV
DbContext
Ebook -S7.49
(Save 50%)

2 Days Left to Save

^100% . 7.1. - O'Reilly, fiie_get_contents

7.15. , upload.php

<?php // upload.php
echo <_END
<html><head><title>PHP-$opMa cepBep</title></head><body>
<form method^post action= upload.php enctype='multi part/form-data'>
: <input ty p e = 'file ' name='filename' size= 10' />
<input type='submit' value='' />
</form>
_END:
i f ($_FILES)

{
Sname = $_FILES[,filen am e'][,name']:
move_uploaded_fi1e($_FILES[' f i 1ename ] [ 'tmp_name']. $name):
echo " '$name'<br /xim g src='$name' /> :

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

?>

177

.
echo H T M L-, ,
.
, POST,
upload.php (
) - ,
multipart/
form-data.

, .
.
i nput type, f i 1,
name, f i 1ename,
size, ,
.
,
( ,
, Submit Query, ).
.

-, :
,
.
P H P -, ,
,
$_FILES.
, S FILES . i f
($_FILES).

,
, $_FI LES , .
,
$_FI LES.
, , ,
, ,
$name. ,
, .
move_upl oaded_f11, ,
.
,
<IMG>. . 7.2.

move_uploaded_file
Permission denied, ,
, .

178

7.

/) - Mo^ilUi I irefux

x ii

; Q

http7//lQcalhost:/web/upload.php

&

j i^

Q PHP- ... | <

.. 11

'smiley jpg1

. 7.2.

$_FILES
$_FILES ,
. 7.6 ( ,
).
7.6. $_FILES

$_FILES['file]['name']

(, smiley.jpg)

$_FILES[,file'][type']

(, image/jpeg)

$_FILES[,file'] ['size']

$_FILES[,file,][,tmp_name']

$_FILES['filel]['error']

M IM E - (Multipurpose Internet
Mail Extension ).

, ,
(Internet media types). . 7.7
,
$_FILES[ ' f i 1' ] [ 'type '].
7.7. ,

application/pdf

image/gif

multi part/form-data

text/xml

application/zip

image/jpeg

text/css

video/mpeg

audio/mpeg

image/png

text/html

video/mp4

audio/x-wav

image/tiff

text/plain

video/quicktime

179


, ( )
,
.
, ,
, ,
.
upl oad.php upl oad2.
php, 7.16.
7.16. upload.php
<?php // upload2.php
echo <_END
<html><head><title>PHP-(j)opMa cepeep</title></head><body>
<form method='post' action='upload2.php' enctype='multipart/form-data>
JPG. GIF. PNG TIF:

<input type=' f i 1e name=filename size='10' />


<input type='submit1 !='3' /></form>
_END;
i f ($_FILES)

{
Sname = S_FILES['filename']['name'];
swi tch($_FILES[f i 1ename'] [ 'type'])
{
case 'image/jpeg'; $ext = ' jp g ';
case 'image/gif': $ext = 'g i f ';
case 'image/png : $ext = 'png';
case 'im a g e/tiff': $ext = 'ti f ';
default;
$ext = '';
}

break;
break;
break;
break;
break;

i f ($ext)

{
$n = "image.$ext":
move_uploaded_fi1e($_FILES[' f i 1ename'] [ 'tmp_name'], $n):
echo " 'Sname' '$n':<br />";
echo "<img src='Sn />";

}
else echo "'$name' - ";

}
else echo " ";
echo "</body></html>";

?>
, H T M L-, ,
7.15 20 , i f ($_FILES).
, i f
,

180

7.

el se, ,
.
i f Sname ,
( ) ,
, .
swi tch,
,
. $ext
, .
, ,
Sext "".
, $ext ,
$ ,
image , $ext. ,

: image, jpg, image.gif, image.png image.tif.
, P H P -
.
, ,
.

, , , , , , .

i f else,
,
, .

,
.
-
, . ,
,
, ,
, .
,
, - ,
,
(. 17)
Sname:
Sname = ereg_replace("[*A-Za-zO-9.]"f "". Sname):
Sname A-Z, a-z,
0-9 , .

181

,
, ,

:
Sname = strtolower(ereg_replace("[^A-Za-zO-9.]".

Sname));

image/pjpeg,
JPEG-.
image/jpeg:
case 'image/pjpeg':
case 'image/jpeg': $ext = 'jpg'; break;


,
, .
.
,
, 7.17.
Windows Windows- dir.
Linux, Unix Mac OS X
,
1s. ,
exec. php .
7.17.

<?php // exec.php
Scmd = "dir";
// Windows
// Scmd = "Is"; // Linux, Unix & Mac
exec(escapeshellcmd($cmd), Soutput, Sstatus);
i f (Sstatus) echo " exec ";
else
{
echo "<pre>";
foreach(Soutput as Sline) echo "$line\n";
}
?>

( Windows di ):
Volume in drive is HP
Volume Serial Number is E67F-EE11
Directory of C:\web

182

7.

20/01/2011

10:34

20/01/2011

10: 34

19/01/2011
20/01/2011
20/01/2011
19/01/2011
19/01/2011
20/01/2011

16::26
236 maketest.php
10::47
198 exec.php
13.741 smiley.jpg
08::04
54 test.php
18::01
16::59
35 te s tfile .tx t
886 upload.php
09::35
6 File(s)
15.150 bytes
2 Dir(s) 382.907.748.352 bytes free

exec .
1. ( $cmd).
2. , ,
( $output).
3. (
Sstatus).
Soutput Sstatus ,
, ,
, .
escapeshel 1cmd.

, ,
,
.

, -
.

. , ,
, Windows, Linux/Unix,
.

XHTML
X H T M L (extensible Hypertext Markup Language
) ,
. , H TM L- <br>
X H T M L - <br />
?
, , X H T M L
HTML, ,
. HTM L
(), XHTM L,

XHTML

183

, X M L (extensible Markup Language


),
, ,
.

XHTML
X H T M L ,
X M L -. ,
- (
iPhone Blackberry, ,
Android Windows, ),
, ,
, - ,
. , XHTML,
, -
.
, ,
,
- XHTML. ,
HTM L XHTML,
.

XHTML
X H T M L
, ,
, X H T M L 1.0.
X H T M L (, 1.1, 1.2 2.0),
,
-,
, .

XHTML HTML
X H T M L HTM L .
.
, ,
/ >. , , <input type=' subm it>
, Ter<input type=' submit' />. ,
<> </>,
< />.
. <> <i >
</ ></ i > , <>
<i>. <> <i ></i ></b>.

184

7.

.
, <form method=post action=post .php>, <form
method=' post' acti on=' post. php' >. :
<formmethod="post" action="post.php">.
(&) . ,
Batpian & Robin Batman &amp; Robin.
, URL- : H T M L- <
tiref="index.php? page=12&item=15"> < href="index.php?
v page=12&amp;item=15">.
X H T M L ,
. H T M L-, <B0DY><DIV ID="heading">,
: <body><di v id="heading">.
, ,
<option name="bill" selected>,
: <option name="bil1" selected="selected">. ,
checked disabled, checked="checked",
disabled="disabled" . .
X H T M L
X M L -. : <?xml
version=" 1.0" encoding="UTF-8"?>.
DOCTYPE.
<html > xml ns.
, 7.18,
X H T M L 1.0.

7.18. XML

<?xml version*"1.0" encoding="UTF-8"?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml 1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equ i v="Content-Type"
content="text/html; charset=utf-8" />
<1> XHTML 1.0 </title>
</head>
<body>
<> XHTML 1.0 </p>
<hl>3T0 </11>
<> </>
</body>
</html>
, * X M L -,
DOCTYPE <html > xml ns.
HTML, , meta , ,
/>.

XHTML

185

HTML 4.01
,
, D0CTYPE,
. , H TM L 4.01
(Document Type Declarations (DTD)). DTD
7.19 HTM L 4.01.
7.19. DTD HTML 4.01

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">
DTD 7.20
. ( ,
http://w3.org/TR/xhtmll, ,
.)
7.20. DTD HTML 4.01
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/1oose.dtd">

, 7.21 HTML 4.01, .


7.21. DTD HTML 4.01
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
"http://www.w3.org/TR/html4/frameset.dtd">

HTML5
HTML5 ,
:
<!DOCTYPE html>
html , ,
- HTML5. ,
2011
HTML5, ,
, ,

.

XHTML 1.0
, HTML-
. X H T M L 1.0 ,
.
DTD 7.22
.

7.

186

7.22. DTD XHTML 1.0


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtnil 1/DTD/xhtml l-strict.d td ">

DTD X H T M L 1.0, 7.23,


, DTD.
7.23. DTD XHTML 1.0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtmll/DTD/xhtmll-transitional.dtd">

7.24 X H T M L 1.0 DTD,


.
7.24. DTD XHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"

"http:/ /www.w3.org/TR/xhtml1/DTD/xhtml 1-frameset.dtd">

XHTML
XHTM L, W 3C
http://validator.w3.org,
U R L -
-. ,
, , ,
. ,
X H T M L -, . 4
XHTML, ,
, . . 7.3 ,
7.18 X H T M L 1.0.

3 http://validator.w3.org/check7unrhttp%3A%2F1
*
file

dit

iew

Favorites

loots

3 [Valid] Markup Validation .

La

fcjdp

This document was successfully checked as XHTML 1,0 Strict!


Result: i Passed
Address : ;

jhtfcp://validator.w3.org/

Encoding : i utf-8
Doctype : j XHTML 1.0 Strict
Root Element
Root Namespace:

I(detect automaticatly)
|(detect automatically)

html
http://www.w3.orq/1999/xhtml

The W3C validators are hosted on server technology donated by HP, and
supported by community donations.
Donate and help us build better tools for a better web.

^ 100% . 7.3. 7.18,

'

187

, XHTML 1.0 HTML, I , XHTML, . J


, <script>. ilft <script src="script.src" />,
<script src=,,script.src"></script>.


. ,
, X H T M L . .


1. pri ntf
?
2. pri ntf Happy
Bi rthday **?
3.
pri ntf , ?
4. Unix ,
7:11 May 2nd, 2016?
5. fopen,

?
6. P H P - fi 1 . txt?
7. P H P -
?
8.
?
9. P H P - ?
10. X H T M L 1.0: <input type=file
name=file size=10>?
,
7.

MySQL

10 M ySQL ,
,
-. 1990-
, ,
-.
, , ,
. ,
, ,
.
M ySQ L ,
-.
, eW EEK, ,
MySQL Oracle
.

MySQL
,
,
.
MySQL SQL Structured Query Language
. ,
,
, Oracle Microsoft SQL Server.

:
SELECT t i t l e FROM publications WHERE author = 'Charles Dickens':

MySQL ,
, . , ,
. . 8.1 ,
, ,
, .

MySQL

189

8.1.

Author ()

Title ()

Type ()

Year()

Mark Twain
( )

The Adventures of Tom Sawyer


( )

Fiction
()

1876

Jane Austen
( )

Pride and Prejudice


( )

Fiction
()

1811

Charles Darwin
( )

The Origin of Species


( )

Non-Fiction
()

1856

Charles Dickens
( )

The Old Curiosity Shop


( )

Fiction
()

1841

William Shakespeare
( )

Romeo and Juliet


( )

Play
()

1594

MySQL,
MySQL.
,
publications ().
, ,
, , classics.

,

, ,
:
MySQL;
,
;
, ;
.
, ,
,
, ,
.

MySQL
M ySQ L :
, - phpMyAdmin
, .
10, .

8. MySQL

190



Windows, Mac OS X Linux.

Windows
, 2,
Zend Server WAMP, M vSQL
( 32-, 64- ):
:\Program F i 1es\Zend\MySQL51\bin
C:\Program F ile s (x86)\Zend\MySQL51\bin
fit

**--1

Zend Server \Program Files ( \Program Files (86)),

4 , .
M ySQ L root ,
. , ,
,
.
MySQL,
CMD,
Enter. Windows.
, (
):
"C:\Program Files\Zend\MySQL51\bin\mysql" -u root
"C:\Program F ile s (x86)\Zend\MySQL51\bin\mysql" - root

tit

1 --------------------------------------------- :---------------

#%
, .
, ---- , ,
Command.

MySQL root
. M ySQL
. , ,
,
. 8.1:
SHOW databases;


, , M ySQL
Zend Server ( 2). ,
.

MySQL

191

Hi & '

| C:\Windows\system32\cmd.exe
M ic r o s o f t H in d us f U e r s i o i f . i. 1
Copjst4
\ > Mi Co i-po svvf:io n .

f i l l r:i<< >t: n r e s e r v e d .

: \Us t v? \ in > Pro ra n F i 1e:; \ll-xv yp! *F 2 .


I .hin'Mnysql'' u r o o t
We i t. r> t he 1 QI- no n i t <}r .
Conrw '<ds n d u i t h j o r \ c f .
Vow fly&QL connect: :ion i d : 16 to scj yer o e m io n : j . 0 . 2 ? ~ mnun i t ~lo g
1

f be i n : '* v * \h '

f o r h e lp .

:
1 c ts v;

!
!

j.n s e t

\o J tn

c le a r

:ht: b u F F e r.

<;0 >

nysfj]./ ^

. 8.1. MySQL Windows

Mac OS X
, ,
, 2, Zend
Server . -
MySQL.
M ySQL
Terminal ( Utilities Finder).
MySQL, /usr/local/zend/
mysql/bin.

M ySQL
root, root.
:
/usr/loca-1/zend/mysql/bin/mysql -u root

M ySQL root
. , ,
( . 8.2):
SHOW databases;

,
MySQL (Can't connect to local MySQL server through socket), ,
MySQL. ,
2, MySQL OS X.

.

Linux
, U nix-
, Linux, M vSQ L

192

8. MySQL

,
. M ySQL,
:
mysql -u root -

iMac:zend robin$ show databases;


-bash: show: command not found
iMac:zend robin$ /usr/local/zend/mysql/bin/mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.54 MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type help;' or '\h for help. Type 4 c to clear the current input statement.
mysql> show databases;
| Oatabase

| information_schema |
I nysql
j
I test
|
3 rows in set (0.00 sec)
mysql> |

. 8.2. MySQL Terminal OS X

M ySQL root
. , ,
Enter.
,
,
. 8.3:
SHOW databases:

- ,
2 LAM P Linux,
MySQL.
,
.

MySQL
M ySQL
Telnet (
SSH), , ,
Linux/FreeBSD/Unix.

, ,
, .

MySQL

193

MySQL ,
. , ,
username :
mysql -u username -

. 8.3. MySQL Linux

.
,
. 8.3:
SHOW databases;

pi ,
test .
,
,
. , ,
,
, .

, .


. .


, , ,
Windows, Mac OS X Linux

194

8. MySQL

MySQL, ( ,
) .


. , , ,
(;) SHOWdatabases;? MySQL
. , MySQL
.
, ,
. ,
. Enter
.
at -
4

MySQL.
, , .
, Enter, .

MySQL (. 8.2),
,
.
8.2. MySQL

MySQL

mysql >

MySQL

->

'>

">

'>

,
(')

/*>

,
/*


, , , ,
Ctr+C! .
\ Enter.
8.1.
8.1.
mysql \
M ySQL
. \ .
: -

MySQL

195

, , \, ,
MySQL \ . 8.2 ,
\.
8.2.
" mysql " \

, \
, .

MySQL
SHOW,
, . . 8.3
.
8.3. MySQL

()

ALTER

BACKUP

\
CREATE

DELETE

DESCRIBE

DROP

EXIT (Ctrl+C)
GRANT

HELP (\h, \?)

INSERT

LOCK

()

()
, EXIT

QUIT (\q)
RENAME

SHOW

SOURCE

STATUS (\s)
TRUNCATE

UNLOCK

()

()

UPDATE

USE

,
, MySQL.

196

8. MySQL

SQL .
CREATE, create . ,
,
.
Windows,
Linux Mac OS X.
.

.


,
,
. ,
,
publications :
CREATE DATABASE publications;
,
, Query OK, 1 row affected (0.38 sec) (
, 1 0,38 ), .
,
:
USE publications:

(Database changed),
.


, , MySQL,
, ,
, , ,
P H P - (root)
MySQL, , -
-.

GRANT, ( ,
):
GRANT ON _. _@_'
IDENTIFIED BY 11:
- , ,
..
, (. 8.4).

MySQL

197

8.4. GRANT

**

_*

_.

, ,
, (
jim mypasswd ):

publications

GRANT ALL ON publications.* TO 'jim '@1ocalhost'


IDENTIFIED BY 'mypasswd':
jim@l ocal host
publications mypasswd.
, QUIT ,
M ySQL, ,
-u root - - jim -
. . 8.5 ,
, , Zend Server
( 2), M ySQ L-
, .
8.5. MySQL jim(3>localhost

32-
Windows

"C:\Program Files\Zend\MySQL51\bin\mysql" -u jim -p

64-
Windows

"C:\Program Files (x86)


\Zend\MySQL51\bin\mysql" -u jim -p

Mac OS X

/usr/local/zend/mysql/bin/mysql -u jim -p

Linux

mysql -u jim -p

, , ,
. ,
- ( ).
. , ,
,
..
, ,
GRANT. ,
. , ,
, , , , REVOKE,
: http://tinyurl.com/mysqlgrant.
, ,
IDENTIFIED BY, , -
, .

8. MySQL

198


MySQL, (ALL)
, publications ( ,
), .
,
( publications , ):
USE publications:

, 8.3.
8.3. classics
CREATE TABLE cla ssics (
author VARCHAR(128),
t i t l e VARCHAR(128),
type VARCHAR(16).
year CHAR(4)) ENGINE MyISAM;

---

--------------------------------------------------------------------------------------------- :

CREATE TABLE classics (author VARCHAR(128). title


b'

VARCHAR(128). type VARCHARC16). year CHAR(4)) ENGINE MyISAM;

MySQL ,
, .

M ySQL : Query . rows affected,


, .
, .
, , -
. ENGINE MyI SAM,
, M ySQL
, .
, :
DESCRIBE classics;

, ,
8.4,
.
8.4. MySQL:
mysql> USE publications;
Database changed
mysql> CREATE TABLE classics (
-> author VARCHAR(128).
-> t i t l e VARCHAR(128),
-> type VARCHAR(16).
-> year CHAR(4)) ENGINE MyISAM:
Query OK, 0 rows affected (0.03 sec)
mysql> DESCRIBE classics;

MySQL

199

---- _+ __ ---- .+---- .+--- +-------+----Field |


| Null | Key | Default | Extra
__+---------- _+_ _ _+
h------ +
author | varchar(128) | YES |
| NULL
|
t it le j varchar(128) j YES j
j NULL
|
type
j varchar(16) | YES j
| NULL
|
year
j char(4)
j YES |
| NULL
|
--------- +----------------+....... +-------+---4 rows in set (0.00 sec)
DESCRIBE , -.
MySQL.
,
. :
Field ;
, ;
Nul 1 , NULL;
Key M ySQL , ,
. Key
( );
Default , ,
;
Extra ,
.


8.3 ,
VARCHAR, CHAR. VARCHAR VARiable
length R acter string ,
, M ySQL ,
, .
, MySQL
.
: ,
, .
year () , VARCHAR
CHAR(4). 4
4 , -999 9999.
, , , ,

- ,
,
2000 - 1 2000
1900 .

200

8. MySQL

YEAR classics ,
0000 1901- 2155-. MySQL
1 , ,
256 , classics
.

, CHAR, VARCHAR, ,
. ,
CHAR . ,
. VARCHAR ;
,
. VARCHAR ,
. CHAR
, , a VARCHAR
,
. ,
VARCHAR , CHAR.

CHAR
. 8.6 CHAR.
, ( ) ,
. ,
. VARCHAR
255 1 , 256
2 .
8.6. CHAR, MySQL

CHAR(n)


(< 255)

CHAR(5) Hello 5
CHAR(57) New York 57

VARCHAR(n)

VARCHAR(IOO) Greetings 9
1
VARCHAR(7) Morning 7
1

(< 65 535)

BINARY
BINARY , ,
(. 8.7). ,
BINARY GIF.
8.7. BINARY, MySQL

BINARY(n)
BYTE(n)


(< 255)

CHAR,

VARBINARY(n)

(< 65 535)

VARCHAR,

201

MySQL

TEXT VARCHAR
TEXT VARCHAR .
5.0.3 M ySQL VARCHAR
, 256 .
TEXT .
TEXT MySQL (
).
, VARCHAR
, .

, , ,
TEXT (. 8.8).
8.8. TEXT, MySQL

TINYTEXT(n)

(< 255)

()

(< 65 535)

MEDIUMTEXT(n)

(< 16 777 215)

LONGTEXT(n)

(< 4 294 967 295)

BLOB
Binary Large Object ,
, , BLOB
, 65 536 .
BLOB BINARY , BLOB
(. 8.9).
8.9. BLOB, MySQL

TINYBLOB(n)

(< 255)

BLOB(n)

(< 65 535)

MEDIUMBLOB(n)

(< 16 777 215)

LONGBLOB(n)

(< 4 294 967 295) ,



MySQL ,
.
8 ,
, .
.

202

8. MySQL

. 8.10 , MySQL,
, .
, ,
.-: ,
.
, : ::
, , :
. , (
) .
8.10. , 5> =


( / )


( / )

TINYINT

-128

12 "

SMALLINT

-32 768

32 757

MEDIUMINT

-8 388 608
0

5 3SS 507
7 215

INT INTEGER

-2 147 483 648


0

2 1 * "48 3647
* 29* 967 295

BIGINT

-9 223 372 036 854 ^ 5


0

Z23 372 036 854 775 807


15^ 467 440 737 09 551 615

FLOAT

-3,402823466+38
( -'

3 ^2823466+38
)

DOUBLE REAL

-1,797693134862315^306
( ^

1.7976931348623157+308
)

, .
, UNSIGNED.
tablename, fie 'c ^ - e UNSIGNED INTEGER:
CREATE TABLE tablename (fieldname INT UNSI

>^
:
CREATE TABLE tablename (fieldname INT(4:

, BINARY CHAR
. : . ,
,
.
ZERC-FI_:
CREATE TABLE tablename (fieldname INT'-

I*^I__

.
,

MySQL

203

.
, .

DATE TIME
. 8.11 ,
MySQL, .
8.11. DATE TIME, MySQL

DATETIME

'0000-00-00

DATE

'0000-00-00'

TIMESTAMP

'0000-00-00 00:00:00'

00:00:00'

TIME

'00:00:00'

YEAR

0000 ( 0000 1901-2155)

, DATETIME TIMESTAMP,
. , TIMESTAMP ( 1970
2037 ), DATETIME ,
.
TIMESTAMP , , , MySQL
.
,
. MySQL
TIMESTAMP .

AUTO.INCREMENT
,
.

.
. ,
. , ,
. .
.

.
ISBN (International Standard Book Number
) classics,
AUT0_
INCREMENT.

, ,
,
. 8.5
, id classics
.

204

8. MySQL

8.5. id
ALTER TABLE classics ADD id INT UNSIGNED NOT NULL AUTOJNCREMENT KEY;

ALTER, CREATE.
ALTER ,

. id,
:
I NT UNSIGNED ,
, 4 ;
NOT NULL .
NULL,
- . ,
.
NULL ;
AUTO_INCREMENT M ySQL
, .
, ,
: , ,
;
KEY ,
.
.
id,
1,
. , id
.
,
, CREATE.
8.3 8.6.
.
8.6. id
CREATE TABLE classics (
author VARCHAR(128).
t i t l e VARCHAR(128).
type VARCHAR(16),
year CHAR(4),
id INT UNSIGNED NOT NULL AUTOJNCREMENT KEY) ENGINE MyI SAM:

, ,
, :
DESCRIBE classics:

, , i d
, , , 8.5,
, 8.7.

MySQL

205

8.7. id
ALTER TABLE classics DROP id:


INSERT.
, classics 8.1,
INSERT ( 8.8).
8.8. c l ass i c s
INSERT INTO classi cs(author. t itle , type, year)
VALUES('Mark Twain'.The Adventures of Tom S a w y e r F i c t i o n 1876');
INSERT INTO classics(author. t itle , type, year)
VALUES('Jane Austen'. 'Pride and Prejudice'. ' F ictio n '.'1811');
INSERT INTO classics(author. t itle , type, year)
VALUES( 'Charles Darwin' , 'The Origin of Species' . ' Non-Fiction'.'1856');
INSERT INTO classics(author, t itle , type, year)
VALUES('Charles Dickens' . 'The Old Curiosity Shop', 'F ic tio n '. '184);
INSERT INTO classics(author, t itle , type, year)
VALUES('William Shakespeare'. ' Romeo and J u lie t ', 'P lay','1594');

Query . ,
, :
SELECT * FROM classics;
, . 8.4.

. 8.4. classics

SELECT,
MySQL . ,
.

206

8. MySQL

, INSERT.
, INSERT INTO classics, MySQL,
. : author,
t it le , type year, .
M ySQL , .
INSERT VALUES,
,
. M ySQL ,
. (
,
, .)

. ,
.
.


,
, ALTER. , , ,
classics 1900. :
ALTER TABLE classics RENAME prel900:
, ,
, ,
:
ALTER TABLE prel900 RENAME classics:


ALTER,
MODIFY.
year CHAR(4) SMALLI NT (
2 , ),
:
ALTER TABLE classics MODIFY year SMALLINT;
, M ySQL ,
, .
,
.


,
, . . ,
pages,
, :
ALTER TABLE classics ADD pages SMALLINT UNSIGNED:

MySQL

207

pages, ,
UNSIGNEDSMALLINT, 65 535.
- !
M vSQL ,
DESCRIBE,
(. 8.5):
DESCRIBE classics:

. 8.5. pages


. 8.5, , type
, M ySQL
.
category:
ALTER TABLE classics CHANGE type category VARCHAR(16);
VARCHAR( 16) .
, CHANGE
, , VARCHAR( 16)
, type.


, , pages,
, ,
, DROP:
ALTER TABLE classics DROP pages:

, DROP ,

( )!

8. MySQL

208


.
cl assi cs, .
, ,
, , 8.9.
. 8.6.
8.9. ,

CREATE TABLE disposable(trash INT);


DESCRIBE disposable:
DROP TABLE disposable:
SHOW tables:

rai C:\Windows\system32\cmd.exe

11 1i ^

. 8.6. ,

cl assies,
, MySQL, .
, .

, MySQL
. ,
.
, ,
, , ,
. MySQL,

, MySQL
.

209



, . -
. , , , INDEX, PRIMARY
KEY FULLTEXT. , , ,
,
. ,
. ,

.
classics,
, .
pages, ,
, , ,
.
, ,
8.10.
8.10. classics
ALTER TABLE classics ADD INDEXCauthor(20));
ALTER TABLE classics ADD INDEX(title(20)):
ALTER TABLE classics ADD INDEX(category(4));
ALTER TABLE classics ADD INDEX(year);
DESCRIBE classics;

author
title , .
, M ySQL :
The Adventures of Tom Sawyer
20 :
The Adventures of

. 20 ,
,
. M ySQL ,

, ,
.
category, ,
, (F
Fiction, N Non-Fiction Play), ,
,
. (
, .)

210

8. MySQL

, year,
, .
( DESCRIBE, ,
) . 8.7,
MUL . ,
, , , ,
,
. .

. 8.7. classics

CREATE INDEX
ALTERTABLE, CREATE INDEX.
, , CREATE INDEX
PRIMARY
KEY (. ).
8.11.
8.11.
ALTER TABLE classics ADD INDEX(author(20)):
CREATE INDEX author ON classics (author(20));


, - . ,
. ,
classics .
8.12 8.3,
. , ,
, category
type, year SMALLINT,

211

CHAR(4).
cl assi cs cl assi cs , c la s s ic s l,
c la s sics l.
8.12. classics

CREATE TABLE classics (


author VARCHARQ28).
t i t l e VARCHAR(128).
category VARCHAR(16).
year SMALL INT,
INDEX(author(20)).
INDEX(ti t le ( 20)).
INDEX(category(4)),
INDEX(year)) ENGINE MylSAM;


c la s sics
, - .
,
, .
( )
, (.
:
9).
A U TO _IN CREM EN T
,
id , ,
.
: ISBN.

. , , ISBN 13 , ,
:
ALTER TABLE classics ADD isbn CHARC13) PRIMARY KEY:

. ,
, 1: Duplicate
entry. , ,
NULL , ,
, ,
. ,
,
.
:
, , 8.13.
, ,

212

8. MySQL

year. , UPDATE WHERE,



MySQL .
8.13. isbn
ALTER TABLE classics ADD isbn CHAR(13);
UPDATE classics
SETisbn= 9781598184891' WHERE year='1876':
UPDATE classics
SETisbn= 9780582506206* WHERE year='1811 ;
UPDATE classics
SETisbn='9780517123201' WHERE year='1856 ;
UPDATE classics
SETisbn= 9780099533474' WHERE year=,1841, :
UPDATE classics
SETisbn=19780192814968 WHERE year= 1594, ;
ALTER TABLE classics ADD PRIMARY KEY(isbn);
DESCRIBE classics;

, ,
. 8.8. , ALTER
TABLE INDEX PRIMARY KEY (
8.10 8.13).

. 8.8. classics

^ cl assi cs,
, 8.14. ,
, classics 1 , .
8.14. classics
CREATE TABLE classics (
author VARCHAR(128),
t i t l e VARCHAR(128).
category VARCHAR(16).
year SMALLINT,
isbn CHAR(13).

213

INDEX(author(20)).
INDEX(ti tle ( 20)),
INDEX(category(4)).
INDEX(year).
PRIMARY KEY (isbn)) ENGINE MyISAM;

FULLTEXT
, MySQL FULLTEXT

, ,
, .

**

------------------------------------------------------------

- , MySQL FULLTEXT,
? d * ,
---- 500 ,
. ,
stopwords, the, as, is, of . . MySQL
FULLTEXT- .
.

FULLTEXT,
.
FULLTEXT MyISAM,
( ) M ySQL (M ySQL
).
MyISAM, MySQL:
ALTER TABLE tablename ENGINE = MyISAM;
FULLTEXT CHAR,
VARCHAR TEXT.
FULLTEXT CREATE TABLE
ALTER
TABLE ( CREATE INDEX).
,
FULLTEXT, , ,
FULLTEXT.
FULLTEXT, ,
8.15, FULLTEXT author
title , cl assi cs ( ,
, ).
8.15. FULLTEXT classics

ALTER TABLE classics ADD FULLTEXT(author.title);



FULLTEXT. ,

214

8. MySQL

(,
), .
FULLTEXT
MATCH...AGAINST MySQL.

---

----------------------------------------------------------------------------------------------

MySQL ,
, .
-**? , , .
.
, 9 , ,
.
4

MySQL
, MySQL ,
, . ,
.

SELECT
. 8.4 , SELECT
.
, - ,
,
.
SELECT .
:
SELECT - FROM _;

-, , (*),
, -
. 8.16 , (author
t i t l ) ISBN.
. 8.9.
8.16. SELECT
SELECT author,title FROM classics;
SELECT title .isb n FROM classics:

SELECT COUNT
- COUNT,
. 8.17

(*), .
5, .
8.17.
SELECT COUNT(*) FROM classics:

215

j C:\Windows4v>ystem32\crrid.exe

I*=>
' claries;
*i
i 1;

1i,e

't u r e 'j o f Tors


^.rid P r e ju d ic e
f pe i s

Ui
--; in

d C u r i o s i t y
.Rene and J y J i e t

Sh \

: F80M c Ia s s

. 8.9. , SELECT

SELECT DISTINCT
( DISTINCTROW)
, . , ,
, .
author , ,
,
. DISTINCT
. ,
,
( 8.18).
8.18.
INSERT INTO classics-:author, title , category, year, isbn)
VALUESC'Charles Dickens . Little D o rrit'. 'F ic tio n '. '1 8 5 7 ' . '9780141439969');
, ,
SELECT DISTINCT .
8.19 . 8.10 , SELECT
, DISTINCT
.
8.19. SELECT DISTINCT
SELECT author FROM classics:
SELECT DISTINCT author FROM classics:

DELETE
, DELETE.
SELECT,

, WHERE LIMIT.

216

8. MySQL

. 8.10. DISTINCT

, , 8.18,
DISTINCT, L it t le D orrit ,
8.20.
8.20.
DELETE FROM classics WHERE t it le = L it t le D orrit';

DELETE , t i t l
Li t t l Dorri t.
WHERE , ,
.
( , WHERE
).
, SQL.

WHERE

WHERE ,
,
. = 8.20
, t i t l e
L it t le Dorrit. 8.21 ,
WHERE =.
8.21. WHERE
SELECT a u th o r.title FROM classics WHERE author="Mark Twain";
SELECT a u th o r,title FROM classics WHERE isbn="9781598184891 ";


.
, , -

217

, ( ,
, ISBN ) The Adventures of Tom Sawyer.
, , ,
, ,
.

, LIKE,
.
% . ,
- , - .
8.22 ,
, , .
. 8.11.
8.22. LIKE

SELECT a u th o r.title FROM classics WHEREauthor LIKE "Charles^";


SELECT a u th o r.title FROM classics WHERE t i t l e LIKE
"^Species";
SELECT a u th o r.title FROM classics WHERE t i t l e LIKE
"XandX :

. 8.11. WHERE LIKE

, ,
, LIKE
Charles, .
The Origin of Species,
, Species.
Pri de and Prejudi ce
Romeo and Jul iet,
and .
% ,
. , .

218

8. MySQL

LIMIT
LIMIT
, . ,
MySQL
, .
,
, M ySQL ,
, . ,
: , .
8.23 .
. , 1 (
). , 3 (
).
. 8.12.
8.23.

SELECT a u th o r.title
SELECT a u th o r.title
SELECT a u th o r.title

FROM classics
FROM classics
FROM classics

LIMIT
LIMIT
LIMIT

3:
1.2;
3.1:

. 8.12. LIMIT

UMIT ,
, . LIMIT 1,3
, .

MATCH...AGAINST
MATCH.. .AGAINST ,
FULLTEXT (. FULLTEXT).
, ,

219

, . .
*HERE. . .= WHERE.. .LIKE, MATCH...
AGAINST
, FULLTEXT. FULLTEXT
, ,
.
, FULLTEXT author t i t l e
, 8.24.
, and. and
. MySQL ,
, .
, : ol d shop.
tom sawyer.
. 8.13.
8.24. /

SELECT
WHERE
SELECT
WHERE
SELECT
WHERE

~= MATCH... AGAINST FULLTEXT

a u th c 'W '/ e r R0M classics


M A T C H . t i t l e ) AGAINST( 'and'):
a u tn c 'W - 'e "ROM classics
MATCH, s .: . v tie ) AGAINSTCold shop'):
a u tr : - .v " 'e r R0M classics
MATCr =.:r : r . : 't le ) AGAINSTCtom sawyer'):

. 8.13. /- MATCH...AGAINST FULLTEXT

MATCH...AGAINST...IN BOOLEAN MODE


., MATCH... AGAINST,
, .
. FULLTEXT
, .
,
.

220

8. MySQL

+
, .
,
, ,
. , ,
, .
8.25 , .
, charl es
species. ,
, o rig in of. . 8.14
.
8.25. MATCH.. .AGAINST.. . IN BOOLEAN MODE

SELECT a u th o r.title FROM classics


WHERE MATCH(author.title)
AGAINST(+charles -species' IN BOOLEAN MODE);
SELECT a u th o r,title FROM classics
WHERE MATCH(author.title)
AGAINST(' "origin o f " IN BOOLEAN MODE):

. 8.14. MATCH...AGAINST... IN BOOLEAN MODE

, , , The Old
Curiosity Shop . ,
,
species.
.

____ 4*4

- :
of, ,
.

221

UPDATE...SET
: .
:~: > : ,
, ,
-: , SELECT.
8.26 UPDATE.. .SET.
. 8.15.
8.2.

/:~: UPDAIE...SET

UPDATE5s' : SET author='Mark Twain (Samuel Langhorne Clemens)'


WHERE
w5rk Twain';
UPDATE
: SET category='Classic Fiction'
WHERE C5ie;:\= r "lotion';
jgg CAWinooec jsa-fr32\crr>d.exe

Pmc. 8.1 5 . classics

-_ v . , ! . ''' Twain Samuel


_ =-:
*: - .
, :*::.Tri-.- : Fiction category
31 I 7 1 C
>
, LIMIT,
1-11= GROUP BY.

ORDER BY
ORZl2 z
51 .
8.27 ,
. 8.16.

222

8. MySQL

8.27. ORDER BY
SELECT a u th o r.title FROM classics ORDER BY author;
SELECT a u th o r.title FROM classics ORDER BY t i t l e DESC;

. 8.16.

,
( ),
.
,
( ),
:
SELECT au th or.title.year FROM cla ssics ORDER BY author.year DESC:

,
DESC
, , year. author
, ,
.
,
:
SELECT au th or.title.year FROM classics ORDER BY author ASC.year DESC;

GROUP BY
, ORDER BY, ,
, GROUP BY,
. ,
, class'cs,

SELECT category.COUNT(author) FROM classics GROUP BY category:

223

:
. + ------------

category

| C0UNT(author)
- + --------------------------

Classic Fiction 1
Non-Fiction
1
Play
1
.+

1
1

------------------

3 rows in set (0.00 sec)


,
, . , ,
customers,
cl ass i cs.

, 8.28. . 8.17.
8.28. customers
CREATE TABLE customers (
name VARCHAR(128),
isbn VARCHAR(128).
PRIMARY KEY (isbn)) ENGINE MyISAM:
INSERT INTO customers(name.isbn)
VALUESCJoe Bloggs . '9780099533474 ):
INSERT INTO customers(name.isbn)
VALUESCMary Smith', '9780582506206'):
INSERT INTO customers (name, isbn.)
VALUESCJack W ilson'. '9780517123201'):
SELECT * FROM customers;
j Eg C:\Windows\system32\cmd.exe

si
1
1
IH
1
R

^ ]

1> GREAT TABLE c u s to n e r s <


~> nane UftftCHft IK 12 >
->
b h n < i 28 > .
- > PHI KEY
Qu e
O K 0 ;;- a f fe e t: A < -02 ">
IHSEKT 1HTO
r Mi.'n
- > UALU ES < J J e 1 s<4
' *Vb Utf * ; '>4 ? '! J>;
Q uery OK, 1 r'c.v a .fr e c o r d
s
t'i'jt-.q .1> INSERT i
' ,i i t
-> UftLUESi < ' Mar v So ti n , J
Q uery OK 1 pow a f f e c t e
:;<rc /

u J if , > ;

rVsql> INSERT INTO c u s t o r u ^ s < . 1.>


-> U ALU ES<'Jack i. is p. , 9?80572:2 ' > ;
Q uery OK, 1 row afee?;eJ. O ..0 8 see >

n<?.ne

1 is-hrt

i Jo
;
<;n,i.r.h
i J a c k U ils o n

j v ? 8 009 v b 33474
1 9?a058250b28S
; 9780 7123201

;
;
i

. 8.17. customers

224

^
fS x

' _U

8. MySQL

, 8.28, INSERT INTO ,


, :
INSERT INTO customers(name.isbn) VALUES
C J o e B l o g g s V 9780099533474').
(Mary Smith','9780582506206').
('Jack Wilson'.'9780517123201'):

, , ,
, , . .,
.
,
- classics: isbn.
(ISBN
),
, 8.29.
8.29.

SELECT

SELECT name.author,title from customers.classics


WHERE customers.isbn=classi cs. i sbn:
:
name

-+------------| author
| t it le

Joe Bloggs | Charles Dickens | The Old Curiosity Shop


Mary Smith
Jane Austen
j Pride and Prejudice
Jack Wilson | Charles Darwin j The Origin of Species
_ _ --- +----- ---.+-- ----------- _ _
+
3 rows in set (0.00 sec)

, ,
classics,
customers?

NATURAL JOIN
NATURAL JOIN,
. ,
.
, 8.29, :
SELECT name.author.title FROM customers NATURAL JOIN classics:

JOIN...ON
, ,
JOIN.. .ON,
, 8.29:

225

SELECT name.author.title FROM customers


JOIN classics ON customers.isbn=classics.isbn;

AS

AS.
AS, .
, 8.29:
SELECT name.author.title from
customers AS cust. classics AS class WHERE cust.isbn=class.isbn;
:

+---------------+---------------------- +------------------------------+
| name

| author

|t it le

+---------------+---------------------- +------------------------------+
| Joe Bloggs| Charles Dickens |The Old Curiosity Shop |
j Mary Smith | Jane Austen
j Pride and Prejudice
j
j Jack Wilson j
Charles Darwinj The Origin of Speciesj

+---------------+---------------------- +------------------------------+
3 rows in set (0.00 sec)

,
.


MySQL,
WHERE, AND, OR NOT.
8.30 ,
.
8.30.

SELECT author.title FROM classics WHERE


author LIKE "Charlesr AND author LIKE "fcDarwin";
SELECT author.title FROM classics WHERE
author LIKE " Twainfc" OR author LIKE "^Samuel Langhorne Clemens^":
SELECT author,title FROM classics WHERE
author LIKE "Charles^" AND author NOT LIKE "^Darwin":
,
.
, author
Charles Darwin. ,
, Mark Twain,
Samuel Langhorne Cl emens.
, Charles, Darwin.

226

8. MySQL

MySQL
M ySQL
. :
MySQL .
MySQL,
, .
M ySQL
, .

URL-:
: http://tinyurl.com/mysqlstrfuncs:
: http://tinyurl.com/mysqkJatsfjncs.

.

MySQL phpMyAdmin
MySQL, ,
, , ,

phpMyAdmin.
,
, publications
cl assi cs customers ,
.

Windows
,
, Zend Server . ,
M ySQL :
http://1ocalhost/phpMyAdmi n
, . 8.18,
zend ( )
. , . 8.19.
phpMyAdmin.

Mac OS X
, Zend Server
Apache MySQL, :
http://1ocalhost:10081/phpmyadmi /

227

MySQL phpMyAdmin

# 1 http://localhost P - <SX
:

File

Edit

View

Fgvorites

Tools

. phpM yAdm in

X Ij&aS&J

Help

phpMyAdmin
Welcome to phpMyAdmin
-Language-----------------------------------------

| E nglish___________________

[[

-Log in -----Username:

zend

Password:
1. 9-1

^100% *
. 8.18. phpMyAdmin

i
file

. & http://localhost/phpMyAdmin/index.php?t
dt

Vkw

Fflvorites

Iools

P 8 X

localhost / localhost | php...

tl^ P

I localhost

informatkm_schema (28)
my?iql(23)~
lest

gb Databases

^SQL

^Privileges

Ij, Replication

Status , fg|Variables
^Processes

Actions

f<j|Charsets

gfoExport

^Synchronize

MySQL

81 Server: localhost via TCP/IP


89 Server version: 5.1.50-

? Change password
Please select a database

ggEngines

jgp)Import

Logout

community
Protocol version: 10
User root@loca(host

MySQL localhost

MySQL charset: UTF-8


Unicode (utffi)
|Collation

|r| ( Create 1

HD MySQL connection collation:


|utf8_general_d
M

Webserver

Interface
SP Language :
|English

1 Theme / Style: [OriginaF

Apache/2.2.21 (Win32)
mod_ssl/2.2.21
OpenSSL/O.9.80
MySQL client version:
mysqind 5.0.8-dev 20102224 -SRevision:
318113$
PHP extension: mysqli_____

^100% *
. 8.19. phpMyAdmin

228

8. MySQL

10081 Zend
, , phpMyAdmin.

, . 8.18,
zend ( ) .
, . 8.19,
phpMyAdmin.

Linux
Zend Server MySQL, phpMyAdmin
:
https -.//local host: 10082/phpMyAdmin
, . 8.18.
zend ( ) ,
. 8.19. .

phpMyAdmin
phpMyAdmin,
, Databases (
) publications,
, .
cl assi cs, ,
(. 8.20).
,
, , .
phpM yAdm in http://www.
phpmyad mi n.net/documentation/.

,
.
M ySQL ,
,
MySQL.

, SQL-,
MySQL.


1. MySQL?
2.
?

229

localhost/ localhost/ publicabons/ classics|phpMyAdmin 2.9.1.1-Mozflla Firefox


4t
icw Hgtwy fipoknwls loots
6

&

& Server: localhost

{Empty

(S 1 P I5 P I
Database
pubfccabons (2)

j publications (2)

*
9 customers

.P Search

^In sert

(Export

03Import

category varchar(16)

Attributes

Nun Default Extra


Yes NULL
Yes

NULL

Yes

NULL

SB

Yes
No

NULL

03

j?

Indexes:

E s
s &

Iatm1jswedish_a

'

Adtpn
X EB

year
smaKrip
is bn
char(13)
Iatm1_swedisti_a
t _ Check All / Uncheck All With selected:

Keyname
PRIMARY

Type
PRIMARY

INDEX

v u fo a rjtl FULLTEXT
*

Create an index on 1

\. E

> x

- |,<aQ,,,|

Space usage

CanflnaWy
5

$
me
INDEX
catej|0ty <
year

Type
Coffation
varchar(128) Iaftn1_swedish_a
varctef(128) tetini_swe<fishd

Pnnt vniewJK Propose table structure


|e Add 1
field(s) At End of Table At Beginning of Table After author

II

^Operations

IS Drop

Flehl
author
title

....... p i!

Database: publications Table: classics

OSBrowse:
&

C" j

ft

fisjlr jJijs ( fiu 1http://localhosfc/home/mysql/

Action
S X

Reid
isbn

Type
Data

Usage
4

X
X
X

author
20
title
20
category 4

Index
Total

7,592

None
None
None

f
S
f

None

year

None

aiihor
fife

'

cotomnsfGo~|

Done

. 8.20. classics, phpMyAdmin

3. MySQL newuser
newpass,
newdatabase?
4. ?
5. MySQL?
6. FULLTEXT?
7. ?
8. , SELECT DISTINCT GROUP BY,
,
. SELECT DISTINCT
GROUP BY?
9. SELECT.. .WHERE ,
- author cl assi cs,
, Langhorne?
10. ,
?
,
8.

MySQL

8
SQL.
, , , .
, ,
, . ,
, .
,

.


, ,
, , ,

, M ySQL
.

, , ,
.
-
.
, ?
?
?
?
?
?
?
- ?

231

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

.
authors (). ,
, ,
. ,
, ,
authors.
books (). .
, .
,
.
customers (). ,
,
.

,
, . ,
, ,
,
. ,
.

. .
: .
ISBN, , ,
,
ISBN.

232

9. MySQL

, AUTO INCREMENT, ,
, .
, -
, , , ,
, ,
. ,
. ISBN
,
, .
,
AUTOJNCREMENT.


. ,
.
,
.
,
, ,
.
, , ,
,
,
. ,
ISBN.

, ,
.
,
, ,
. ,
,
,

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

233

9.1.

Author 1 Author 2 Title


( 1) ( 2) (
)

ISBN

Price
Cust. name Cust.
() (
address
) (
)

Purch.
date
(
)

D a v id S k la r A d a m

0596101015

44,99

Mar 03
2009

T ra c h te n

PH P
C ookbook

Emma
Brown

1565
Rainbow
Road, Los
Angeles, CA
90014

b e rg

Dynamic
HTML

0596527403 59,99

Darren
Ryder

4758 Emily Dec 19


Drive,
2008
Richmond,
VA 23219

David Lane PHP and


MySQL

0596005436 44,95

Earl B.
Thurston

862 Gregory Jun 22


Lane,
2009
Frankfort,
KY 40601

Darren
Ryder

4758 Emily Dec 19


Drive,
2008
Richmond,
VA 23219

David Miller

3647 Cedar
Lane,
Waltham,
MA 02154

Danny
Goodman

Hugh E.
Williams

D a v id S k la r A d a m
T ra c h te n

PH P

0596101015

44,99

C ookbook

b e rg

Rasmus
Lerdorf

Kevin
Tatroe
& Peter
MacIntyre

Program
ming PHP

0596006815 39,99

Jan 16
2009

,
,
,
.


,
.
1. ,
.
2. .
3. .
, , Author 1
Author 2 . ,
, ,
Author 1.
, , Programming ,
. , Author 2
Kevin Tatroe Peter MacIntyre 2.
.

234

9. MySQL

3 , ISBN
.
. 9.2 . 9.1.
, ,
.
9.2. Authors . 9.1

Title
()

ISBN

Price ()

Purch.
Cust. Address
Cust. name
( ( Date (
)
)
)

C ookbook

0596101015

44,99

Emma Brown

Dynamic HTML

0596527403

59,99

Darren Ryder 4758 Emily


Drive,
Richmond, VA
23219

Dec 19 2008

and
MySQL

0596005436

44,95

Earl B.
Thurston

Jun 22 2009

PH P C ookbook

0596101015

44,99

Darren Ryder 4758 Emily


Drive,
Richmond, VA
23219

Programming
PHP

0596006815

39,99

David Miller

1565 Rainbow
Road, Los
Angeles, CA
90014

862 Gregory
Lane, Frankfort,
KY 40601

3647 Cedar Lane,


Waltham, MA
02154

Mar 03 2009

Dec 19 2008

Jan 16 2009

Authors . 9.3,
. ISBN,
, .
,
,
, . : MySQL
. ,
, M ySQL ISBN
, - .
9.3. Authors

ISBN

Author ()

0596101015

David Sklar

0596101015

Adam Trachtenberg

0596527403

Danny Goodman

0596005436

Hugh E Williams

0596005436

David Lane

0596006815

Rasmus Lerdorf

0596006815

Kevin Tatroe

0596006815

Peter MacIntyre

235

, ISBN
Books, . ,
, ISBN
Authors. Authors
,
.
Authors ISBN ,
, , ,
.
, : ISBN
,
.

, .

( ) MySQL .
4 . 8
----
, WHERE .
. ,

.



( ) .
.
,
.
, ,
,
.
. 9.2. , Darren Ryder
, . , ,
(Customer name Customer address),
. . 9.4 ,
, . 9.2.
9.4. Titles

ISBN

Title ()

Price ()
44,99

0596101015

Cookbook

0596527403

Dynamic HTML

59,99

0596005436

PHP and MySQL

44,95

0596006815

Programming PHP

39,99

236

9. MySQL

, . 9.4 ISBN, (Ti tl )


(Price) ,
,
, .
,
.
, , . .,
. ,
, : ,
,
,
. ,
.
, , ,
. 9.5, ,
, Darren Ryder -
. , 2
( )
,
Address, City, State Zip.
9.5. . 9.2

ISBN

Cust Name
( )

Cust. Address
( )

Purch. Date
( )

0596101015

Emma Brown

1565 Rainbow Road,


Los Angeles, CA 90014

Mar 03 2009

0596527403

Darren Ryder

4758 Emily Drive,


Richmond, VA 23219

Dec 19 2008

0596005436

Earl B. Thurston

862 Gregory Lane,


Frankfort, KY 40601

Jun 22 2009

0596101015

Darren Ryder

4758 Emily Drive,


Richmond, VA 23219

Dec 19 2008

0596006815

David Miller

3647 Cedar Lane,


Waltham, MA 02154

Jan 16 2009

,
, . ISBN

( ), .
. 9.6 Customers
.
, CustNo,
, ,
AUTO INCREMENT.
,
.

237

9.6. Customers

CustNo
(
)

Name ()

Address
()

City ()

State ()

Zip (
)

Emma Brown

1565 Rainbow
Road

Los Angeles

CA

90014

Darren Ryder

4758 Emily
Drive

Richmond

VA

23219

Earl .
Thurston

862 Gregory
Lane

Frankfort

KY

40601

David Miller

3647 Cedar
Lane

Waltham

MA

02154

. 9.6
,
.
Purchases (. 9.7).
9.7. Purchases

CustNo ( ) ISBN

Date ()

1
2
2

Mar 03 2009

0596101015
0596527403

Dec 19 2008

0596101015

Dec 19 2008

0596005436

Jun 22 2009

0596006815

Jan 16 2009

, Customers Purchases,
CustNo . 9.6.
ISBN, Authors,
Titles.
CustNo ( )
Purchases:
( ), CustNo
. Purchases
. ,
.
, ,
.
, , , CustNo ISBN.

---

----------------------------------------------------------------------------------------------

, , ,
*<SV4 * .

, ,

Purchases ().

238

9. MySQL

: Authors (. . 9.3), Titles (. . 9.4),


Customers (. . 9.6) Purchases (. . 9.7).
Cust No, ISBN.
, , , Darren Ryder,
. 9.6, Customers, , CustNo
2.
, , . 9.7, Purchases,
ISBN , 0596527403 059610101519
2008 . ,
MySQL.
, . 9.4, Titles,
, Dynamic HTML Cookbook.
, ISBN,
. 9.3, Authors. , ISBN 0596527403, Dynamic
HTML, Danny Goodman, ISBN 0596101015, Cookbook
David Sklar Adam Trachtenberg.



, , ,
- .
,
, , ,
,
, ,
.
, . 9.6, Customers, , State,
Ci ty Zi code ,
.
, Address
City, State.
, . 9.6,
. 9.8-9.11.
9.8. Customers,

CustNo
(
)

Name ()

Address ()

Zip
(
)

1
2

Emma Brown

1565 Rainbow Road

90014

Darren Ryder

4758 Emily Drive

23219

Earl . Thurston

862 Gregory Lane

40601

David Miller

3647 Cedar Lane

02154

239

9.9. Zip codes,

Zip ( )

CitylD ( )

90014

1234

23219

5678

40601

4321

02154

8765

9.10. Cities,

CitylD (
)

Name ()

StatelD (
)

1234

Los Angeles

5678

Richmond

46

4321

Frankfort

17

8765

Waltham

21

9.11. States,

StatelD (
)

Name ()

Abbreviation
()

California

CA

46

Virginia

VA

17

Kentucky

KY

21

Massachusetts

MA


9.6? . 9.8 Zip-, . 9.9
. , . 9.10 ',
StatelD, . 9.11
.

, . ,
. 9.11, ,
.
.
t3 f

---

----------------------------------------------------------------------------------------------

9.10 4 * , () .
-*#?* , ,
.

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

240

9. MySQL

, ,
, . ,
? , . 9.6,
, .
,
. 9.10 ,
.
,
,
.
1. ,
?
2. -
?
, , ,
.


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

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

, .
, . MySQL
(triggers),

. ( .)

241

PH P-
.
. (
MySQL .)
MySQL,
,
.
MySQL .

MySQL ,
, .
.



:
. . ,
, ,
. , ,
,
.
, , , - .
Customers-Addresses . 9.1
: ,
.
, ,
.
:
, ;
, ,
.
, ,
,
( , ).


( ) ,
.
, . 9.8 ,

242

9. MySQL

.
.

9.8, a (Customers)

9.8,

(Addresses)

Addre$&

Emma Brown............. ......... 1565 Rainbow Road

Darren Ryder............. .........4758 Emily Drive

23219

Earl . Thurston......... ......... 862 Gregory Lane

40601

David M iller........................ 3647 Cedar Lane

02154

90014

. 9.1. , Customers (. . 9.8),

. 9.8, , . 9.1, ,
, . 9.7,
. 9.8, .
. 9.7, Purchases, ( ) ,
.
.
. 9.2 ,
, ,
.
,

.

9.8, a (Customers)

9.7 (Purchases)

CustNo

ISBN

Date

Emma Brown.................. .. 1

0596101015

Mar 03 2009

Darren Ryder ............ .. 2

0596527403

Dec 19 2008

L ..... 2

0596101015

Dec 19 2008

Earl B. Thurston.............. .. 3

0596005436

Jun 22 2009

David M iller..... -............. .. 4

0596006815

Jan 16 2009

Custblo

Name

1
2

. 9.2.



. ,
, ,

243

. ,
.
. 9.12.
. 9.7, Purchases (),
. ISBN ,
.
9.12.
Customer ()

ISBN

1
2
2

0596101015
0596527403
0596101015

0596005436

0596006815


, .
, ,
.
, , ,
23219. (zip code) . 9.8, ,
, 2
, . . 9.8, ,
. 9.12,
.
, , ,
. 9.4, . 9.3
.
, , , ,
, . ,
. 9.3 .

9.8,
(Customers)

9.4
(Titles)

9.12
(Customers/ISBN)

Zip

Cust

90014

1 ------- 1
2 ---- ~ - - 2

0596101015 .... .... 0596101015

L 2

0596101015..... ..... 0596527403

40601

......... 3

0596005436 ..... ..... 0596005436

PHP and MySQL

02154

4 ... -.... ----- 4

0596006815 .......... 0596006815

Programming PHP

23219

CustNo

ISBN

ISBN

Title
PHP Cookbook

0596527403 .....
Dynamic HTML

. 9.3.

244

9. MySQL

(zip-)
.
,
ISBN.
ISBN , ,
.

zip-. Titl es
ISBN,
, , , Customers
zip-
.


, , , ,
. ,
zip- ,
.
,
,
.

,

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

.
,
, , .
?
. ,
, ?
, MySQL ,
.

245

,

,
, , M ySQL
.

( )
MySQL ,
M ySQ L- InnoDB. ,
.
, , 9.1. (
, M ySQL
.)
9.1. ,
CREATE TABLE accounts (
number INT, balance FLOAT. PRIMARY KEY(number)
) ENGINE InnoDB;
DESCRIBE accounts;

, ,
, .
:

+----------- +----------+-------+-------+----------+---------+
| Field

| Type

| Null | Key

|Default| Extra |

| NO
| YES

| 0
|NULL

+----------- +----------+-------+-------+----------+---------+
| number | in t ( ll)
| balance | flo a t

| PRI
|

|
|

|
|

+----------- +----------+-------+-------+----------+---------+
2 rows in set (0.00 sec)

,
. , 9.2.
9.2. accounts
INSERT INTO accounts(number, balance) VALUES(12345. 1025.50);
INSERT INTO accounts(number, balance) VALUES(67890, 140.00);
SELECT * FROM accounts;

,
. :

+--------- +-----------+
| number | balance |

+--------- +-----------+
| 12345 | 1025.5 |
|

67890 |

140 |

+--------- +-----------+
2 rows in set (0.00 sec)

246

9. MySQL

BEGIN
M ySQL BEGIN, START
TRANSACTION. MySQL, ,
9.3.
9.3. MySQL
BEGIN;
UPDATE accounts SET balance=balance+25.11 WHERE number=12345;
COMMIT;
SELECT * FROM accounts;
,
, :

+---------+---------- +
|

number |balance |

+---------+---------- +
|
12345 |1050.61 |
| 67890 |
140 |

+---------+---------- +

2 rows in set (0.00 sec)


, 12345 25,11 1050,61.
9.3 COMMIT,
.

COMMIT
, , ,
, COMMIT, .
COMMIT,
MySQL . ,
COMMIT ROLLBACK.

ROLLBACK
ROLLBACK, M ySQL ,
.
, 9.4.

BEGIN;
UPDATE
UPDATE
SELECT

9.4.
accounts SET balance=balance-250 WHERE number=12345;
accounts SET balance=balance+250 WHERE number=67890;
* FROM accounts;

247

EXPLAIN

, :

+---------+--------- +
|

number | balance |

|
|

12345 | 800.61 |
67890 |
390 |

+---------+--------- +

+ ------------------------- + --------------------

2 rows in set (0.00 sec)

250 ,
, 250
250 . , -
. ,
9.5.
9.5. / :

ROLLBACK

ROLLBACK;
SELECT * FROM accounts:

,
,
ROLLBACK:

_ ---- + .
number | balance
12345 | 1050.61
140
67890 |
2 rows in set (0.00 sec)

EXPLAIN
MySQL ,
, .
EXPLAIN, , ,
.
accounts 9.6.
9.6. EXPLAIN

EXPLAIN SELECT * FROM accounts WHERE number='12345 ;

EXPLAIN :
+------ +--- +--------- +-----+----- +---- +---+--- +
\ ' z \ se'ect_type|ta b l

|type |possi ble_keys|key

|key_len|ref

|rows|Extra|

+ _ _ _ ------------------+ --------------- + -------- + ----------------------+ -----------+ ------------- + ----------+ ------ + --------+

| 1 51_

|accounts |const |PRIMARY

|PRIMARY 14

|const |

1|

+ - ------------ +---------- +------+--------------- +------- +---------+------ +---- +----- +


1 "Zfi

se: (0.00 sec)

248

9. MySQL

M ySQL :
select_type. SIMPLE.
(join) ;
table. accounts;
type. const. ,
: ALL, index, range, ref, eq_ref, const, system
NULL;
possi bl e_keys. , , PRIMARY, ,
;
key. PRIMARY,
;
key len. 4. ,
MySQL;
ref. ref ,
. ;
rows. , ,
1, .
,
, EXPLAIN, ,
. , (
) , . .,

( ).

accounts , mS' 4 * :

<

DROP TABLE accounts;

, ,
,
,
.
.
,
.
, .
M ySQ L
mysqldump.

249

mysqldump
mysqldump
, ,
.
CSV
(Comma-Separated Values) ,
, X M L -.
, ,
. ,
M ySQL:cepBepa mysqldump
.
mysql dump
. ( )
M ySQL :
LOCK TABLES _1 READ, _2 READ ...
:
UNLOCK TABLES:
mysqldump
, ,
>.
mysqldump :
mysqldump - - _
, , ,
mysqldump
. . 9.13

, 2. -
, .
9.13. mysqldump

ZendServerCE 32-
Windows

C:\Pro0ram Files\zend\MySQL51\bin

ZendServerCE 64- .
Windows

C:\Program Files(x86)\zend\MySQL51\bin

OS X Zend Server

/usr/local/zend/mysql/bin

Linux Zend Server CE

/usr/local/zend/mysql/bin

publications, 8,
mysql dump ( )
, 9.7.

9. MySQL

250

9.7. p u b lica tio n s


mysqldump

- - pu b lica tio n s

,
MySQL.
, , -
,
(root) (
). ::-: ,
. 9.4.
2| C:\Window5\5y5tem3Z\cmd.exe
>

. = - ii

DEFAULT CHARSET = 1 a t in 1 ;

LO CK

T S iiL I - S

INSEKT

ALTER TABLE ' u s e JHSftBLE KEYS *.* ;


INTO 'c u to m e * s ' UfiLUES <5H avu S n i r h ' ,

B8 5 i V l 2 3 2 e t >;

s *M 8 0 0 0 f l L i a
UNLOCK TABLES;
>'<*18103

S I-1

. ' c u c t o n e iv : '

T IM E

ENaiiLE KEVS

*\

Z O K E ^ O L D . . . . T I M E . ..Z O N E .

> * 40101 SET SQI._HOv--tfOI.D SQL, MODE * / ;


./* 4 88 14 RET POKE IGK . CHECKS l 30Li) 1
'/* * 4 8 8 1 4 SET UNIQUE .CHECKS---eOLi). UNI w ill
**.
. .SET CLJ 1
1? < - i/ * ( !3 1 SET ft lift SET RESULTS - ,
ur >
/*? 4 0 1 SET COLLATION tt)MNECTION*G"H v f
1 t l SET SQLNOTES -0 )J.?QL...NOTES **/;
-

Dum p

co n p Ie * d

|C : \ P t 4 w r a n

on

F iI e S F . a s * # P H F

-
3 .

'--'0

I;
i

1.1 : i i } : 4 i >

>

. 9 .4 . publications


mysqldump .
, ,
>.
,
' cati ons.
sql , , 9.8 (
).
9.8. public a v : - s

Zz?r

mysqldump -u -p pub"~:~^s > i^ r'^ catiors.sc'

, -

9.8 .
4 * - , ----
. , , ,
, ,
.


, SQL-:

251

DROP TABLE IF EXISTS 'c la s s ic s ';


CREATE TABLE 'c la s s ic s ' (
'author' varchar(128) default NULL.
t i t l e ' varchar(128) default NULL,
'category' varchar(16) default NULL.
'year' smal1in t (6) default NULL.
'isbn' char 13) NOT NULL default
PRIMARY KEY ( 'is b n ').
KEY 'author' ('author' (20)).
KEY ' t i t l e ' ( ' t i t l e ' (20)).
KEY 'category' ('category' (4)).
KEY 'year' ('ye ar').
FULLTEXT KEY 'author_2' ( 'author' . ' t i t l e ' )
) ENGINE=MyISAM DEFAULT CHARSET=latinl;

,
, ,
, ,
MySQL.


(
classics publications),
MySQL , :
LOCK TABLES p ub lications.classics READ;

MySQL , .
, MySQL, ,
:
mysqldump - - publications classics > classics.sq l

,
MySQL ,
, :
UNLOCK TABLES;


MySQL
( , mysql), ,
9.9,
MySQL, , .
9.9. MySQL

mysqldump - - --all-databases > all_databases.sql

&
, MySQL SQL? 4 .
---- ^
, , .

252

9. MySQL


,
mysql , ,

<. ,
--all-databases, ,
9.10.
9.10. " 5 -*

mysql - - < all_databcses.se'

-D,
. 9.11 ,
publ i cati ons , ,
9.8.
9.11. publicat"ors

mysql -u - -D publications < publications.sql

,
9.12, pub! i cati ons
cl assi cs.
9.12. classics publications

mysql - - -D publications < classics.sq l

CSV
, mysql dump
, CSV.
9.13 , cl assi cs customers
publications c la s s ic s .tx t customers.txt,
: /temp. Zend Server
root .
OS X Linux,
.
9.13. CSV

mysqldump - - --no-create-info --tab=c:/temp


--fields-term inated-by='.' publications

, ,
.
:
Mark Twain (Samuel Langhorne Clem ens)'The Adventures
of Tom Sawyer . 'C lassic F ic t io n '.'1876'.'9781598184891
Jane Austen , 'Pride and P re ju d ice ', 'C lassic F ic t io n '.'1811','9780582506206
Charles Darwin','The Origin of Species . 'N o n -F ictio n ','1856'.'9780517123201
Charles Dickens'. 'The Old Curiosity Shop'. 'C lassic F ic t io n '.'1841','9780099533474

253

William Shakespeare'. 'Romeo and J u l i e t ' . 'P la y '.'1594','9780192814968


Mary Smith . 9780582506206
Jack W ils o n ' .'9780517123201


,
, . ,

. ,
.
, .

df


. ,
. ,
, ;
, , - DVD . .
, - .


, MySQL. ,
.


1. (relationship)
?
2.
?
3. ?
4. ?
5. , ,
, ?
6. ?
7. MySQL?
8. M ySQL
?
9.
pub! ic a ti ons publ icati ons. sql ?
,
9.

1 0 MySQL
X I #

MySQL, . ,

MySQL.

MySQL

MySQL
SQL- ,
-.
M ySQL ,
MySQL

, MySQL. MySQL
, ,
, .

-.

M ySQL .
1. MySQL.
2. , .
3. .
4. .
5. -.
6. 3- 5- .
.
7. MySQL.

MySQL

255

,
, ,
,
.


-, ,
, MySQL, ,
.
, , . ,
1ogin. php, 10.1. ,
_ ,
MySQL, , , , 2.
. 1ocal host
, M ySQL
, publications,
.

10.1. login.php

<?php // login.php
$db_hostname = 'localhost';
$db_database = 'publications';
$db_username = ' _' ;
$db_password = '':
?>
1ogi n. php, 10.1,
<?php ?>, , ,
, .
, -
, . ,
. -
-.
$db_hostname ,
. ,
M ySQL ,
, ,
. ,
, .
mysql.myserver.com,
localhost ( 1- 127.0.0.1).
, $db_database,
publications, , , , 8,
, (
1ogi n.php).

10. MySQL

256

$db_username $db_password
, MySQL.

, ,
,
, PHP-,
MySQL.

MySQL
login.php require_
P H P -, .
, i ncl ude, ,
, . ,
,
, .
requi _, reqi.'re ,
, - ,
. ,
, 10.2.
once

10.2. MySQL
<?php
requi re_once 1ogi n .php ;
$db_server = mysql_connect($db_hostname. Scz^se^rame. $db_password);
if

( !$db_server) die("HeB03M0>KH0

MySQL: " . m ysql_error());

?>
- mysql connect,
: (hostname) M ySQ L -, (username)
(password).
, FALSE.
, i f
die, ()
, Sdb server
.
, die, ,
M ySQ L ,
, mysql_error.
,
M ySQL.
, $dbserver,
MySQL.

M ySQL -.

MySQL

257

die , , ,
, .
, ,
, :
function mysql_fatal_error($msg)

{
$msg2 - mysql_error();
echo < _END
, .
:

<p>$msg: $msg2</p>

,
. ,
. < href=Mmailto:admin@server.com">coo6iiiHTe
</>. .
END:

)______________________________________________________________


M ySQL
, . , 10.3.
10.3.

<?php
mysql_select_db($db_database)
or di(" : " . mysql_error());
?>
mysql_select_db.
, .

die.
, ,
mysql _sel ect_db, TRUE, FALSE.
P H P - or, :
, ,
. , or
.


MySQL mysql_
query. 10.4.
10.4.

<?php
$query = "SELECT * FROM classics":

258

10. MySQL

$result = mysql_query($query);

i f !Sresult) die (" : " . mysql_error()):


?>
Squery ,
. cl assi cs.
, , MySQL,
, mysql query,
,
. MySQL , , .
, Sresult.
M ySQL ,
Sresul t , , ,
,
. . .
Sresul t ,
. .
Sresul t FALSE.
. FALSE, ,
die.


, mysql_query,
.
mysql _result. 10.5
,
.
, 1ogi n.php,
query. php.
10.5.

<?php // query.php
requi re_once '1ogi n.php ;
$db_server = mysql_connect($db_hostname. $db_username. Sdb_password);
if

( !Sdb_server) die("HeB03M0MH0

MySQL: " . mysql_error());

mysql_select_db($db_database)
or die("HeB03M0>KH0 : " . m ysql_ error()) ;
Squery = "SELECT * FROM classics":
Sresult = mysql_query(Squery):
i f ( ! Sresult) die (" : " . mysql_error()):
Srows = mysql_num_rows(Sresult):
for (Sj = 0 ; Sj < Srows : ++Sj)

259

MySQL

echo
echo
echo
echo
echo

'Author: '
. mysql_result($result,$j, 'author')
'<br
'Title: '
. m ysql_result($result,$j.'title')
'<br
'Category: ' .mysql_result($result,$j. 'category') . '<br
'Year: '
. mysql_result($result,$j.'year')
'<br
'ISBN: '
. mysql_result($result,$j. ' isbn*)
'<br /><br

/>';
/>';
/>';
/>':
/>':

}
?>
,
. $rows ,
mysql num rows.
, .
, for,
mysql resul t.
$result, mysql_
query, $j , .
, mysql _resul t,
echo
.
. 10.1.
Mozitla Rrefox

..

v.

fiookmwte ..
...........................| ( D

I http://localho5t/wefa/quMy.php

v:.

Q .

'fc jlC b l Google

Author Mark Twain (Samuel Langhorne Clemens)


Tide: The Adventures of Tom Sawyer
Category. Classic Fiction
Year 1876
ISBN: 9781598184891
Author Jane Austen
Tide: Pride and Prejudice
Category: Classic Fiction
Year 1811
ISBN: 9780582506206
Author. Charles Darwin
Title: The Origin of Spedes
Category. Non-Fiction
Year 1856
ISBN: 9780517123201
Author Charles Dickens
Tide: The Old Curiosity Shop
Category: Classic Fiction
Year 1841
ISBN: 9780099533474
Author. WiBtam Shakespeare
Done

. 10.1. , query.p hp, 10.5

260

10. MySQL

, , , 8 classics
, , , query.php .
,

25 mysql result.
, mysql_fetch_row
.

9 , ,
, classics ,
, . ,
, .
MySQL
,
.


M ySQL
, .
for query. php (. 10.5) ,
10.6, , ,
. 10.1.
for
<?php
for ($j = 0 ; $j < Srows ; ++$j)
{
$row = mysql _fetch__row($result):
echo 'Author: '
$row[0] . ' <br / > ':
echo 'Title: ' .
Srow[l] . <br / > ':
echo 'Category: '
$row[2] . '<br / > ':
echo 'Year: '
$row[3] . '<br /> :
$row[4] . '<br /><br />
echo 'ISBN: '
}
?>

10.6.

, MySQL,
( 80 %) , mysql_fetch_row
. ,
$row.

$row ( ). , $row[0]
, $row[l] . .,
, MySQL.
mysql_result mysql_fetch_row
,
,
.

261

.
, 10.7.

10.7. MySQL

<?php
mysql_close($db_server);
?>
,
mysql _connect 10.2 $db_server.

sif
,
4 *, / 10.5 , .
!
,
,
.



M ySQL .
10.8
sqltest.php. ,
. 10.2.

10.8 HTML-. ,
.

uf'4j L

10.8. sqltest.php

<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname. $db_username, $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_db($db_database. $db_server)
or die(" : " . mysql_error());
i f (isset($_P0ST['delete']) && isset($_P0ST['isbn']))
{
$isbn = get_post('isbn'):
$query = "DELETE FROM classics WHERE isbn='$isbn'
i f (!mysql_query($query, $db_server))

262

10. MySQL

Mozilla Firefox
|

. ^ goobnarie

Io o ls

S k

gdp

in i ( D

Q
|http://localhost/web/sqltest.php

" I ( E H 600^ *

P \\,

A u th o r

f l

T itle
C a te g o ry
I

Year

ISB N

;
;

J
1 A Q P B E C Q R P .I

A u th o r
T itle
C a te g o ry
Y ear
ISB N
[

A u th o r
T itle
C a te g o ry
Y ear
IS B N

H a r k T w a in (S a m u e l L a n g h o r n e C le m e n s )
The A d v e n t u r e s o f Tom S aw y e r
C la s s ic F ic tio n
187 6
9781598184891

Ja n e A u s te n
P r id e a n d P r e ju d ic e
C la s s ic F ic tio n
181 1
9780582S06206

ImeiEMCoRel
A u th o r
T itle
C a te g o ry
Y ear

C h a r l e s D a r w in
The O r i g i n o f S p e c ie s
N o n - F ic tio n
185 6

Done

#>

. 10.2. , 10.8,
sqltest.php

echo " : $query<br />"


mysql_error() . "<br /x b r />";
}
i f ( isset($_P0ST[' author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
Sauthor = get_post('author'):
S title
= g e t_ p o st('title '):
Scategory = get_post('category');
Syear
= get_post('year'):
$i sbn
= get_post( ' i sbn');
$query = "INSERT INTO classics VALUES" .
"('Sauthor'. ' $ t it le '. 'Scategory'. 'Syear', 'Sisbn')";
i f ( !mysql_query(Squery, $db_server))
echo " : $query<br />" .
mysql_error() . "<br /><br />";

263

}
echo <_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="textn name=,,title " />
Category <input type="text" name=,,category" />
Year <input type=,,text" name=M
year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" /> //
//
</pre></form>
_END;
Squery = "SELECT * FROM classics";
$result = mysql_query(Squery);
i f ( ! Sresult) die (" : " . mysql_error());
Srows = mysql_num_rows(Sresult);
for ($j = 0 ; $j < Srows ; ++$j)
{
Srow = mysql_fetch_row($result):
echo <_END
<pre>
Author $row[0]
Title $row[l]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value=nyes" />
<input type="hidden" name="isbn" value="$row[4]" />
<input type="submit" value="DELETE RECORD" /></form>

//
//

_END:
}
mysql_close($db_server):
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
80
,
10.5, .

264

10. MySQL

,

classics publ ications, .
, ,
. , .
isset,
, .
,
if, get post,
. , :
.

$_POST
3 ,
GET- POST-. POST-,
. - (
) $_P0ST. .
$_P0ST , 6.
$_P0ST S GET
, , POST GET.
.
, .
, i sbn, S P0ST
isbn. P H P - ,
$_P0ST['isbn'], $_P0ST["isbn"] (
).
$_P0ST ,
, 10.8:
, $_P0ST
. PH P- :
S P0ST .
&

$_POST .
4 ,
#? .

get post, ,
mysql_real_escape_string,
,
.


,
, ,

265

$_POST[ 'delete' ]. , ,
DELETE RECORD ( ).
Sisbn.
, ISBN
. H T M L- ISBN DELETE FROM,
Squery, mysql query,
MySQL. mysql_query TRUE, FALSE,
FALSE ,
.
Sdelete yes (),
else. Squery INSERT INTO,
.
mysql query,
TRUE, FALSE. FALSE,
.


, ,
. 10.2. echo <_END,
, END,
.

echo ,
?>, HTML, ,
<?php. ,
PHP- :

( )
, .php .
HTML;

HTML,
. HTML
, , HTML.

H T M L - , ,
sqltest.php. ,
sql test, php, .
POST-, GET-. ,
GET- U R L -
.

.
POST-,
, .
HT M L Submit
ADD RECORD ( ), .

266

10. MySQL

<> </>,
.
<> ,
.


10.5,
M ySQL
classics. Srows ,
,
for.
. <br />,
10.5 ,
<>, ,
.
,
sql te s t. php ( ),
: delete isbn. delete yes,
isbn , $row[4],
ISBN . Submit
DELETE RECORD ( ), .
for, ,
.
get post,
. P H P -,
MySQL. ,
.


( )
Moby Dick,
:
Herman Melville
Moby Dick
Fiction
1851
9780199535729
ADD RECORD (
), - ,
. . 10.3.
, ,
. 1
ADD RECORD ( ).

267

MySQL

, , . ,
, DELETE RECORD
( ) , ,
.
Mozilla Fi refox

file drt

)ifcm

gookmarks Tools fcldp

' X ^ Q
j?. ( D Ihttp://localhost/web/sqltest.php
won-nccxon------ ~
----------

c a t e g o r y
Y e ar 1856
ISBN 9780517123201

>

ft - HEMax***
p\
------------- ------------------

| DELETE RECORD |
Author
Ti tl e
Ca te go ry
Ye ar
ISBN

Charles Dickens
The Ol d C u ri os it y Shop
Cl as si c Fi ct io n
1841
9780099533474

[ DELETE RECORD |
Au th or
Ti tl e
Ca t e g o r y
Ye ar
IS BN

W i l l i a m Sh akespeere
Romeo and Juliet
Play
1594
9780192814968

[ DELETE RECORD |
Author
Ti tl e
Ca t e g o r y
Year
I S BN

e ;|

H e rm an Me lv il le
M o b y Dick
Fiction
1851
97 80 199535729

| DELETE RECORD |

Done

. 1 0 .3 . M o b y Dick

^ --hV

---------------------------------------------------------------------------------------------

, , .
, (
Moby Dick) , .
, , ,
, ,
ISBN, .

MySQL
,
MySQL,
, , ,
- . ,
, 1ogi . php,
.

268

10. MySQL


,
. ,
: , , , , , ,
, .
. , .
, .
, ,
, , ,
, .
, id.
10.9 ,
MySQL, . ,
, .
10.9.

cats

<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname. $db_username. $db_password):
i f ( !$db_server) die(" MySQL: " . mysql_errorO):
mysql _select_db($db_database)
or die("HeB03M0>KH0 : " . mysql_error()):
$query = "CREATE TABLE cats (
id SMALLINT NOT NULL AUTOINCREMENT,
family VARCHAR(32) NOT NULL,
name VARCHAR(32) NOT NULL,
age TINYINT NOT NULL.
PRIMARY KEY (id)

)":
Sresult = mysql_query($query):
i f ( ! Sresult) die (" : " . mysql_error()):
?>
, M ySQL- ,
, ,
, MySQL
.


MySQL,
,
. DESCRIBE _ ,
H T M L-, : Column (), (),
Nul 1 () Key (),

MySQL

269

. 10.10 ,
cats .
10.10. cats

<?php
require_once 'login.php';
$db_server = mysql_connect(Sdb_hostname, $db_username, $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_db($db_database)
or die(,,Heooo : " . mysql_error()):
$query = "DESCRIBE cats";

Sresult = mysql_query(Squery);
i f ( ! Sresult) die (" : " . mysql_error()):
Srows = mysql_num_rows(Sresult):
echo "<table><tr> <th>Column</th> <th>Type</th>
<th>Nul1</th> <th>Key</th> </tr>";
for (Sj = 0 : Sj < Srows : ++$j)
{
Srow = mysql_fetch_row(Sresult);
echo "<tr>":
for (Sk = 0 : Sk < 4 ; ++Sk) echo "<td>Srow[Sk]</td>":
echo "</tr>":
}
echo "</table>":
?>
, , :
Column Type

Null Key

id
family
name
age

N0
N0
N0
N0

smal1in t(6)
varchar(32)
varchar(32)
tinyint(4)

PRI


,
. 10.11 .
, ,
cats
, 10.9.
10.11. cats

<?php
requi re_once '1ogin.php';
$db_server = mysql_connect(Sdb_hostname. $db_username, $db_password):

270

10. MySQL

i f ( !$db_server) die(" MySQL: " . mysql_error());


mysql_select_db($db_database)
or die("Heooo : " . mysql_error()):
$query "DROP TABLE cats";

Sresult = mysql_query($query):
i f ( ! Sresult) die (" : " . mysql_error()):
?>


, ,
10.12.
10.12. cats

<?php
require_once 'login.php':
$db_server = mysql_connect($db_hostname. $db_username. $db_password):
i f ( !$db_server) die(" MySQL: " . mysql_error()):
mysql_select_db($db_database)
or die("Heooo : " . mysql_error()):
Squery = "INSERT INTO cats VALUES(NULL, 'Lion', 'Leo'. 4)";
Sresult = mysql_query(Squery);
i f ( ! Sresult) die (" : " . mysql_error());
?>
Squery, ,
:
Squery = "INSERT INTO cats VALUESCNULL. 'Cougar'. 'Growler', 2)":
Squery = "INSERT INTO cats VALUESCNULL, 'Cheetah'. Charly'. 3)":
, ,
NULL? , i d AUTO_INCREMENT MySQL ,

, NULL,
.
*
4

1 4*

, MySQL .


, cats , 10.13
, ,
.

MySQL

271

10.13. cats

<?php
require_once 'login.php';
$db_server = mysql_connect(Sdb_hostname, $db_username. $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_db($db_database)
or die(" : '' . mysql_error()):
$query = "SELECT * FROM cats":

$result = mysql_query(Squery);
i f (!$result) die (" : " . mysql_error()):
Srows = mysql_num_rows(Sresult):
echo "<table><tr> <th>Id</th> <th>Family</th>
<th>Name</th><th>Age</th></tr>";
for (Sj = 0 ; Sj < Srows : ++$j)
{
$row = m ysql_fetch_row ($result);
echo "<tr> ;

for ($k = 0 ; Sk < 4 ; ++$k) echo "<td>$row[$k]</td>";


echo "</tr>":
}
echo "</table>";

?>
M ySQL- SELECT * FROMcats,
. :
Id Family

Name

Age

1 Lion
Leo
4
2 Cougar Growler 2
3 Cheetah Charly 3
, i d
.


.
, (cheetah) Charly?
Chari i , 10.14.
10.14. Charly Charlie

<?php
requi re_once '1ogi n .php':
$db_server = mysql_connect($db_hostname. $db_usernaine. $db_password);
i f ( !$db_server) die("HeB03M0WH0 MySQL: " . m ysql_error());
mysql_select_db($db_database)

272

10. MySQL

' : " . mysql_error()):


Squery = "UPDATE cats SET name='Charlie' WHERE name='Chariy'

Sresult = mysql_query($query);
i f ( ! Sresult) die (" : " . mysql_error());
?>
10.13,
:
Id Family

Name

Age

1 Lion
Leo
4
2 Cougar Growler 2
3 Cheetah Charlie 3


Growler ,
0 .
10.15.
10.15. Growler cats

<?php
require_once 'login.php :
Sdb_server = mysql_connect($db_hostname. $db_username, Sdb_password):
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Heooo : " . mysql_error()):
Squery = "DELETE FROM cats WHERE name='G r o w le r ;

Sresult = mysql_query($query):
i f ( ! Sresult) die (" : " . mysql_error()):
?>
DELETE FROM,
10.13, ,
:
Id Family

Name

Age

1 Lion
Leo
4
3 Cheetah Charlie 3

AUTO_INCREMENT
AUT0_INCREMENT ,
, .
, M ySQL
mysql in se rtjd . ,
Customers ,

273

MySQL

Cust Id .
10.12 10.16,
.
10.16. cats id

<?php
requi re_once 1ogin.php';
$db_server = mysql_connect($db_hostname, Sdb_username, $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_ab(Sab_database)
or die(" : " . mysql_error()):
Squery = "INSERT INTO cats VALUESCNULL, Lynx', 'Stumpy'. 5)";

Sresult = mysql_query($query):
echo " ID " . mysql_insert_id();

i f ( ! Sresult) die " : " . mysql_error());


?>
(
, i d, 2, ,1
):
Id Family

Name

Age

1 Lion
Leo
&
3 Cheetah Charlie 3
4 Lynx
Stumpy 5


: , . .
ID,
.
, ,
- ,
,
, .
10.16, , ID,
, SinsertID,
:
Squery
Sresult

= "INSERT INTO cats VALUES(NULL,'Lynx', Stumpy',


= mysql_query(Squery);
SinsertID = mysql_insert_id():
Squery
Sresult

5)":

= "INSERT INTO owners VALUES(SinsertID, 'Ann','Smith')":


= mysql_query(Squery);


, AUT0_
INCREMENT.

274

10. MySQL



ID .
,
, .
.
1. (, cats).
2.
3. ID mysql_
insert_id.
4. .
5.
,
ID .
, 9, ,
M ySQL-.


, .
, customers cl assies,
8. customers
, classics
. ISBN,
isbn,
.
,
, . 10.17.
10.17.

<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname. Sdbjjsername. $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error());
mysql_select_db($db_database)
or die(" : " . mysql_error());
Squery = "SELECT * FROM customers":

$result = mysql_query($query):
i f ( ! Sresult) die (" : " . mysql_error()):
Srows = mysql_num_rows(Sresult);
for (Sj = 0 : Sj < Srows : ++$j)
{
$row = mysql_fetch_row($result);

MySQL

275

echo $row[0] purchased ISBN $row[l]:<br />";


$subquery = "SELECT * FROM cla ssics WHERE isbn='$row[l]'";

$subresult = mysql_query($subquery);
i f ( ! Ssubresult) die (" : " . mysql_error());
$subrow = mysql_fetch_row(Ssubresult) :
echo " Ssubrow[l]' by $subrow[0]<br />":
}
?>
customers,
. ISBN ,
, cl assi cs,
.
:
Mary Smith purchased ISBN 9780582506206:
'Pride and Prefer ' :y Jsre Austeri
Jack Wilson purchases IS5S 9~S251~1232CL:
'The Origin c~ 5:e:~es'
I^5r'es Darwin

,
,
NATURAL JOIN (. 8):
SELECT name.'s:^

. ..'*:'* FROM customers

NATURAL JOIN :'5ss:s:

SQL-
, M ySQL
. , ,
:
Suser = $_P0ST['user']:
Spass = S_P0ST[pass]:
Squery = "SELECT * FROM users WHERE user='Suser' AND pass='Spass'":
.
fredsmith mypass,
Suser Spass, , MySQL,
:
SELECT * FROM users WHERE user='fredsmith' AND pass=mypass'
, , -
Suser ( Spass
):
admin' #

276

10. MySQL

, MySQL:
SELECT * FROM users WHERE user= *admin' #' AND pass="
, ( )? M ySQL
# .
admin (, admin),
.
,
.
SELECT * FROM users WHERE user=,admin #' AND pass="

, ,
, . , , ,
, ,
admi . ,
?
:
$user

= $_P0ST[' user'];

Spass

= $_P0ST[ pass ]:

Squery = "DELETE FROM users WHERE user=$user' AND pass='Spass'":


, , ,
- Suser :
anything' OR 1=1 #
MySQL (
):
DELETE FROM users WHERE user='anything' OR 1=1 #' AND pass="

SQL- ,
, .
?
(magic
quotes),
(\). ?
, .
, , .
,
. 5.3.0 ,
6 .
MySQL
mysql_real_escape_string. 10.18 ,
, ,
,
.

MySQL

277

10.18. , ,

MySQL
<?php
function mysql_fix_string($string)
{
i f (get_magic_quotes_gpc()) Sstring = stripslashes(Sstring):
return mysql_real_escape_string(Sstring);
}
?>
get_magic_quotes_gpc TRUE,
. ,
, mysql real eascape stri ng
,
. 10.19 ,
mysql _fi .
10.19. MySQL ,


<?php
Suser = mysql_fi x_stri ng($_P0ST[user ]);
Spass = mysql_fix_string($_POST['pass]);
Squery = "SELECT * FROM users WHERE user='Suser' AND pass='Spass'";
function mysql_fix_string(Sstring)
{
i f (get_magic_quotes_gpc()) Sstring = stripslashes(Sstring);
return mysql_real_escape_string($string);
}
?>

, mysql_escape_string
MySQL, .


,
SQL-
.
(?) , .
M ySQ L-
, .
,
SQ L-.
, SQL- .
M ySQL
, 10.20.

10. MySQL

278

10.20.

PREPARE statement FROM "INSERT INTO classics VALUESC?.?.?.?.?:4:


SET @author
title
category
@year
@isbn

= "Emily Bronta".
= "Wuthering Heights".
= "Classic Fiction".
= "1847",
= "9780553212587":

EXECUTE statement USING author,title.category.year.='5:^:


DEALLOCATE PREPARE statement:
st~te^ert
classics. ,

?. .
M vSQL ,
.
. II
, , .
, 10.21 (
, login.php
).
10.21.

<?php
require 'login.php :
$db_server = mysql_connect($db_hostname. $db_username. $db_passwor':: :
i f ( !$db_server) die(" MySQL: " . m y s q "
mysql_select_db($db_database)
or die(" : " . mysql_error()):
$query = 'PREPARE statement FROM "INSERT INTO classics
VALUESC?,?.?.?.?)"':
mysql_query(Squery);
Squery = 'SET author = "Emily Bronta".'
' title = "Wuthering Heights",' .
'category = "Classic Fiction",'
'year = "1847",' .
'isbn = "9780553212587"';
mysql_query(Squery);
Squery = 'EXECUTE statement USING author,title.category.ye5r\?'s:^ mysql_query(Squery);
Squery = DEALLOCATE PREPARE statement1:
mysql_query(Squery):
?>

MySQL

279


, .

MySQL . ,
.

HTML-
,
-,
. (Cross Site
Scripting), XSS.
,
, - HTML- ,
, JavaScript-. , ,
. ,
cookie,
. ,
.
, html entities,
HTM L ,
,
. , , HTML:
<script src=' http://x.com/hack.js> </script><script>hack();</script>
JavaScript,
. html entities,
:
&11 :s c r ip t src= ' h ttp :/ / x .com/hack.j s ' & gt:

&lt:/script&gt;&lt;script&gt;hack():&1t:/script&gt:
- - ,
,
html entities.
,
10.22, SQL- XSS-.
10.22. SQL XSS

<?php
function mysql_entities_fix_string(Sstring)
{
return htmlentities(mysql_fix_string(Sstring));
}
function mysql_fix_string(Sstring)
{
i f (get_magic_quotes_gpc()) Sstring = stripslashes(Sstring):
return mysql_real_escape_string($string);

280

10. MySQL

}
?>
mysql _enti ti es_f i x_stri ng mysc1^ 4x_stri ng
, ,
html entities. 10.23 ,
10.19.
10.23. MySQL XSS-

<?php
$user = mysql_enti ti es_f i x_stri ng( $_P0ST[' user' ]);
Spass = mysql_entities_fix_string($_POST[' pass']):
Squery = "SELECT * FROM users WHERE user='Suser' AND pass=' S p a s s ;
function mysql_entities_fix_string(Sstring)
{
return htmlentities(mysql_fix_string(Sstring));
}
function mysql_fix_string(Sstring)
{
i f (get_magic_quotes_gpc()) $string = stripslashes(Sstring);
return mysql_real_escape_string($sthng);
}
?>
M ySQL
, ,
,
, ,
.


1. P H P -
MySQL?
2. mysql resul t ?
3. ,
POST, GET.
4. ,
AUT0_INCREMENT?
5. P H P - ,
MySQL?
6. XSS- ?
,
10.

Jj 4
M ySQL
H T M L-.
, 1993 , , ,
.
, H T M L- ,
,


.


.
, .
-, ,
. ,
,
. ,
, ,
, .
:
<form> </form>;
, GET POST;
;
U R L - , .
11.1 ,
. formtest. php.
11.1. formtest.php -

<?php // formtest.php
echo <_END
<html>

11.

282

<head>
<title>Form Test</title>
</head>
<body>
<form method="post" action="formtest.php" />
?
<input type="text" name="name" />
<input type^'submit" />
</form>
</body>
</html>
_END;
?>
, ,
: . P H P -
H T M L-
echo <_END.. ._END.
,
H T M L-,
. ,
POST- P H P - formtest. php,
.
: ,
H T M L- P H P - echo <_END.
- . 11.1.
Form Test - Mozilla Firefox

Form Test

? |

& (

http:/flocaJhost/web/formtest.php

11 "]

. 11.1. fo rm tes t.p h p -


11.1
. ,
, , .
P H P-, .

283

11.2 ,
. formtest.
php, , formtest2. php
.
. 11.2.
11.2. formtest.php

<?php // formtest2.php
i f (isset($_POST[,name'])) $name = $_P0ST['name'];
else Sname = "(He )";
echo <_END
<html>
<head>
<title>Form Test</title>
</head>
<body>
: $name<br />
<form method="post" action="formtest2.php">
?

<input type="text" name="name" />


<input type="submit" />
</form>
</body>
</html>
_END;
?>

1Form Test - Mozilla Firefox


I ^
U S
j Q Form Test

1J[X1

http://localhost/web/formtest2.php

..... ....

^ |
f

:
? |

~][

. 11.2 . fo rm tes t.p h p

, ,
$_P0ST name.
S POST ,
H T M L-. 11.2
name, POST,
name $_P0ST $_P0ST[' name ].

284

11.

P H P - isset
$_P0ST[' name' ]. ,
$name ( ). ,
. <body> ,
, $name.

register_globals:

,
S P0ST $_GET . , $name=$_P0ST[ 'name' ];
,
Sname, .
( 4.2.0)
, ,
,
. , -,
, register globals ,
.
register globals?
GET- U R L -, : http: //myserver. com?overri de=l,
- Soverri de
(, , $override=0:),
.
- ,
, ,
, - .
,
,
.

- , , ,
, ,
, , register_globaIs,
POST- GET-.
, ,
$_POST $_GET.



- . , ,
,
. ,

285

, 25 6 % ,
,
. H T M L- ,
11.3.
11.3.

<form method="post" action="calc.php"><pre>


<input type="text" name="principlen />
<input type="text" name="monthly" />
<input type=,,text" name="years" value="25 />
<input type="text" name="rate" value="6" />
<input type="submit" />
</pre></form>

---

----------------------------------------------------------------------------------------------

HTML- ( ),
4 * HTML, test.html,
*! .

.
val ue
, ,
. ,
-
.
. 11.3. ,
, calc.php ,
.
} Form Test

Mozilla Firefox

-----

-----

25
6

. 11.3.

,
, , ,
- -
. .

286

11.


HTM L- ,
,
, . .


, ,
, . -
.
:
<input type="text nam="" s iz e = " maxiength="" value = "" />
name () val ue () ,
: size () maxlength ( ).
size ,
, a maxlength ,
.
type (),
- , name (),
,
.


,
, . ,
,
. :
<textarea nam="" cols="" rows="" = " ">
</textarea>
, ,
<textarea>, <input>,
</textarea>, .
- , ,
, ,
</textarea>,
:
<textarea name="" cols="" rows="" = " ">
, .

</textarea>

col s () rows ().
,
. ,

287

, , ,
, -,
.
, wrap ()
( ,
). . 11.1 .
wrap, (soft wrapping).
11.1. , < te x ta re a >

off

, ,

soft

hard

,
,
.
:
<input type="checkbox" nam="" valu="" checked=,,checkedn />
checked (),
(,
, ,
). ,
.
:
<input type="checkbox" name-'agree" />

, .
, agree on.
on (,
1), :
<input type="checkbox" name="agree" value="l" />

,
,
:
? <input type="checkbox" name="news" checked="checked" />

,
. ,
,

11.

288

. 11.4
(
. 11.4).
11.4. ,
<input type="checkb.ox name="ice" value="Vanilla" />
<input type="checkbox" name="ice" value="Chocolate" />
<input type="checkbox" name="ice" value="Strawberry" />

' Mozilld Firefox

(D

:'.\

*1

http://locafhost/web/formtest.php

___ _________ ______________ _-......... ........ ...

D 0 0

. 11.4.

, ,
( i ).
, ,
.
,
, (. ),
,
HTML, 11.5 (
[] ice):
11.5.
<input
<input
<input

type="checkbox"name="ice[]n value="Vanilla" />


type="checkbox"name="ice[]" value="Chocolate"
type=checkbox"name=Mice[]" value="Strawberry"

/>
/>

, - ,
i , .
, :
Sice = $_P0ST[' i ']:

ice , Sice
, .
i ( 11.5), Si
.

289

. 11.2 ,
H T M L - , .
,
.
11.2. $ice

$ice[0] =>

$ice[0] =>

$ice[0] =>

$ice[0] =>

$ice[l] =>

$ice[l] =>

$ice[0] =>

$ice[2] =>
$ice[0] =>
$ice[l] =>
$ice[0] =>
$ice[l] =>

Sice ,
-:
foreach(Sice as Sitem) echo "Sitem<br />":
P H P - foreach,
Sice
Sitem,
echo. < /> H T M L -,

.

(radio buttons )
,
,
.
,
.
, ,
.
, -
, H TM L-,
11.6 ( . 11.5).
11.6.

8.00-12.00<input type="radio" name="time" value="l" />|


12.00-16.00<input type="radio" name-time" value=n2" checked=,,checked"
16.00-20.00<input type="radio" name="time" value="3" />

/>|

290

11.

1 Mozilla f irefox

Qf

^
Q http://loca!host/web/formtest.php
___ ______________1':.':;;:;:."::;:.:::;__ ____ ______ _ .........

8 00-12.00 0|

12.00-16.00 | 16.00-20.00

-1

. 11.5.

: 12.00-16.00.
, ,

. ,

. .


,
. ,
, . , HTML:
echo ' <input type="hidden" name="submitted" value="yes" />'

- echo, H TM L-.
, .
P H P -
, submi tted .
, .
, , P H P -
submitted, yes.
:
if

( is s e t ( $_P0ST[ subm itted']))

{
,
,
, . .

, .
HTML, ,
, .

291

select ,
.
:
<select ="/" siz ="" 1="1>
size () .
,
. multiple ( ),
Ctrl
. ,
, ,
( 11.7).
11.7.

<select name="veg" size="r>


<option value="">opox</option>
<option val=""></^on>
<option value="M0 pK0 Bb">M0 pK0 Bb</0 p t i 0 n>
<option value="KanycTa">KanycTa</option>

<option 1=""></^>
</select>
H T M L- , , ,
( ).
. 11.6 ,
. ,
(, ), selected:
<option selected="selected" 1=,,"></^>

I. ! ifX ;

Q jjF ffl

http://locaiho5t/web/formtest.php

ft

. 11.6. select


( 11.8).

11.

292

11.8. select multiple

<select name="veg size=n5" multi pie="multipi">


<option value="">opox</option>
<option value="aco">aco</option>
<option value="MopKOBb">MopKOBb</option>

<option. value="KanycTa">KanycTa</option>
<option 1=""></^>

</select>
HTM L ,
size 5 multiple. ,
. 11.7, ,
Ctrl. size,
,
, ,
.
, ,
,
, .

M o z illa fir ^ fo x

( )

http://localhost/web/formtest.php

. 11.7. m u ltip le

,
, selected
.

label
<1 abel >
. ,
,
<1abel >.
,
, :
<1abel>8.00-12.00<input type="radio" name="time" value=,,r /></1 abel>

293


, ,
, ,
.



, ,
value:
<input type-'submit" 1="" />

, HTML:
<input type="image" name="submit" src="image.gif" />


. ,
, ,
,
.
,
.
, , ,
H T M L-
, ,
,
-
.
- ,
$_GET $_P0ST, , .
,
JavaScript, ,
MySQL, .
,
:
Svariable = $_POST[,user_input'];
.
, escape- ,
MySQL, ( ,
,
M ySQL,
):
Svariable = mysql_real_escape_string(Svariable):

294

11.

-,
magic quotes gpc, :
Svariable = stri pslashes(Svari able):
H T M L- :
Svariable = htmlenti ti es(Svari able):
, H TM L <b>hi</b>
&11:b&gt;hi&11: /b&gt:,
HTML.
, HTML,
:
Svariable = stri p_tags(Svari able);
,
, 11.9 ,
, .
11.9. sanitizeString sanitizeMySQL
<?php
function sanitizeString(Svar)
{
i f (get_magic_quotes_gpc()) Svar = stripslashes(Svar):
Svar = htmlentities(Svar):
Svar = strip_tags($var):
return Svar:
}

function sanitizeMySQL(Svar)
{
Svar = mysql_rea1_escape_string($var);
$var = sanitizeString($var):
return Svar;
}
?>
,
:
Svariable = saniti zeStri ng(S_P0ST[' user_input D):
, MySQL:
Svariable = sani ti zeMySQK S_P0ST['user_i nput']):


, P H P - H T M L, convert.php,
11.10. .

295

11.10.
<?php // convert.php
$f = $ =

i f (isset($_P0ST['f'])) $f = sanitizeString($_POST['f']);
i f (isset($_P0ST[ ])) $c = samtizeStnng($_POST['c']);
i f ($f != " )

{
$c = in tv a l((5 / 9) * ($f - 32));
$out = "$f f $c c";

}
e lse if($ c != '')

{
$f = in tv a l((9 / 5) * $c + 32):
$out = $c c $f f " ;

}
else $out =
echo <_END
<htm l> < head >< title> np orpaM M a T e M n e p a iy p b i< /title >

</head><body><pre>

<b>$out</b>
<form method="post" action="convert.php">
<input type="text name="f" size=,,7" />
<input type="text" name="c" size="7" />
<input type*"submit" 1="" />
</form></pre></body></html>
_END;
function sanitizeString(Svar)
{
Svar = stripslashes($var);
$var = htmlentities(Svar);
Svar = strip_tags($var);
return Svar;
}
?>
convert. php ,
, . 11.8.
,
Sc $f , .
f , .
.
,
, .
sani ti zeStri ng 11.9.

296

11.

' - Mozilla Firefox


1

[ | [ ] | 1

http ://localhost/web/convert. php

^I

21

69

21

[ |

. 11.8.

, ,
$f $, i f . ..
e ls e if.. .else, , $f.
, $.
$ , $out (
).
, $f , $
,
$f .
_ = ( 5 / 9 ) ( _ - 32). $out
, .
, $f , $ ,
$
$f.
: = (9 / 5 ) + 32.
, Sout
, .

P H P - intval. ,
.
, ,
H T M L-, head t it le
, $out.
, Sout
NULL , , , ,
, . ,
Sout , .
, convert. php (
) POST.
, .
, , .

297

H T M L-, ,
sani ti zeStri ng 11.9.
iif
*

"

, ,
* POST. .
, GET,
$_POST, $_GET.

.

,
Smarty ,

.


1. , ,
POST GET.
-?
2. regi ster gl obal s
?
3. ?
4. ,
(
), ,
?
5. - ,
?
6. , ?
7. H T M L- ,

?
8. P H P - H TM L ,
,
HTML?
,
11.

JL

Cookie,


.
,
, , ,
.

, cookie .
, .

cookie
Cookie , -
.
- (
4 ) .
cookie ,
, ,
, , . .
cookie
. , cookie, , oreilly.com,
-, .
- ,
.
- -
,
cookie. cookie.
-.
- cookie
, , .
, , cookie,
-.

cookie

299

cookie ,
H T M L -. cookie
H T M L - .
cookie . . 12.1
cookie - -
.
-

, webserver.com

. 12.1.
cookie

, .
1. index.html -
http://www.webserver.com. ,
.
2. - webserver.com ,
.
(text/html), cookie ,
value.
.
3. cookie,
, , cookie,
cookie cookie . ,
/news.html,
cookie value.
4. /news.html cookie ,
cookie
.

12. Cookie,

300

cookie
cookie . HTM L
setcookie,
(. 12.1):
setcookie(name. value, expire, path, domain, secure, httponly);
12.1. setcookie

name

cookie.
cookie

username

value

cookie .
4 -

Hannah

expire

time() + 2592000
(.)
Unix. ,
time(),
.
, cookie

path

(.) cookie .
(/), cookie
, www.webserver.com.
, cookie
.
, cookie, , ,

domain

(.) -,
cookie. webserver.com, cookie
webserver.com , www.
webserver.com images.webserver.com. images.
webserver.com, cookie images.
webserver.com , sub.images.
webserver.com, www.webserver.com

.webserver.com

secure

(.) , cookie
(https://).
TRUE, cookie
.
FALSE

FALSE

httponly

(; ,
5.2.0.) , cookie
HTTP. TRUE,
, JavaScript,
cookie. (
). FALSE

FALSE

cookie- username Hannah,


-
,
:
setcookie( 'username', 'Hannah'. timeO + 60 * 60 * 24 * 7 ,

HTTP-

301

cookie
cookie
$_001. , ,
cookie username, , , ,
:
i f (isset($_C00KIE[' username']))
Susername = $_C00KIE['username']:
, cookie ,
-. , cookie
, ( cookie) - cookie
.

cookie
cookie
. ,
setcook i , ti mestamp, ,
cookie, .
cookie :
setcookie('username'. 'Hannah', timeO - 2592000.
, cookie .
, 2 592 ( ).
.

-
HTTP- -
. ,
,
,
& .
HTTP-,
, .
, , ,
, .

, , - Apache, *
* , . ----**?
, .
,
.
'*%

302

12. Cookie,

U R L -
,
:
( . 12.2 , Firefox).
, , 12.1.

l:iretox

.^

____

(
^

X
ij b 1 G& i http://localhost/web/authenticate.php
___ ______ ___ :............................................. "::: .

-1

....

fiyo'fc
^

jjC jjX j

Cnp-i-c^a

[ |

<http://locatiost . : Restricted Section

: | Hannah

: |

|
(

OK

| [

| (ocahost...

.:|

. 12.2. -
12.1. -

<?php
i f (isset($_SERVER[' PHP_AUTH_USER']) &&
i sset($_SERVER[*PHP_AUTH_PW' ]))
{
echo " , : " . $_SERVER[' PHP_AUTH_USER'] .
" . : " . $_SERVER['PHP_AUTH_PW'];
}
else
{
header('WWW-Authenticate: Basic rea1m="Restricted Section"'):
header('HTTP/1.0 401 Unauthorized');
d ie(", ");
}
?>
: $_SERVER[ _
AUTHJJSER' ] $_SERVER[' PHP_AUTH_PW' ].
,
.
- , ,
, , . 12.2,
,
Basic realm:
WWW-Authenticate: Basic realm=Restricted Section"

303

, P H P -
. ,
,
:
HTTP/1. 401 Unauthorized

die : ,
(. 12.3).

' 1Mozilla Firefox

&

f%

( L3 http:/flocalhost/web/authenticate.php

f t *1

,:|

. 12.3.

----


, , - - .
,
.

.
12.1 :

, '
.
( 12.2).
12.2. PHP-
<?php
$username = 'admin':
$password = 'le tm e in ':
i f (i sset($_SERVER[' PHP_AUTH_USER']) &&
i sset($_SERVER[' PHP_AUTH_PW']))

{
i f ($_SERVER[1PHP_AUTH_USER'] == $username &&
$_SERVER[' PHP_AUTH_PW'] == Spassword)
echo " ":
else dieC'HeBepHafl " - ""):

}
else

304
{

12. Cookie,

header('WWW-Authenticate: Basic realm="Restricted Section" ):


header( 'HTTP/1.0 401 Unauthorized'):
die (", "):

}
?>
, :
. ,
: ,
, .
,
.
, - ,
.
.
I

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


,
MySQL. -
, , , -
.
.

, .
,

.
md5.
, 32- . ,
, :
Stoken = md5(_');
Stoken
:
34819d7beeabb9260a5c854bc85b3e44

HTTP-

305

shal,
, 40-
.


, md5
, ,
, 32-
, md5.
, Google.
,
md5.
, (salting),

:
Stoken = md5( ^^^ );
_.
, , .
, :
$token

= md5( 'hqb$tMCM_nap(mcg*l'):

, .
, , -,
.

, , MDS-,
, , ( ).
- ^ SHA1, , MD5,
, 40 .
, md5
PHP- shal. ( SHA1 MySQL,
40 .) ,
, PHP- crypt,
CRYPT_BLOWFISH, - http://tinyurl.com/
phpcrypt.

-
,
md5 ,
.
MySQL, ,
. , 12.3,
setupusers.php,
.

306

12. Cookie,

12.3. users

<?php // setupusers.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname. $db_username. $db_password);
i f ( !$db_server) die(" MySQL: " . mysql_error()):
mysql_select_db($db_database)
or die(" : " . mysql_error());
Squery = "CREATE TABLE users (
forename VARCHAR(32) NOT NULL,
surname VARCHAR(32) NOT NULL,
username VARCHAR(32) NOT NULL UNIQUE,
password VARCHAR(32) NOT NULL
)";
Sresult = mysql_query(Squery);
i f ( ! Sresult) die (" : " . mysql_());
Ssaltl = "qm&h*";
Ssalt2 = pg!@":
Sforename = 'B i l l ':
Ssurname = 'Smith':
Susername = 'bsmith':
Spassword = mysecret':
Stoken = md5("$saltl$passwordSsalt2")^':
add_user(Sforename. Ssurname. Susername. Stoken):
Sforename = 'Pauline':
Ssurname = 'Jones';
Susername = 'pjones':
Spassword = 'acrobat';
Stoken = md5("SsaltlSpasswordSsalt2"):
add_user(Sforename. Ssurname. Susername, Stoken):
function add_user($fn, Ssn, Sun, Spw)
{
Squery = "INSERT INTO users VALUESCSfn', 'Ssn'. 'Sun'. 'Spw')";
Sresult = mysql_query(Squery);
i f ( ! Sresult) die (" : " . mysql_error());
}
?>
publications (
, 1ogi n. php 10) users.
, Bi 11 Smith Paul i ne Jones,
bsmith mysecret pjones acrobat
.
, , ,
12.2 .

HTTP-

307

12.4. ,
authenticate.php .
12.4. PHP- MySQL
<?php // authenticate.php
requi re_once '1ogi n .php ;
$db_server = mysql_connect($db_hostname. $db_username, $db_password);
i f ( !$db_server) die("HeB03M0>KH0 ^ MySQL: " . m ysql_ error());
mysql_select_db($db_database)

or die("HeB03M0>KH0 : " . mysql_error());


i f (i s s e t ($_SERVER[' PHP_AUTH_USER']) &&
i s s e t( $_SERVER[ PHP_AUTH_PW' ]))
{
$un_temp = mysql_entities_fix_string($_SERVER[,PHP_AUTH_USER,]):
$pw_temp = mysql_entities_fix_sting($_SERVER[,PHP_AUTH_PW,]);
$query = "SELECT * FROM users WHERE username=,$un_telp, ":
$result = mysql_query($query):
i f (!$resu1t) die("C6oii : "
mysql_());
elseif (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
I s a lt l = "qm&h*";
$salt2 = "!;
$token = md5(n$saltl$pw_temp$salt2 ) ;
i f ($token = $row[3]) echo "$row[0] $row[l] :
. $row[0], '$row[2]"';
else " - '"):

}
e ls e dieCHeeepHafl

-"):

e ls e

header('WWW-Aj~fierf:cate: Basic realm="Restricted Section'");


header('HTTP/l.Q 401 Unauthorized );
die (", "):

}
fu n c tio n m y s q l_ e n t it ie s _ f ix _ s t r in g ( S s t r in g )

return htmlenti 11 es mysql_fix_stri ng($string));

}
function mysql_fi x_str"ng{Sstri ng)
i f (get_magic_quotes_g?c()) :$string = stripslashes(Sstring);
return mysql_real_escaoe_string($string):
}
?>

308

12. Cookie,

, , ,
( ).
. , 10.22,
10.
.

,
, $un_temp $pw_temp,
. M ySQL
$un_temp, , ,
$row. ( ,
.) $sal t l $sa 112
,
Spw temp.
md5, 32- ,
$token.
Stoken ,
,
3. $row[3] ,
. , ,
(. 12.4).
. ,
,
, ,
, .
5Mozilia Firefox

B E

i Q

http://locdhost/web/authenticate.php

Bill Smith: , Bill, 'bsmith'

. 12.4. Bill Sm ith

,
bsmith mysecret ( pjones
acrobat), ,
12.3.


,
, ,

309

,
, .
,
10, ,
.
, ,
.
, -
cookie.
cookie -
- .
, , cookies.
, , 4.2.0, cookie
GET- U R L -.
.


,
H T M L P H P - session s ta r t ,
cookie . ,
,
$_SESS ION:
$_SESSI0N[' _] = $__;

, :
$_

= $_SESSI0N[' _'];

, ,
,
, users,
. authenti ca te .php
12.4,
.
12.5.
i f (Stoken == $row[3]),
.
( 12.4) authenti cate2. php.
,
.
12.5.
<?php / / a u t h e n t i c a t e 2 . php
re q u i re_once

' 1o g in . p hp ';

$db_server = mysql_connect($db_hostname, $db_username. $db_password);

12. Cookie,

310

i f ( !$db_server) d ie (" MySQL: " . mysql_error()):


mysql_select_db(Sdb_database)
or d ie (,,Heooo : " . mysql_error()):
i f (is s e t($_SERVER[' PHP_AUTH_USER']) &&
i sset($_SERVER[ PHP_AUTH_PW']))

{
$un_temp = mysql_entities_fix_string(S_SERVER[,PHP_AUiH_USLR j ) :
$pw_temp = m ysql_entitiesJrix_string(SJ>ERVER[,PHP_AUTH_[V ] : :
Squery = "SELECT * FROM users WHERE username='Sun_temp'":
Sresult = mysql_query(Squery);
i f ( !Sresult) die("Co : " . n-.ysqi_er'r:r;.
e ls e if (mysql _num_rows(Sresult))

{
$row =
S sa ltl
$salt2
$token

mysql_fetch_row(Sresult):
= "qm&h*";
= "pg!@ ;
= md5("$saltl$pw_temp$salt2 );

i f ($token = $row[3])
{
s e s s io n s ta rtO ;
$_SESSION['username'] = Suntemp;
$_SESSION['password'] = $pw_temp;
$_SESSION['forename'] = $row[0];
$_SESSION['surname'] = $row[l];
echo "$row[0] $row[l] : , $row[0],
$row[2],e;
die ("<>< href=continue.php>lllee
</></>");

>
else dieC'HeeepHafl " ^ - ~5::

}
else 1(" " - ^=

}
else

{
header('WWW-Authenticate: Basic realm="Restr'C 'ec i e c v : r_ '
header(HTTP/1.0 401 Unauthorized');
die (", ";:

functi on mysql_enti t i es_fi x_string(Sstring)

{
return htm lentities(m ysql_fix_string(Sstr ' r c ; ;:

}
function mysql_fix_string(Sstring)

{
i f (get_magic_quotes_gpc()) Sstring = str-'pslashes(Sstring):

311

return mysql_real_escape_string($string):
}
?>
U RL- conti nue.php. ,
- PH P-.
conti nue. php, ^ 12.6.
12.6.
<?php // continue.php
session_start();
i f (isset($_SESSI0N[' username]))
{
Susername = $_SESSION[,username'];
Spassword = S_SESSION[,password'];
Sforename = S_SESSI0N[forename'];
Ssurname = $_SESSI0N['surname'];
echo " , Sforename.<br />
Sforename Ssurname.<br />
'Susername'
'Spassword'.":
}
else echo ", < href=authenticate2.php>u^KHHTe </>.";
?>
authenticate2.php,
bsmith mysecret ( pjones acrobat)
conti nue. php.
, , . 12.5.

Mozilla Firefox

..^

JL/ 1

http://localhost/web/continue.php

----

, Bill
Bill Smith
'bsmith* 'mysecret'.

. 12.5.

,
.

. sessi on_start
, S SESSI0N.

12. Cookie,

312

12.6 $_SESSI0N[' username ]


, ,
( cookie,
-) .
$_SESSI0N['username'] , ,
, 12.6
,
authenticate2.php.

7^

continue.php , ,
. ,
, ( ) ,
.


-,
, , 12.7.
unset sessi cn_ces"r':.
,
.
12.7.
<?php
function destroy_session_and_data()

{
session_start();
$_SESSI0N = arrayO:
i f (session_id() != "" || isset($JOT<IE[sess^cr._r.arne';];)
setcookie(session_name().
timeO - 259231.
session_destroy();

}
?>
, ccnti nue.
php, 12.8.
12.8.
<?php
session_start();

i f (isset($_SESSI0N[username']))
{
$username = $_SESSI0N['username'];
Spassword = $_SESSI0N['password']:
$forename = $_SESSI0N[' forename']:
Ssurname = $_SESSI0N['surname']:
d e s tro y s e s s io n a n d d a ta O ;

313

echo " , $forename.<br />


Sforename $surname.<br />
$username'
' $ p a s s w o rd ';

}
else echo ", < href=authenticate2.php>u^HHTe </>.";

function destroy_session_and_data()
{
$_SESSI0N = ;
i f (session idO != ,,,, || isset($_COOKIE[session_name()]))
setcookie(session_name(), " , timeO - 2592000.
sessiondestroyO;
}
?>
authenticate2.php continue.php
.
, destroy^session_
and data *
.


,
, ,
,
. ,
, , ,
.
ini_set.
:
in i_ se t('se ssio n .g cjn a x life tim e ', 60 * 60 * 24):

, ,
:
echo in i_ g e t( session.gc_maxlifetime ):


,
,
, . ,
, ,
packet s n iffin g ( ). , (ID )
GET- U RL-,

314

12. Cookie,

. -

Secure Socket Layer (SSL) -,
HTTP HTTPS. ,
-
http ://www.a pache-ssl .org.


SSL ,

IP -.
:
$_SESSI0N[1 '] = $_SERVER[' REMOTE_ADDR']:

,
IP - di fferent_user:
i f ($_SESSI0N[ ip '] != $_SERVER['REMOTE_ADDR']) different_user();
di f ferent_user ,

. ,
.
, , ,
- IP -
, IP -.
, SSL.
( ,
, ),

, .
:
$_SESSION['ua'] = $_SERVER[HTTP_USER_AGENT J :

:
i f ($_SESSI0N[' ua] != $_SERVER['HTTP_USER_AGENT']) different_user():
, ,
, md5:
$_SESSI0N['check'] = md5($_SERVER[REMOTE_ADDR'] .
$_SERVER[1HTTP_USER_AGENT']):
:
i f ($_SESSI0N['check'] 1= md5($_SERVER[,REM0TE_ADDR'] .
$ SERVERC'HTTP USER AGENT'])) different userO:

315



(ID ), .
,
ID GET- U R L -:
h ttp ://yourserver.com/authenti cate.php?PHPSESSID=123456789

ID 123456789.
12.9, .
,
sessiontest.php.
12.9. ,
<?php // sessiontest.php
session_start():
i f ( ! i sset($_SESSION[ ' count'])) $_SESSI0N['count ] = 0;
else ++$_SESSI0N['count'];
echo $_SESSION['count']:
?>

, ,
U RL ( ,
http ://local host/web/):
sessiontest.php?PHPSESSID=1234

, ,
.
U R L -:
sessiontest.php?PHPSESSID=5678

,
. ,
U R L -, U R L ,
.
.
,
URL-
, -
, ,
!
ID
session_regenerate_id.
, ID ,
.

, .

316

12. Cookie,

, , ,
ID ,
.
12.10 , ,
in itiated .
12.10.
<?php
session_start();

i f ( ! isset( $_SESSI0N[' in itia te d ']))


{
session_regenerate_id();
$_SESSI0N[' in itia te d *] = 1;

}
i f (!isset($_SESSI0N['count'])) $_SESSI0N[*count1] = 0;
else ++$_SESSION[count1];
echo $_SESSI0N[ count ];

?>
,
ID - ,
, ID -
. , ID
.

,
cookie
cookies
-, ini set:
ini_set( session.use_only_cookies , 1);

?PHPSESSID= .
,
, cookie,
,
.


,
,
, .
,
( ).
in i set:
in i_ s e t( session.save_path , /home/user/myaccount/sessions1):

317


, ,
.
,

. ,
.
<*

------------------------------------------------------------------------------------------------------------------------------

, - ,
?* 4 * (bots), ,
. ,
, - ,
,
.

, , MySQL,
JavaScript
, .


1. cookie ?
2. P H P - cookie -?
3. cookie?
4. P H P -
-?
5. md5 ?
6. (salting) ?
7. -?
8. -?
9. ?
10. ?
,
12.

13 JavaScript
JavaScript - .
, -
- , ,
, ,
JavaScript. ,
,
-.
JavaScript Netscape Navigator 1995
Java-.
, JavaScript
Java, .
,
,
Java.
H T M L- - ,
D O M (Document
Object Model), JavaScript .

- .
JavaScript,
, ,
. .
, ,
.
JavaScript .
,
Web 2.0 Ajax,
,
-.

JavaScript HTML
JavaScript ,
-.
H T M L- <script> </script>.

JavaScript HTML

319

Hello World, H T M L 4.01


JavaScript, , 13.1.
13.1. Hello World, JavaScript
<html>
<head><ti11e>Hel1 World</ti11e></head>
<body>
<script type=,,text/ja\rascript">
document.write Hell World")
</script>
<noscript>
JavaScript,
</noscript>
</body>
</html>

-,
HTML- <script language="javascript">.
<script type="textyjavascript">.

<script> JavaScript,
document .write, -
echo print. ,
.
, , ,
(;). , JavaScript ,
, .
, ,
, , .
, .
JavaScript.
<noscript>
</noscript>. ,
H TM L , JavaScript
.
, , ,
H T M L ,
JavaScript, .
, , <noscript> ,
,
JavaScript, , .
13.1, -
JavaScript (. 13.1):
Hello World
, JavaScript ,
(. 13.2):
JavaScript,

13. JavaScript

320

Mozilla

Firefox

^'

{ Q

http://localhost/web/hellovvorId.htm

______________

Hello World

. 13.1. JavaScript

fkj

'J Mozilla Tirefox

f% ! [3 http://tacalhost/web/heBoworid.htm

JavaScript,

. 13.2. JavaScript


, <head>,
,
. -
,
, , .

JavaScript <head> , -,
, ,
, .


, ,
H T M L- (<! -- -->),
, . 13.2
, .
13.2. Hello World,
, JavaScript
<html>
<head><ti tle>Hel1 World</titl e></head>
<body>

JavaScript HTML

321

<script type="text/javascript"><!-document.write("Hello World")


// --></script>
^/body>
</html>
H T M L- (<!--)
<script . . . >, ,
, - </scri pt>, .
(//) JavaScript, ,
. ,
, JavaScript, -->,
, JavaScript,
// -->, HTM L-.
,

, JavaScript:
<script type="text/javascript"><!-( JavaScript...)
// --></script>
, ,
.
*

--1 -------------------------------------------------------------

: VBScript, Microsoft
**' J Visual Basic, Tel, 3?* . , JavaScript, ,
text/vbscript text/tcl. VBScript
Internet Explorer,
. Tel .
.

JavaScript
JavaScript HTML-
JavaScript -,
. :
<script type="text/javascript" src="script.js"></script>
:
<script type*"text/javascript" src="http ://someserver.com/script.js">
</script>
<scri pt> </scri pt>,
: ,
JavaScript. JavaScript
.

322

13. JavaScript


- JavaScript,
.
& -*

type="text/javascript" ,
, JavaScript.

---------------------------------------------------------------------------------------------------

JavaScript
JavaScript
.
, , JavaScript
-,
, . . 13.1
. JavaScript
.
13.1. JavaScript

JavaScript

Apple Safari

Safari , ,
, Safari
""
. , JavaScript- Firebug
Lite, :
<script src='http ://tinyurl .com/fbl rte' >

Google Chrome

,
, JavaScript.
Ctrl+Shift+J PC
Command+Shift+J

Microsoft Internet
Explorer

Mozilla Firefox


: Ctrl+Shift+J PC Command+Shift+J

Opera

Mac OS X: Safari
JavaScript, Google Chrome (
Intel OS X 10.5 ), , ,
.

, , ,
. 13.3 13.1,
"! 1 World,
.

JavaScript HTML

323

JavaScript- Hello World,


<html>
<head><title>Hello World</title></head>
<body>
<script type=text/javascript">
document. writeC'Hello World)
</script>
</body>
</html>

13.3.

te s t. html,
. ,
.
( Firefox):
unterminated string literal
document.writeC'Hello World)
,
. , ,
5.
Microsoft Internet Explorer :

, ,
5, 32.
Google Chrome :
Uncaught SyntaxError: Unexpected token ILLEGAL
, 5,
.
Opera 2
:
Syntax error while loading line 2 of inline script
expected statement
document.writeC'Hello World)
, , , Opera
2 ,
H T M L-.
Opera ,
.
,
. Firefox ,
, a Internet Explorer 32,
,
, - , ,
.

324

13. JavaScript

, , , Firefox
,
JavaScript.

, Microsoft Internet Explorer,
- -. ,
,
.
Firebug,
Firefox (http://getfirebug.com),
JavaScript.
df

, , <script> </script>.

_.. -----------------------------------------------------------------------------------------------


, ,
JavaScript ,
.
:
//
(//),
JavaScript , .
:
/*
,

*/
/*
*/. ,
,
,
.


, JavaScript,
, .
:
+= 10

325

,
:
+= 10: -= 5: z = 0
,
.

.
URL- (bookmarklet)
,
, , JavaScript .
.

JavaScript ,
($) .
.
a-z, A-Z, 0-9, $
(_).
, ,
.
a-z, A-Z,
$ _ ( ).
. Count, count COUNT
.
.
$.
JavaScript ,
. ,
JavaScript ,
.


JavaScript
, :
greeting = "! "
warning = '!'

.

:

326

13. JavaScript

greeting = "\"!\ "


warning = 'V' '
,
:
newstring = oldstring
:
status = " "
document.wri te (status)


,
:
count
= 42
temperature = 98.4
,
, .

JavaScript ,
, .
, (
):
toys = [ 'bat'. 'b a ll', 'whistle', 'puzzle', 'doll']

. ,
(
: (R), (G), (0), (Y), () (W),
, ),
:
face =
[
[' R'. G , ' Y' ],
[ '1 , 'R ', ''].
[ 'Y ', , G ]
]
, ,
, :
face = [[ 'R '. 'G'. ' Y' ]. [ *W*. 'R', '0']. [' Y '. 'W. G' ]]

327

:
top = ['R\ 'G' . ' Y' ]
mid = ['W' . 'R' . O']
bot = [ Y' . 'W' , G']
face = [top. mid. bot]
,
, (
, ):
document.wri te(face[l][2])
0, .

JavaScript , ,
15 .

, JavaScript
, ,
(, . .). JavaScript
. ,
15:
document.write(13 + 2)
.



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

J + 12

j - 22

/
%

1* 7
j / 3.13

( )

j% 6

++

++j

--

-i

328

13. JavaScript


.
(=)
+=, -= . . += , , ,
,
.
, count 6, :
count += 1
7 ,
:
count = count + 1
. 13.3 ,
JavaScript.
13.3.

j = 99

j = 99

+=

j += 2

j =j + 2

+=

j += 'string'

j = j + 'string'

-=

j-= 12

j = j - 12

*=

j *= 2

j =j * 2

/=
%=

j /= 6

j =j / 6

j %= 7

j =j % 7


,
i f , . ,
, , ,
,
. . (. 13.4).
13.4.

==
;=

j == 42

He

j != 17

>

j >0

<

j < 100

>=

j >= 23

<=

j <= 13

===

( )

j === 56

!==

( )

j !== 'I'

329


JavaScript, , and
&& || (. 13.5).
13.5.

&&

j == 1

II
!

j < 100 || j >0

! (j role="strong">== k)

== 2


(
) ( ),
, , JavaScript:
++

+= 2 2

-= 3


() JavaScript ,
. . () (+):
document.write(" " + messages + " .")
, messages 3,
:
3 .
+= ,
, :
name = "James"
name += " Dean"


,
, :
, .
;
,
'!* :
heading = "NameUAgeULocation"

13. JavaScript

330

13.6 , JavaScript.
13.6. JavaScript

\b

\f
\n

\r

\t

\"

\\

\xxx

000 377,
Latin-1 (, \251 )

\xXX

00 FF,
Latin-1 (, \9 )

\uXXXX

0000 FFFF,
Unicode (, \u00A9 )


, JavaScript ;

. ,
: JavaScript ,
, .
13.4, .
1. 838102050,
, ,
typeof.
2. ,
12 345 67 890. 838 102 050, ,
. .
3. , .
13.4.
<script>
= 838102050'
document . w r it e ( =

// '
'+ + '. ' + typeof + <

/>')'

= 12345 * 67890;
document.w rite ( 'n =

// ' '
'+ n + '. ' + typeof n + '<br

/>')

n += ' // ' n *

document .wri te( 'n = '
+ n + '. + typeof n + <br
/>')
</script>

331

:
= 838102050. string
= 838102050. number
= 838102050 , string

-
, ,
, ,
( ):
= 123"
n *= 1
// ''
= 123
+=

// V

typeof.

, JavaScript ,
. ,
13.5.
13.5.

<script>
function product(a. b)

{
return a*b

}
"'Vscript>
,
.


,
( , var).
:
= 123
var b = 456
i f ( == 123)

//
//
var = 789 //

var,
, .
, .

332

13. JavaScript


, ,
, .
. , ,
, ,
.
,
,
var. 13.6 ,
.
13.6. , :

"'script^
function testO

{
- 123
//
var b = 456
//
if ( == 123) var ( = /89 //
'-/script>

, ,
i sset. JavaScript ,
13.7 typeof,
undefined, .
13.7. , test

<script>
te s t()
if (typeof
i f (typeof
i f (typeof

a != undefined') document.writo ( a
b != 'undefined') document.write( b
!= 'undefined') document .writ. p (

=
+a + ' <br
=
+b + ' <br
= "' + + "<br

/>')
/>')
/>')

function le s tO

{
a - 123
var b = 456
i f (a == 123) var = 789

:
= '123"

, , ,
,

333

b va
.
, b
, , , .


JavaScript .
(
),
, D O M (Document Object Model).
HTML- ,

JavaScript.
JavaScript , (
, JavaScript
+, ). , ,
card . , name,
address, phone . . JavaScript
:
card.name
card.phone
card.address
, ,
. , ,
card, :
card.display()

, document.write.
, JavaScript , , write
document.
JavaScript
. D O M
(. 13.3).
HTM L-,
- .
, U R L - (body) H TM L-
. JavaScript :
url = document.links.linkname.href
,
. , document, <html > <body>, 1i nks. 1i nkname
< .. .>, a href href=___

334

13. JavaScript

<head>|

<title> \

j
Text...

<hl> \

1 <imf ... > \

<*->)

i
| Heading.. "!

i
actions 1

. 13.3. DOM

H T M L
. 13.8 1i nktest. html,
.

Microsoft Internet Explorer,


, ,
,
getElementByld, .
.

13.8. URL- JavaScript


<html>
<head>
<1> ca>mKH</title>
</head>
<body>
<a id="mylink" href="http://mysite.com">ll^KHH</a><br />
<script>
url = document.links.mylink.href
document.write('URL- - + url)
</script>
</body>
</html>
script,
type="text/JavaScri pt".
( ) ,
<script> </script>. :

URL- - http://mysite.com

document.write. ,

335

document links, mylink (, )


href (, U R L - ).
, ,
, id: my1ink. href. :
url = document.links.mylink.href

url = mylink.href


13.8 Safari, Firefox, Opera Chrome,
Internet Explorer, JavaScript,
Microsoft J Script,
. -!
?
1inks, document,
Internet Explorer , ,
. :
url = document.links.mylink.href
:
url = document.getElementById('mylink') .href
. ,
,
Internet Explorer, , , :
url = mylink.href

$
, $
JavaScript. ,
:
url = $ ('mylink') .href
, getElementById
JavaScript, ,
13.9, $.

13.9. , getElementById

<script>
function $(id)
{
return document.getElementById(id)
}
</script>

336

13. JavaScript

, $ , :
$ ('mylink' ).href
:
document.getElementById('mylink') .href

DOM
1i nks , U RL-,
U RL myl ink 13.8 ,
( ):
url = document.11nks[0].href
, ,
length 1inks:
numlinks = document.links.length

:
for (j=0 : j < document.links.length : ++j)
document.write(document.links[j].href + '<br />')
length ,
. ,
:
document.wri te(hi story.1ength)
- -
, hi story
, .
, , ,
. ,
,
, ,
history. ,
, :
history.(-)

:
hi story.back
history.forward
U R L-
:
document.location.href = 'http://google.com'

337

, D O M
, . ,
JavaScript, D O M
.


1. JavaScript?
2. ,
JavaScript?
3. JavaScript ?
4. JavaScript P H P - echo pri nt?
5. JavaScript?
6. JavaScript ?
7. JavaScript
, ?
8. ,
U R L - id .
9. J avaScript
, history?
10. JavaScript
- oreilly.com?
,
13.

14

JavaScript

JavaScript D O M .
JavaScript

.

JavaScript . 4
, , ,
, ,
, ( true,
fal se).
14.1 .
d,
( <br />
).
14.1.

<script>
document.write(":
document. writeCb:
document.writeC'c:
document.writeC'd:
/script>

" +(42 >


" +(91 <

3) + "<br />")
4) + "<br />")

" +(8 == 2) + "<br />")


" +(4 < 17) + <br />")

339

:
a:
b:
:
d:

true
false
false
true

, : d: true, b: :
fal se. ( 1
), JavaScript true false.
JavaScript
true, ,
fal se: fal se, 0, -0 , , nul 1, '
(undefined) NaN (Not a Number ,
,
).
, , , JavaScript true false
.
, true ,
, ,
TRUE :
i f (1 == true: ccc^ent.writeCtru e ') //
i f (1 == TRUE; :::^ent.write('TRUE') //

--4-

iK

----------------------------------------------------------------------------------------------

, ,; ,
HTML-, * <script> </script>.

----------------------------------------------------- 1----------------------------------------


, ,
, , 22 Enter.
,
. , ,
.
14.2 , ,
' .
14.2.

2 ~

<script>
myname = "Pete^
myage = 24
document.write;5:
document.write("3:
document.write."::
document.write("c:
document.write e:
</script>

" - 42
r - "Hi
- true
+myname
" - '

+"<br
+"<br
+"<br
+"<br
+ "<br

/>") //
/>") //
/>") //
/>") //
/>")//

340

14. JavaScript

, ,
:
:
:
:
d:
:

42
Hi
true
Peter
24

,
.
.
14.3 .
366 - day_number days_to_new_year,
,
days_to_new_year < 30 true.
14.3.

JavaScript

<script>
days_to_new_year = 366 - day_number:
i f (days_to_new_year < 30) document.writeCCKopo !")
</script>

JavaScript ,
, ,
. . (. 14.1).
14.1. JavaScript

+b

+b

= b + 23

12 9

<b
++

&& b

+ ''

.
, (++)
(-), .
, JavaScript
( , , ),
.

341

(ternary) , ? : ,
if,
.
.


, JavaScript ,
,
, .
. 14.2 JavaScript,
.
14.2. JavaScript, (
)

()

()

+ + --

+ - ~ !

* /%

<<


>>

<>
==

<=
1=

>>>

>=
===

!= =

&

&&

II

? ;

II

II
V
V

II

II
#

II
*
II
II
1
II
II <
+
II

II

66
t

JavaScript .
.
.

. , , ,
0:
level = score = time = 0


, ,

342

14. JavaScript

. . 14.3 ,
.
14.3. ,

New

+ + --

+- ~

? ;
II

II
V
V

II
1

II
+

II
II

II
#

II
II <

II
II



, true, false.
: , .


== (
=). 14.4 ,
.
, month July
October .
14.4.
<script>
month = "July"
i f (month == "October") document.writeC'Its the Fall")
</script>
,
JavaScript , .
, , ,
. 14.5 b
( , ),
, - i f .
14.5.
<script>
= 3.1415927
b = "3.1415927"
i f ( == b) document.writeCT')
i f (a == b) document .write("2")
</script>
, , ,
1, , i f t rue.

343

, b
,
3.1415927.
i f
,
JavaScript. , b
, .
, ,
, ,
JavaScript,
.


,
. JavaScript > (
), < (), >= ( ) <= ( ). 14.6
.
14.6.

<script>
= 7; b = 11
i f (
> b) document.w ri te ( "
i f (
< b) document.w ri te ( "
i f (a >= b)document.w ri te ( "
i f (a <= b)document.w ri te ( "
</script>

b<br />")
b<br /> )
b<br />")
b<br />")

7, a b 11,
( 7 11, *11):
b
b


,
. JavaScript
(. 14.4).
14.4. JavaScript

&&

() (true),

II

() (true),

() (true),
, (false),

344

14. JavaScript

14.7 ,
0,1 true.
14.7.

<script>
= 1: b =

document.write(( && b) + "< />")


document.write(( || b) + "<br />")
document.write(( !b ) + <br />")
</script>
&& true ,
true. 11 true ,
true,
b , 0 true.
11 ,
,
true. 14.8 getnext
, finished 1.
14.8. , ||

<script>
i f (finished == 1 || getnext == 1) done = 1
</script>
, getnext
i f, , 14.9.
14.9. i f . . . . !

getnext
<script>
gn = getnextO
i f (finished == 1 || gn == 1) done - I
</script>

getnext , ,
gn i f .
. 14.5
. , ! true fa 1se,
!false true.
14.5. , JavaScript

&&

II

true

true

true

true

true

false

false

true

false

true

true

true

false

false

false

false

onerror

345

with
with , , ,
JavaScript. (
, ),
JavaScript, .
, with
.
14.10, document .write
string .
14.10. with
<script>
string = " "
with (string)
{
document.write(" " + length + " <br />")
document.write(" : " + tollpperCaseO)
}
</script>
, document .write
string, :
55
:

: JavaScript ,
length tollpperCaseO -
. , ,
string, with.

onerror
, .
onerror, try catch,
JavaScript .
, > JavaScript.
- ,
JavaScript. , onclick,
button (), ,
, . 14.11
, onError.
14.11. , onerror
<script>
onerror = errorHandler

346

14. JavaScript

document.writ(" -!") //
function errorHandler(message, u r l. line)
{
out ="K , .\n\n":
.out += ": " + message + "\n";
out += "URL: " + url + "\n";
out += ": " + line + "\n\n";
out += " OK . ,":
alert(out):
return true:
}
</script>

errorHandler. :
, U R L - ,
alert.

: document .writ document, write (
). . 14.1
. onerror
.

1Mqzifta Firefox

L8J

1 i l l http://!ocalhost/wetyonerror.htrnl

http://localhost :

V.J

~:

fx~|

, .
: document.writ is not a function
URL: http://locatyt/web/onefror.html
: 7
OK .

J localhost..'

. 14.1. onerror alert

trycatch
, try catch,
, onerror,

347

.
, , .
,
onerror.
t r y .. .catch
,
, ,
.
, 17 Ajax,
XMLHttpRequest. , Internet Explorer
( ).
try catch,
-
. , 14.12.
14.12.

try catch

<script>
try
{
request = new XMLHTTPRequestO
}
catch(err)
{
//
// XML HTTP Request object
}
</script>
Internet
Explorer , , . try
catch f 1nal 1. ,
, , ,
try.
, catch -,
:
finally
{
alertC'Bbm 'tr y '." )
}

.
- .
, : i f, switch
?.

348

14. JavaScript

if
i f .
,
true. i f
, , ,
. :
i f ( > 100)
{
=2

document.write(" 100")
}
i f (b == 10) document.writeC'b 10")

else
, el se
:
i f ( > 100)
{
document.write(" 100")
}
else
{
document .writeCa 100")
}
JavaScript, , elseif,
el se,
i f , el sei f :
i f (a > 100)
{
document.write(" 100")
}
else if(a < 100)
{
document.write("a 100")
}
else
{
* document.write(" 100")
}
el se i f
i f . .
,
:

349

i f ( > 100) document.write(" 100")


else i f ( < 100) document.write(" 100")
else document.write(" 100")

switch
switch ,
,
. ,
, 4,
JavaScript.
, , .
, : Home, About, News,
Login Links page ,
, .
, i f . . .e ls e if ...,
, 14.13.
14.13. if...e ls e if

<script>
if
else i f
else i f
else i f
else i f
</script>

(page == "Home")
(page =="About")
(page == "News")
(page =="Login")
(page =="Links")

document.write("
document.write("
document.write("
document.write("
document.writeC'Bbi

Home")
About")
News")
Login")
Links")

switch ,
14.14.
14.14. switch

<script>
switch (page)
{
case "Home":
break
case "About":
break
case "News":
break
case "Login":
break
case "Links":
break
}
</script>

document .writer ")


document. writeC About")
document, writer News")
document .writer Login")
document .writer Links")

page swi tch.


case.

350

14. JavaScript

. ,
,
, .

switch
14.14, , , , break
switch
. , ,
case, , break.


d efau lt switch
,
. 14.15 ,
14.14.
14.15. default, . 14.14
default: document.write(" ")
break

?
, (?),
(:),
i f . . .el se. ,
? , , true.
: , ,
fal se.
14.16 ,
, 5,
,
.
14.16.
<script>
document.write(
a <= 5 ?
" 5" :
" 5"

)
</script>


, , , :
size = <= 5 ? "" : ""

351


JavaScript . whi 1, do ... whi 1 for.

while
JavaScript whi 1 ,
,
true. fal se,
Javascript ( ).
,
, ,
false, . 14.17.
14.17. while

<script>
counter=0

while (counter < 5)


{
document.writeCCneTHHK: " + counter + "<br />")
++counter

}
</script>

:
:
:
:
:
:

1
2
3
4

counter ,
, -
Esc
. JavaScript
.

do...while
, , ,
, do... whi 1,
whi 1, ,
.
7 , 14.18.

352

14. JavaScript

14.18. do...w hile


<script>
count = 1
do

{
document.write(count + " 7 + count * 7 + "<br />")
} while (++count <= 7)
</script>

, :
1
2
3
4
5
6
7

7
7
7
7
7
7
7

7
14
21
28
35
42
49

fo r
for
, :
;
Q ;
.
: for (1;
2: ).
. 7
count 1.
( count <= 7),
,
true.
. 7
count . 14.19
.
14.19. for

<script>;
for (count = 1 ; count <= 7 ; ++count)

{
document.write(count + " 7 " + count * 7 + "<br />");

}
</script>

PHP, for
, :
for (i = 1. j = 1 : i < 10 : i++)

353


:
for (i = 1 : i < 10 : i++. --j)
:
for (i = 1. j = 1 ; i < 10 : i++, --j)


break, switch
, for. ,
. ,

. break 14.20.
14.20. break for
<script>
haystack = new ArrayO
haystack[17] = "
for (j = 0 ; j <* 20 ; ++j)
(
if (haystack[j] == "")
{
document.write("<br />- " + j)
break
}
else document.write(j + ". ")
}
</script>
:
0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.
- 17

continue
, ,
.
continue. 14.21.
14.21. continue for
<script>
haystack
= new ArrayO
haystack[4] = ""
haystack[ll] = ""
haystack[17] = ""
for (j = 0 ; j < 20 ; ++j)

354
{

14. JavaScript

if (haystack[j} == "")
{
document.write("<br />- " + j + "<br />")
continue
}

document.write(j + ". ")


}
</script>
, document write
else ( ),
, continue
. :
0: 1. 2. 3 .

- 4
5. 6. 7. 8. 9, 10.
- 11
12, 13. 14. 15. 16.
17
18. 19.


, JavaScript ,
(int) (float). ,
, JavaScript,
. 14.6.
14.6. , JavaScript

Int, Integer

parselnt()

Bool, Boolean

BooleanQ

Float, Double, Real

parseFloat()

String

String()

Array

splitQ

, ,
( 3):
= 3.1415927
i = parselnt(n)
document.write(i)
:
document.write(parselnt(3.1415927))

355


.
JavaScript , .


1. JavaScript?
2. ,
?
3.
?
4. (===)?
5. ?
6. .
7. i f whi 1 ,
, ?
8. for whi 1?
9. wi th?
10. JavaScript
?
,
14.

4 * ,
JavaScript
JavaScript ,
. JavaScript , ,
, D O M ,
HTML- , .
,
, ,
, JavaScript
.

JavaScript
JavaScript ( ),
write, , ,
document .write, .
-
, .


:
function _ ([ [. ...]])
{

}
, :
function;

, , ,
;
;
,
( ,
).

JavaScript

357

, get Input, GETI NPUT


getinput .
JavaScript :
, ,
.
getinput, ,
. bumpyCaps (
) camelCase ( ).
, ,
,
.
return,
.
return - ,
.


arguments.
, ,
, . , , displayltems.
15.1.
15.1.

<script>
displayltems("". ". "", "". "")
function di spl ayItems (vl. 2. v3', v4. v5)
{
document.write(vl + "<br />")
document.write(v2 + "<br />")
document.write(v3 + "<br />")
document.write(v4 + "<br />")
document.write(v5 + "<br />")
}
</script>

:


*:
-

, ?
document.wri te
. ,
^gjinents .

15. , JavaScript

358

15.2
.
15.2.
<script>
function displayltems()
{
for (j = 0 : j < displayItems.arguments.length ; ++j)
document.write(displayltems.arguments[j] + "<br />")
}
</script>
1ength,
, , j,
,
di spl ay Items .arguments. for
, ,
.
,
,
.


.

. fi xNames, 15.3, . arguments ( )
.
fi () ,
,
, .
15.3.
<script>
document.wnte(fixNames(the". "DALLAS". "CowBoys"))
function fixNames0
{
var s = ""
for (j = 0 ; j < fixNames.arguments.length ; ++j)
s += fixNames.arguments[j].charAt(0).tollpperCaseO +
fixNames.arguments[j].substr(l).toLowerCaseO + "
return s.substr(0, s.length-1)
}
</script>

JavaScript

359

, the, DALLAS CowBoys,


The Dal 1as Cowboys. .
( ) s,
. for

charAt tollpperCase.
, , JavaScript .

substr,
toLowerCase. substr,
,
:
substr(l. (arguments[j].length) - 1 )
, substr :
, 1 ( ),
( 1ength ).
, substr ,
, .

,
s.
s
substr. , substr,
, .
,
, :
fi xNames.arguments[j ] .substr(1).toLowerCa se()
, ,
. JavaScript
.
1. : fi xNames.
2. j.
3. substr 1.
,
.
4. , , toLowerCase.
. ,
, mixedCASE,
:
xedCase
' xedCase
* edcase

15. , JavaScript

360

: s
.
s return,
,
.
s .
(
), - ,
, JavaScript ,
.


15.3 . ,
?
, 15.4.
15.4.

<script>
words = fixNames("the", "DALLAS. "CowBoys")
for (j = 0 : j < words.length ; ++j)
document.write(words[j] + "<br />")
function fixNamesO
{
var s = new ArrayO
for (j = 0 : j < fixNames.arguments.length ; ++j)
s[j] = fixNames.arguments[j].charAt(0).toUpperCase() +
fixNames.arguments[j].substr(l).toLowerCaseO
return s
}
</script>
words
, fixNames. for
,
.
f i xNames,
15.3, , s ,
return.

, , ( The
Cowboys):
v.
words = fixNamesCthe, "DALLAS , "CowBoys")
document.write(words[0] + " " + words[2])

JavaScript

361

JavaScript
,
, JavaScript ,
.
.


, ,
, . ,
, .
, , , , ,
, .
, User,
.
.
( ,
) .
.
15.5 User, :
- forename, username password.
- showUser.
15.5. User
<script.>function User(forename, username, password)
this.forename = forename
this.username = username
this.password = password
this. showUser = functionO
{
document.writeC'l/lMfl: " + this.forename + "<br />")
document.write(" : " + this.username + "<br- />")
document.write(": " + this.password + "<br />")
1
script>
.
this.
User, thi s
.
, User
forename . .

362

15. , JavaScript

0 showUser.
, . - showUser
User. , showUser user.
,
, ,
bumpyCaps
.
15.5
, ,
. 15.6 , ,
.
15.6.

<script>
function User(forename, username, password)
{
this.forename = forename
this.username = username
this.password = password
this.showUser = showUser
1
function showUserO
{
document.writeC'HMfl: " + this.forename + "<b^

'

document .wri te (,,ooaecoe : " + this, username + <br />")


document.write(": " + this.password + <br >")
}
</script>
,
,
.


User
:
details = new User("Wolfgang . "w.a.mozart". "composer")
:
details = new User
:
details.forename = "Wolfgang"
detail s.username = "w.a.mozart
detaiIs.password = "composer"

JavaScript

363

:
details.greeting = ""


:
document.write(detai1s .greeti ng)


,
:
name = detail s.forename
i f (details.username == "Admin") loginAsAdmin()

showUser, User,
,
detai 1s:
details.showUserO


:
: Wolfgang
: w.a.mozart
: composer

prototype
prototype
. User
. , ,
showUser . ,
,
. ,
:
this. showUser = functionO

:
User, prototype. showUser = functionO

15.7.
15.7.

prototype
<script>
function User(forename. username, password)

364

15. , JavaScript

this.forename = forename
this.username = username
this.password = password
User, prototype, showllser = functionO
{
document.write(": " + this.forename + <br />")
document^ : " + this.username + "<br />")
document.write (,,apob: " + this.password + "<br />")
}
}
</script>
,
prototype, ,
, .
.
, prototype
( ,
), :
User.prototype.greeting = ""
document,write(detaiIs.greeting)
User prototype,
greeti ng, . detai 1s
.
,
:
User.prototype.showUser = functionO { document.write(" " +
this.forename + " " + this.username + " " + this.password) }
detaiIs.showUser()
, (,
if), ,
showUser.
detai Is
detai 1s . showUser ,
showUser .


,
, ,
. JavaScript ,

. User
:
User.prototype.greeting = "
document.wri te (User.prototype.greeti ng)

365

JavaScript

JavaScript
prototype
. , ,
,
.
JavaScript String :
String.prototype.nbsp =
function { return this.replace(/ /g. &nbsp: ) }

&nbsp: replace (. 16).
:
document.write(" ",nbsp())
: &$;&
sp:. ,
, (
):
String.prototype.trim =
function { return this.replace(/^\s+|\s+$/g. ) }
,
. (
):
document-.writer

".trim O)

, /
, g .
A\s+
, ,
\s+$
, .
|
.

,
.

JavaScript
JavaScript ,
.

.

366

15. , JavaScript


, :
arrayname = new ArrayO
:
arrayname = []



, :
$arrayname[] = " 1";
$arrayname[] = " 2";
JavaScript push:
arrayname.push(" 1")
arrayname. 2")
, .
, ,
length:
document.write(arrayname.1ength)
,
, :
arrayname[0] = " 1"
arrayname[l] - " 2"
15.8 , ,
, .
,
<script>
numbers = []
numbers.push("")
numbers.push("")
numbers. pushC'Tpn")

15.8.

for (j = .0 ; j < numbers.length ; ++j)


document.write(" " + j + " = " + numbers[j] + "<br />")
</script>
:
0 =
1 =
2 =

array
Array
:

367

JavaScript

numbers = Array("". "". "")


.

, JavaScript
, .
.


,
, .
, , !
(:) ,
. 15.9 ,
(balls) -
.
15.9.

<script>
b a lls = {"":
"":
"":
"-":

"
. 6".
"
. 3".
" . 1".
" -, 12 ."}

for (ball in balls)


document.write(ball + " = " + balls[bal1] + "<br />")
</script>


for, in.
, (
ball), ,
in ( bal 1s).
bal 1s, bal 1.
, ball,
balls.
:
= . 6
= . 3
= , 1
- = -, 12. .

,
(
, 1):
document.write(bal1s [ ''])

368

15. , JavaScript


JavaScript
. , ,
(8 * 8 ), 15.10.

<script>
checkerboard = Array(
Array(
Array(
Array(
Array(
Array(
Array(
Array(
Array(
))

15.10.

document.wri te("<pre>")
for (j = 0 ; j < 8 ; ++j)
{
for (k = 0 ; k < 8 ; ++k)
document.wri te(checkerboa rd[j][k] +
document.write("<br />")
}
document.wri te( "</pre>")
</script>

")

,
. for,
,
.
,
. ,
, [j ][], (
).
, .
<> </> :
0

0
0

0
0

0
0

0
0
0
0

0.

0
0
0
0


, :
document.write(checkerboard[7][2])

JavaScript

369

0 ,
,
, .


, ,
JavaScript
. ,
.

concat
concat . , . . :

fru it = ["", ""]


veg = ["". ""]
document.wri te ( fr u it.concat(veg))
, concat
.
concat, pets
....:
pets
= ["". "". ""]
more_pets = pets.concat("". "")
document.wri te(more_pets)

forEach ( IE)
JavaScript forEach
, ,
foreach, ,
Internet Explorer. ,
, .
, 15.11.
15.11. forEach

<scr~ ~>
pets = I"". "". "", ""]
pets.~orEach(output)
function output(element. index, array)

{
document.write(" " + index + " " +
element + "<br />")

}
</scnpt>

, forEach, output.
: , . ,

15. , JavaScript

370

.
document .write.
, :
pets.forEach(output)
:

0
1
2
3

forEach (- )
, Microsoft
forEach, ,
Internet Explorer. - , IE , pets.
f or Each (output) :
for (j = 0 : j < pets.length ; ++j) output(pets[j]. j)

join
join ,
,
. 15.12 .
15.12. join
<script>
'pets = ["", "". "". ""]
document.write(pets.joinO
+"<br />")
document.write(pets.join( )
+"<br />")
document.write(pets.join( : ') +"<br />")
</script>
, join
,
join . 15.12 :
..,

: : :

push pop
push .
pop.
.
15.13.
15.13. push pop
<script>
sports = ["". "". ""]

JavaScript

371

^*: ite( " = "


+ sports + "<br />")
sports.push("Hockey")
d c c y ^ t.w r ite ( " = " + sports + "<br />")
removed = sports.pop()
z z c ^ e r i .write( " = " + sports + u<br />")
ccc^rert.wrue( " = "
+ removed + "<br />")
< 5CrlDt>

.
sports,
, ,
. document .w rite
.
:
= ..
= ...
= ..
' =

15.14, push pop ,


- ,
.
15.14. push pop *
<script>
numbers = []
for (j=0

j<3 : ++j)

{
numbers.push(j):
document.write(" " + j + "<br />")

}
// -
document.write(n<br />")

document.write (,ae " + numbers.pop() + "<br />")


document.write(" " + numbers.pop() + "<br />")
document.write (,,ae " + numbers.pop() + "<br />")
</script>

:

1
2
2
1

372

15. , JavaScript

reverse
reverse
. 15.15.
15.15. reverse
<script>
sports = ["". "". "". ""]
sports, reversed
document.wri te (sports)
</script>
,
:
...

sort
sort . 15.16
.
15.16. sort
<script>
//
sports = ["". "". "". ""]
sports.sort
document.write(sports + "<br />")
//
sports = ["". "". "", ""]
sports.sort( ) . reverse()
document.write(sports + "<br />")
//
numbers = [7. 23, 6, 74]
numbers.sort(function(a,b){return a - b})
document.write(numbers + "<br />")
//
numbers = [7, 23. 6. 74]
numbers.sort(function(a.b){return b - a})
document.write(numbers + "<br />")
</script>

, , reverse,
.

. ,
. function,

373

,
( showUser).
functi on , sort.
, ,
. ,
, b . ,
b , .

.
( - b b - )
15.16
.
JavaScript.
,
.
, ,
.


1. JavaScript
?
2. ,
?
3. .
4.
?
5.
?
6. ?
7.
?
8. ?
9. ?
10. .
,
15.

1 f i
JL v
JavaScript

JavaScript .

.
, a JavaScript --
,
.
,
,
.

JavaScript, .

,
, JavaScript
JavaScript
, -, ,
, , ,
, JavaScript.
,
- .
, JavaScript
, ,
JavaScript , .
, JavaScript,
,
,
,
.

, , JavaScript

375

validate.html ( )
,
-,
. , , , ,
. 16.1 ,
.
16.1. JavaScript ( )

<html><head><ti 11> </1i 11e>


<-style>.signup { border: lpx so lid #999999:
font: normal 14px helvetica: col or:#444444: }</style>
<script>
function validate(form) {
f a i 1 = validateForename(form.forename.value)
f a il += validateSurnameCform.surname.value)
f a il + validateUsername(form.username.value)
f a il += validatePassword(form.password.value)
f a il += validateAge(form.age.value)
fa il -h= validateEmail(form.email.value)
i f ( fa il = "") return true
else { a le r t( fa il) : return false }

>
< /s c rip t> < /h e a d > < b o d y >

<table class=,,signup" border="0" cellpadding="2


cellspacing="5" bgcolor=#eeeeee">
<th colspan="2" align=,,center,,>PerncTpaunoHHafl $opMa</th>
<form method=,,post" action="adduser.php
onSubmit="return v a lid a te (th is)>
<tr><td>MMfl</td><td><input type="text" maxlength=!,32
name^'forename" /></td>
</tr><tr><td>a</td><td><input type="text" maxlength="32"
name="surname" /></td>
</tr><tr><td>ooaecoe HMfl</td><td><input type="text" maxlength=,'16"
name="usernamen /></td>
</tr><tr><td>napoflb</td><td><input type="text" maxlength=,,12"
name=password" /></td>
< /tr > < tr> < td > B 0 3 p a c T < /td > < td > < in p u t t y p e = " t e x t M m a x le n g th ^ 'S "
=,, / > < /t d >

</tr><tr><td^eKTpoHHbm aflpec</td><td><input type="textM maxlength=n64"


name="emai1" /></td>
</tr><tr><td colspan=2M al ign="center,,>
<input type="submit" 1=,, /></td>
</ t r > < /fo r m > < /ta b le >

,
,
. , , ,

376

16. JavaScript

val i date. html, , ,

. 16.1.

1 - Mozilla Firefox

f- | ] |X j

(Q

http://localhost/web/validate.html

^ ^j

|
~|
]

| ^

. 16.1. , 16.1


, .
CSS,
.
, JavaScript.
<script> </script> validate,
, , ,
. . , ,
, , .
,
.
,
true, fal se. , val i date,
: false,
.
.
true, ,
.
HTM L ,
. H TM L
, onSubmit="return v a lid a te (th is ),
<form>. onSubmi t

, , JavaScript

377

.
true, fa l se, ,
.
th is (< ).
validate,
form.
, H T M L - JavaScript ,
return, onSubmit. ,
JavaScript ,
onSubmit HTML.

validate.html ( )
16.2, ,
.
, val i date.
html. H T M L- <^-
. ,
<5>-, 16.1.
16.2. , JavaScript
<script>
function validateForenameCfield) {
i f ( fie ld = "") return "He .\
return ""

}
function validateSurname(field) {
i f ( fie ld = "") return "He .\n"
return ""

}
function validateUsername(field) {
i f ( fie ld == "") return "He .\n"
else i f (fie ld .le n g th < 5)
return " 5 .\"
else i f (/[Aa-zA-Z0-9_-]/.test(field))
return " a-z, A-Z, 0-9. - _.\"
return "

}function validatePassword(field) {
i f ( fie ld == "") return "He .\n"
else i f (fie ld .le n g th < 6)
return " 6 .\"
else i f ( ! / [a - z ]/.te s t(fie ld ) || ! /[A -Z ]/.te st(fie ld ) ||
!/[0-9]/.t e s t ( f ie ld ) )
return " 1 a-z, A-Z 0-9.\"
return ""

378

16. JavaScript

function validateAge(field) {

i f (isNaN(field)) return "He .\n"


else i f (field < 18 11 field > 110)
return " 18 110.\"
return ""

function validateEm ail(field) {

i f (field == "") return "He .\n"


else i f ( ! ( ( f ie ld .indexOf(".") > 0) &&
(field.indexOf("@") > 0 )) ||
/ [Aa-zA-Z0-9.@_-]/.test(field))
return " .\n"
return ""
}
</scri pt></body></html>
, , ,
validateForename.


. validateForename field,
(forename), val i date.
, ,
, , ,
.
,
val i dateForename, .
, ,
,
, , -,
,
.


validateSurname validateForename,
, (surname)
.
, ,
, . .


val i datellsername ,
. ,
a-z, A-Z, 0-9, _ -, ,
.

, , JavaScript

379

i f . . .else
, .
, ,
.
JavaScript- test,
( ,
) (. ).
, test true,
validateUsername .


val i datePassword.
,
. ,
.
, , ,
,
, test ,
.
false, , ,
.
, , .


val idateAge ,
( i sNaN)
18 110 .
.
.


,
validateEmail.
-
JavaScript- i ndexOf.
(.), ,
.
, test,
.
, .
,
, , @. ,
test. ,
, .
.

16. JavaScript

380

. 16.2
.
- Firefox

Qp-

1 Q :file:///:/web/validate.html

[ JavaScript]

.
.
.
.
18 110.
.

G O

. 16.2. JavaScript-

JavaScript
,

JavaScript (
<scri pt> </scri pt>!). val i date_
functions. js 16.1,
:
<script s="va1idate_functions.jsn></script>


,
,
JavaScript, .
.

,
(/).
, ,
. , (*) (
) , ,

381

Windows. : ,
,
.
, Le Gui ,
, . - (-,
, , )
:
The

difficulty

of

classifying Le

Guin's

works

To LeGui ,
Le Gui , .
:
/Le *Guin/
, Le Gui , ,
.
- , .
, , Le Guin?
, .
, .
(+),
:
/Le +Guin/


(.),
, .
, H T M L-, <
>.
:
/<.*>/
, (*)
,
: , < >,
.
<>, <em>, <br /> . .
, <>,
* +:
/<.+>/

, : , <
>, .

382

16. JavaScript

<> </>, <hl> </hl,


, :
< href="www.mozilla.org">
,
> , :
<1><></></111>
!
.
&

rVr*5? J

+ *,
,
, <> <i>, <> <textarea>.

, ( .) ,
, (\),
,
.
, ,
5.0, :
/5\./
,
(
).
,
.
.
5.0, 5.,
.
5.00,5. . .,
. :
/5\.0*/


, ,
, , . ,
:
1.000
1 .000.000
1 .0 0 0 .0 0 0 . 0 0 0
1 .0 0 0 .0 0 0 .0 0 0 . 0 0 0

383

, ,000
, .
:
/1C,000)+ /
: -
. 1,00.000 1.000.00
, 1,
, .
, ,
. 1,000.00
,
1.000, ,00 .
,
.


, ,
.
:
.

[]. , ,
, .
.
, ,
gray grey, :
/[]/
, .
: , ,
.
.


(-).

, :
/[0-9]/

, \
<

:

384

16. JavaScript


. ()
.
: ,
. , Yahoo,
. (
!)
:
/Yahoo[A!]/
,
. -
. , , Yahoo
, - ,
.
( , ), .



HTML.

, - , <>
</>, , :
< href="www.mozil1a.orgn>
:
/<[->]+>/
,
- .
. . 16.3
.
:
/ , , ;
< HTML. ,
;
[>] .
> : ,
;
+ ,
[>],
;

385

> HTML. ;
/

, .

.
,

,
HTML.

.

,
[>]

,
HTML.

.
,

. 16.3.
* -

_______________________________________________________________________
HTML
* . ^ , .
,
.
, http://tinyurl.com/
aboutregex.

16.1,
val idateUsername:
/[Aa-zA-Z0-9J/
. 16.4 .
:
/ , , ;
[ , ;
*

: , ;

a z ;

A-Z ;

0-9 ;

_ - ;
] , ;
/

, .

386

16. JavaScript

.
,

a -z

A-Z

0 -9

. 16.4. , validateUsername
.
, . ( )
,
,
. , ($ )
,
.

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


: , ,
, , . ,
, , Le Guin?
,
:
/. *Guin$/

387


. 16.1 , .
16.1.

[ ]

[ ]

{ re g e x )

re g e x (, )

: *, + ?

[1-]

\d

\D
\
n
\
s

\s

\
t

\w

, (a-z, A-Z, 0-9 _)

\W

, (, a-z, A-Z,
0-9 J

\x

(, ,
)

{}

{,}

{ m in, m ax}

m/

m ax

/[ zA
ZU-9_] / , /[A\w]/,
( w )
/, A-Z, 0 9
,
/. ( W ) ,

388

16. JavaScript

a-z, A-Z, 0-9 _.


/[\W]/.
, ,
. 16.2 ,
.
16.2.

The quick brown

nec[ei][ei]ve

receive, recieve ( receeve reciive)

rec[ei]{2}ve

receive, recieve ( receeve reciive)

rec(ei|ie)ve

receive, recieve ( receeve reciive)

cat

cat I like cats and dogs

cat |dog

cat dog I like cats and dogs

\
5\.0*

. ( \ , . )

[a-f]
cats$

, , , d, f
cats My cats are friendly cats

Amy

my my cats are my pets

\d{2,3>

- ( 00 999)

5., 5.0, 5.00, 5.000 . .

7(,000)+

7,000; 7,000,000; 7,000,000,000; 7,000,000,000,000 . .

[\w]+

[\w]{5>


:
/ .
,
, ;
/i .
/[a-zA-Z]/ / [a-z]/i /[A-Z]/i;
/ , ( )
($)
.
*
, $ .
, /cats/g
cats I like cats and cats like me. /dogs/
gi dogs (Dogs dogs)
Dogs like other dogs,
.

389


JavaScript
JavaScript : test
( ) replace. test ,
, repl
, ,
. , replace
, .
,
true, , cats :
document.write(/cats/i .testCCats are fun. I like cats."))
cats dogs,
. (/),
, (/i),
, (Cats):
document.writeC'Cats are fun. I like cats.".replace(/cats/gi."dogs"))
,
: ,
, Cats dogs, Dogs.


,
: pregjnatch, preg_match_al 1 preg_repl .
cats ,
,
oregjnatch:
Sn = pregjnatchC/cats/i". "Cats are fun. I like cats.");
P H P 1 TRUE 0 FALSE,
$ 1.
, ,
. pregjnatch ,
, ,
:
$n = pregjnatchC/cats/i". "Cats are fun. I like cats.". Smatch):
echo " $n: $match[0]";
( Smatch).
, ,
, , ,
Smatch[0].

390

16. JavaScript

,
:
1: Cats

, preg match a 11:


$n = preg_m atch_all("/cats/r. "Cats are fun. I lik e cats.". Smatch);
echo " $n: ":
for ($j=0 : $j < $n : ++$j) echo Smatch[0][$j J ."

, Smatch $match[0]
,
.
for.
, preg_
repl . cats, ,
dogs:
echo preg_replace("/cats/in. "dogs". "Cats are fun. I lik e cats."):

, .
?' 4 , http://

tinyurl.com/wikiregex.


-
. HTML-
v a lid a te .html, P H P - adduser.php,

, JavaScript
JavaScript .
, adduser. php.
,
, , .
, , 16.3.
16.3. adduser.php
<?php // adduser.php
//
$forename = Isurname = $username = Spassword = Sage = Semail =
i f (isset($_P0ST[ forename']))
$forename = fix_string($_POST['forename']):
i f (isset($_POST['surname']))
$surname = fix_string($_POST[' surname ]);
i f (isset($_P0ST[ username']))

Susername = fix_string($_POST[,username ] ) :
i f (is s e t($_P0ST[' password ]))

Spassword = fix_string($_POST[*password']);
i f (isset($_P0ST[' age']))
Sage = fix s trin g C S P O S T C a g e ']):
i f (isset(S_POST['email']))
Semail = fix_string($_POST['eman']):
S fa il
$ fa il
$ fa il
S fa il
S fa il
S fail

=
.=
.=
.=
.=
.=

validateforename(Sforename):
validatesurname(Ssurname);
validate_username(Susername):
validate_password($password):
validate_age(Sage):
validateem ail(Sem ail):

echo "<html><head><title>npHMep </1>":


i f (Sfail =

"") {

echo "</head><body>npoBepKa : Sforename.


Ssurname. Susername. Spassword. Sage. Semail.</body></html>":
//
exit;

>
// HTML JavaScript
echo <_END
<!-- HTML -->

<style>.signup { border: lpx solid #999999;


font: normal 14px helvetica: color:#444444: }</style>
<script type="text/javascript>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += val idatellsername( form, username, value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
i f (fail == "") return true
else { a le rt(fa il); return false }
}
</script></head><body>
<table class="signupM border="0" cellpadding="2"
cel 1spacing=M5" bgcolor=,,#eeeeee">
< th c o ls p a n = ,,2" a l i g n = ,,c e n t e r M>PerncTpaunoHHafl $opM a</th>

<tr><td colspan="2">K , <br />

391

392

16. JavaScript

: <pxfont color=red size=l><i>$fail</i></font></p>


</td></tr>

<form method="post" action="adduser.php"


onSubmit="return validate(this)">
<trxtd>l/lMfl</td><td><input type="text" maxlength="32"
name="forename" value="$forename" /></td>
</tr><trxtd>a</td><td><input type="text" maxlength=,,32"
name="surname" value="$surname" /></td>
<^><^> HMfl</td><td><input type="text" maxlength="16"
name="username" value="$username" /></td>

</tr><tr><td>apob</td><td><input type="text" maxiength="12"


name="password" value=,,$password,, /></td>
</tr><tr><td>Bo3pacT</td><td><input type="text" maxlength="3"
name="age" value="$age" /></td>
<><><^> aflpec</td><td><input type="text" maxlength="64"
name="email" value="$email" /></td>
</tr><tr><td colspan=M2 align="center">
<input type="submit" 1="" /></td>
</tr></form></table>
<!-- JavaScript -->

<script type="text/javascript">
function validateForename(field) {
i f (field == "") return "He .\\n"
return ""
}
function validateSurname(field) {
i f (field == "") return "He .\\n"
return ""
}
function validatellsername(field) {
i f (field == "") return "He .\\n"
else i f (field.length < 5)
return " 5 .\\"
else i f (/[^a-zA-Z0-9_-]/.test(field))
return " a-z, A-Z, 0-9. - _.\\"
return ""
}
function validatePassword(field) {
i f (field "") return "He .\\n"
else i f (field.length < 6)
return " 6 .\\"
else i f ( !/[a-z]/.test(field) || ! /[A-Z]/.test(field) ||
! /[0-9]/.test(fi eld ))

return " 1 a-z. A-Z 0-9.\\"


return ""

}
function validateAge(field) {
i f (isNaN(field)) return "He .\\n"
else i f ( fie ld < 18 11 fie ld > 110)
return " 18 110.\\"
return ""

}
function validateEmai1(fie ld ) {
i f ( fie ld == "") return "He .\\n"
else i f ( !((fie ld .in d e xO f(".") > 0) &&
(field.indexOf("@ ) > 0)) ||
/pa-zA-Z0-9.@_-] / .test ( f ie ld ))
return " .\\"
return "

}
</script></body></html>
END:
/ / - -
function v alidateforenam e(lfield ) {
i f ($ fie ld = "") return "He < />":
return
:

}
function validate_surname($field) {
i f ( I fie ld = "") return "He < />":
return

}
function validate_username($field) {
i f ( I fie ld = "") return "He />".
else i f (strle n ($ fie ld ) < 5)
return " 5 < />":
else i f (pregm atchC '/Pa-zA-ZO ^ -]/". I fie ld ) )
return " , . - _<br />
return
:

}
function validate password(Sfield) {
i f ( I fie ld = "") return "He < />":
else i f ( s tr le n ( lfie ld ) < 6)
return " 6 < /> :
else i f ( !preg_match(,7 [ a - z ] / " . I fie ld ) ||
!preg match("/[A-Z]/". I fie ld ) jj

394

16. JavaScript

!pregjnatch(7 [0 -9 ]/". $ fie ld ) )


return " 1 a-z
return

A-Z 0-9<br />":

}
function validate^age($field) {
i f ($ fie ld = "") return "He < />":
else i f (S fie ld < 18 11 $ fie ld > 110)
return " 18 110<br />
return "":

}
function validate_em ail($field) {
i f ($ fie ld = "") return "He < />".
else i f (!((strp os($ fie ld . ".") > 0) &&
(strpos($field. " ) > 0)) 11
pregjnatch(" / [^a-zA-Z0- 9 . "
$ field ))
return " < />":
return "":

}
function fix string($string) {
i f (ge tm ag icq uote sg p cO ) $string = strips'!ashes(Sstring);
return htm lentities (Sstring):

}
?>
. JavaScript (
) . 16.5.
- , H T M L-,
,
, 16.1 16.2.
(, ,
- http://lpmj.net), ,
JavaScript.
.
. -,

f ix string, .
-, , H TM L 16.1.
- " ' END.
JNI):
,
. value
<input> (, valup="$forename").
,
,
.

395

Mozilla Firefox

ULl

h t t p : //lo c a lh o 5 t/v \'e b /a d d u 5 e r .p h p


.

& . . - _
<v:o & 1 * ; *3*doto a-z. A-Z 0-9

! James

-Jones

: .oe

jj icnes

jsecret

|_____________ |

-**

[) )cmes(i>mysite corn

ZZD
]

^ 1

. 16.5. , ,

hV

HTML-
, 16.1. ,
-, 16.3, HTML.
,
, .
JavaScript
JS.

, H T M L JavaScript
Ajax (Asynchronous JavaScript
And X M L JavaScript X M L),
JavaScript-.
-,
-.


1. JavaScript ,
?
2. JavaScript )?

396

16. JavaScript

3. ,
, ,
.
4. , fox,
fix.
5. ,
, , .
6. , JavaScript,
fox The quick brown fox.
7. , ,
the The cow jumps over the moon my.
8. H T M L
?
,
16.

4 " J
J . Ajax
Ajax 2005
JavaScript XM L* (Asynchronous JavaScript and XM L),
. , Ajax -,
-op , JavaScript,
.
Google Maps (. 17.1),
,
.

G oog le M acs -

Fjfe

V ie

P X
Web images

Maps

Goode
Maps

ookroarics

Toots

htdp

- -i

http://maps.google.com

Video Mail

more

Sion m | Help
Search Me

- esses addresses and places ol .ntsre^t. Lc-arr. nre;-?,

# EootI Sand;eUok

i: Transferring data from maps.googIe.com...

. 17.1. Google Maps Ajax

398

17. Ajax

Ajax
, -,
.

.

Ajax?
Ajax 1999 Internet Explorer 5,
ActiveX- XMLHttpRequest. Microsoft
ActiveX
, .
, ActiveX
, JavaScript.
Ajax,
, .
,
.
, Ajax, JavaScript.

XMLHttpRequest
- XMLHttpRequest, ,
,
.
XMLHttpRequest:
IE 5: request = new ActiveXObject("Microsoft.XMLHTTP");
IE6+: request = newActiveX0bject("Msxml2.XMLHTTP");
: request = new XMLHttpRequest().
, Microsoft Internet Explorer 6
, .
, 17.1, ,
.
17.1. - Ajax-
<script>
function ajaxRequestO
{
try // IE?
{
var request = new XMLHttpRequest()
}
catch(el)
{
try // IE 6+?

XMLHttpRequest

399

{
request = new Act'veXQb :ect("Msxml2.XMLHTTP")
}
catch(e2)
{
try // IE 5?

request = --e* -:tiveXObject("Microsoft.XMLHTTP)


el-

Ajax

}
returr
}
</script>
,
try. . .catch. 17.1
,
, try
Ajax- IE
':---. . ,
ZzZtn
. ,
.
, , Ajax
request fal se,
. , - Ajax,
JavaScript.
, XMLHttpRequest,
, .
() (),
. 17.1 17.2 .
17.1. XMLHttpRequest

onreadystatechange

,
readyState

readyState

, .
: 0 = ,
1 = , 2 = , 3 = 4 =

responseText

responseXML

, XML

status

HTTP,

statusText

HTTP,

400

17. Ajax

17.2. XMLHttpRequest

abort()

getAIIResponseHeaders()

getResponseHeader( )

open ( ' ', ' u r f , ' ')

HTTP- (GET POST),


URL-
(true false)

send ( )

setRequestHeader('1, '

')

,
, .
, : (
HTM L ) XML. ,
, POST GET, .
POST, :
H T M L JavaScript P H P -
Ajax. , ,
Web 2.0 Ajax.
JavaScript -
-,
.

Ajax POST-
url post. html 17.2,
.
17.2. urlpost.html

<html><head><titl> Ajax</title>
</headxbody><center />
<hl>3a DIV</hl>
<div id= i nfo' > ^! v>
<script>
params = "url=oreilly.com"
request = new ajaxRequestO
request.open("POST", "urlpost.php", true)
request. setRequestHeaderCContent-type".
"application/x-www-form-urlencoded")
request.setRequestHeader("Content-1ength". pa rams.1ength)
request.setRequestHeader("Connection". "close")
request, onreadystatechange = functionO

Ajax POST-

401

i f (this.readyState == 4)
{
i f (this.status == 200)
{
i f (this.responseText != null)
{
document.getElementBylcK in fo ') .innerHTML =
this.responseText
}
else a le rt(" Ajax: )
}
else alert( " Ajax: " + this.statusText)
}

}
request.send(pa rams)
function ajaxRequestC)
{
try
{
var request = new XMLHttpRequestO
}
catch(el)
{
try
{
request = new ActiveX0bjectC'Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObjectC'Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
return request
}
</scri pt></bodyx/html >
, ,
, , H T M L-,
. <div>-Ter ID info,
: .
, Ajax.

402

17. Ajax

Ajax-3anpoca -^~ POST.


params, , ,
= . Ajax- .
open, POST-
url post, php .
, ,
POST-.

readyState
Ajax-,
readyState. .
onreadystatechange ,
readyState !. Ajax

. ,
, ( ) .
,
readyState.

, .
request, onreadystatechange = functionO
{
i f (this.readyState == 4)
{
// -
}
}
- z - :
:

request.onreadystatechange = ajaxCal1back
function ajaxCallbackO
{
i f (this.readyState 4)
{
// -
}
}
. 17.1 , .
l i r *?:: :~
. ^
^ 4,

:--

- h i
, readyState -. K zc z*
--^
,
-:

, 200, . : 5

Ajax POST-

403

200,
, statusText.

, this.readyState, this.
status . ., request, request.
?*1 readyState request.status. ,
,
this .
J

, , , readyState 4, a status 200,


responseText. ,
.
<div> responseText:
document.getElementById(in fo ') . innerHTML = this.responseText
getEl ementBy ID
info, innerHTML ,
Ajax-.
Ajax-
- ,
, params:
request.send(params)

readyState. ajaxRequest 17.1 ,
JavaScript HTML.

Ajax-
P H P - ,
17.3. u r l post. php.
17.3. urlpost.php

<?php // urlpost.php
if (isset($_P0ST['url'])) {
echo file_get_contents("http: / / " .SanitizeString($_P0ST['url' ]));

'unction SanitizeString(Svar) {
$var = strip_tags($var).;
Svar = htmlentities($var);
return stripslashes($var);
>
,
SanitizeString,
.

404

17. Ajax

-, URL-,
POST- $_P0ST['url'], PHP- file_
get contents. ,
- ,
, .
- url post,
html, oreilly.com,
<di >-, .
, -,
: ,
. , . 17.2.
1.^[5

AJAX POST Example -Manila firefox

gtHt

Hgbxy fiookmwte Joote

( L i Ihttp://toca<hort/uriposthtml

Loading a web page into a DIV

OREILLY'
Search

NEWS & COMMENTARY

POPULAR TOPICS
Actionscnpt
Apach*
CSS
Head First
Java
Linux
MySQL
P*ri
Photoshop
Ruby
XML

Afax
C#
Flex
iPhon*
JavaScript
Missing Manuals
Open Source
PHP
Python
Wb 2.0

BROWSE BOOKS
Business & Culture

Personal Finance

[Archive I Audio I Video I Popular Tags]

ETech Preview: Science Commons Wants


Data to Be Free

John Wilbanks has a passion for


lowering the barrier between
scientists who want to share
information. A graduate of Tulane
University, Mr. WHbanks started
his career working as a
legislative aide, before moving
on to pursue work in
btoinformatics, which induded the founding of Incellico, a
company which built semantic graph networks for use in
pharmaceutical research and development Hr. Wilbanks now
serves as the Vice President of Science at Creative
Commons, and runs the Science Commons project. He will
be speaking at The O'Reilly Emerging Technology
Conference in March, on the challenges and
accomplishments of Science Commons, and he's joining us
today to talk a bit about it. Read m o re.

- Co ; Search Tip*

REGISTER NOW AND SAVE!


ETech
ETech Living,
Reinvented: The Technology
of Abundance and Constraints.
Happening March 9-12 in San
Jose, CA. Re giste r Now and
S a v e up to $300!
Web 2.0
W eb 2.0 Expo
Expo
S an Fra n cisco
The Power of Less.
Happening March 31-April 3 in
San Francisco. R e giste r Now
and S a v e up to $3501
Upcom ing C o n feren ces

Stay Connected

O'Reilly on YouTube
O'Reilly on Twitter
O'Reilly on Facebook
News Feed
New Titles Feed
Upcoming Titles Feed
I* New to RSS?

OReilly Emerging
Technology Conference
O'Reilly Web 2.0 Expo San
Fra no sco

O'Reilly RailsConf

I* More from Conferences

An Anonymous Reader
read:
Ba seb a ll H a cks
"S o m e su g g e stio n s to
readers**, Feb. 21 2009
Rating:

. 17.2. - oreilly.com, <>-

Ajax- ,
JavaScript,
-. ,
- oreilly.com Ajax
( P H P - ), ,
, -
Ajax.
.

GET POST

405

GET POST
GET-,
. :
GET-, POST-
. , -
, ,
. ,
,
, U R L-.
17.4 , ,
17.2,
Ajax POST-, GET-.
17.4. urlget.html
<html><head><titl> Ajax GET-3anpocoM</title>
</head><body><center />
<1> - 01\/-</111>
<div id= in fo > 3aMeHeH0</div>
<script>
nocache = "&nocache=H + Math.randomO * 1000000
request = new ajaxRequestO
request.open("GET". "urlget.php?url=oreilly.com" + nocache, true)
request .onreadystatechange = functionO
{
i f (this.readyState == 4)
{
i f (this.status == 200)
{
i f (this.responseText != null)
{
document.getElementById( in fo ) .innerHTML =
this.responseText
}
else ale rt(" Ajax: '')
}
else alert( " Ajax: " + this.statusText)
}
'equest. send (n u ll)
jnction ajaxRequestO
try
{

var request = new XMLHttpRequestO

406

17. Ajax

}
catch(el)
{
try
{
request = new ActiveX0bject("Msxml2.XMLHTTP")
1
catch(e2)
{
try
{
request = new ActiveXObject.("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
1
return request
}
</script></body></html>
,
, .
GET- .
open GET- U R L, ?,
url =orei 1ly . com.
Q &,
nocache
0 1 .
U RL-, .
send nul 1,
, POST-. ,
, .
-
, GET-. ur 1get. php,
, 17.5.

17.5. urlget.php

<?php
i f (isset($_GET[' u r l' ])) {
echo file jje tjro n ten tsC http ://" .sanitizeString($_GET[ 'u r l' ])):
>
function sanitizeString(Svar) {
Svar = strip_tags($var):

XML-

407

$var = htm lentities($var);


return strip s lashes(Svar):

?>
17.3 ,
S P0S1 S_GET.
ur 1g e t. html url post. html.

XML-
XMLHttpRequest,
XML.
Ajax -
,
, , XML.
, Ajax H TM L-,
,
.
-
XML.
P H P - xml get. php, 17.6.
17.6. xml get.php

-?php
f ( is s e t(S_GE1[ u r l '])) {

header( 'Content-Type: text/xml ):


echo fi le g e t contentsC"h t t p : / / . samtizeStrmg($_GET[ ' u r l ' j ) ) :

int. t. ion sam t.i/eString($var) {


Svar - s t n p t a g s ( S v a r ) :
Svar = htm le ntit i es($v a r ):
return strip s Iashes(Svar);


( ),
X M L -.
, , Ajax-
X M L -.
H TM L- xmlget.html, 17.7.
17.7. xmlget.html

><head><t.i11> XML Ajax</title>


^ead><body>
'I' XMI D1V-Vh2
>

408

17. Ajax

<div id=' in fo > 3aMeHeH0</div>


<script>
nocache = ,,&nocache=" + Math.randomO * 1000000
url = "rss.news.yahoo.com/rss/topstories"

request = new ajaxRequestO


request.open("GET. "xmlget.php?url=" + url + nocache, true)
out =

request .onreadystatechange = functionO


{
i f (this.readyState == 4)
{
i f (this.status == 200)
{
i f (this.responseXML != null)
{
t i t l e s = this.responseXML.getElementsByTagName('title')
for (j = 0 : j < title s .le n g th : ++j)

{
out += titles[j].childNodes[0].nodeValue + '<br />'

}
document.getElementById(' i nfo' ) . i nnerHTML = out

}
else a le rt(" Ajax: )
}
else a le rt( " Ajax: " + this.statusText)

request.send(null)
function ajaxRequestO {
try
{
var request = new XMLHttpRequest()
}
catch(el)
{
try
{
request = new ActiveX0bject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActiveXObjectC'Microsoft.XMLHTTP")
}
catch(e3)

409

XML-

request = false

}
}
}
return request
}
</scri pt></bodyx/htrnl >
,
, , ,
U R L - rss.news.yahoo.com/rss/topstories,
X M L -, Yahoo! News
Top Stories feed.
responseXML,
responseText. X M L -,
responseText nul 1, responseXML
X M L -.
responseXML X M L -
X M L -,
D O M -. , ,
, JavaScript- getElementsByTagName.

XML
X M L, , RSS-,
17.8. X M L ,
D O M - (. *17.3),
.

<rss>

<title>|

<linjc>JJ |<dwor^gtion>l
:

j<pubdbit|

. 17.3. DOM- 17.8

410

17. Ajax

17.8. XML
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0M>
<channel>
<title>RSS-n0T0K</title>
<1i nk>h ttp ://website.com</li nk>
<description>RSS- website.com </description>
<01>. 16 2011 . 00:00:00 GMT</pubDate>
<item>
<ti 11e>3a r0 H0 B0 K</ti 11e>
<gui d>h ttp :/ /websi t e .com/headli ne</gui d>
<description>3io 3ai^0B0K</descripti0n>
</item>
<item>
<title>3a 2</title>
<guid>http://website.com/headline2</guid>
< descripti> ^OBOK</descri ption>
</item>
</channel>
</rss>

, getEl ementsByTagName,
, ,
. 17.7,
:
t it le s = this.responseXML.getElementsByTagName('title')

t i t l e
t it le s .
( j ,
):
titles[j].childNodes[0].nodeValue

out,
, < div> -K O H TeftH ep
. xml g et. html ,
, . 17.4.

------------------------------------------------------------*

XML-, , POST, GET


.

XML?
, XM L,
X M L - RSS-? ,
,
Ajax-, , -

411

Ajax

,
JavaScript.
Q&ifxJ

' XML Ajax -Mozilld Firefox

titf ( Q http://k>cdhost/web/xmlget.html
...... .................................. . ____ __...:::::;________________ ______________ -------

ft A

X M L - D IV -
Yahoo! News Top Stones

I'-i

Yahoo* News

,'}

C IA chief Panetta: US has dnven back al-Qaida (AP)


Police arrest more than 500 at Toronto summit (AP)
Pope deplores Belgian sex raids, stresses autonomy (AP)

lyj.

Longtime Sen Byrd in hospital, senously ill (AP)


G O P senators: Can Kagan be impartial judge? (AP)

M an charged in Pa. stabbing rampage that killed 4 (AP)

;^

Oil spill's psychological toll quietly mounts (AP)


Scientists say test could predict menopause (AP)
Jay-Z leads nominees at music-filled BET Awards (AP)
Argentina beats Mexico 3-1 at W orld Cup (AP)
G20 walks tightrope between growth, deficits (Reuters)
Toronto police fired tear gas on G20 protesters (Reuters)

. 17.4. Ajax XML- Yahoo!

X M L - Ajax-, -'
D O M -
HTM L D O M -.

Ajax
, , Ajax-,
,
,

. , j Query, ,
, Ajax.
( ) - http://jquery.
zd m. , , > $, j Query.
, j Query, ,
-
~1 .
, Ajax, ,
^ -
:_ CSS (Cascading Style Sheets).

412

17. Ajax


1. XMLHttpRequest-?
2. try ... catch?
3. XMLHttpRequest?
4. Ajax-?
5. Ajax-?
6. XMLHttpRequest ,
Ajax-?
7. XMLHttpRequest X M L -,
Ajax-?
8. ,
Ajax-?
9. XMLHttpRequest Ajax-3a?
10. Ajax GET- POST-?
,
17.

18

CSS

Cascading Style Sheets (CSS),


-,
. CSS
Document Object Model (D O M ), 13.
CSS, .
, , <hl>,
<h2> . ., , ,
,
, .
-
<head> </head>.
, <hl>,
(
):
<style>
hi { col or:red: font-size:3em; font-family:Arial; }
</style>
H T M L- , 18.1,
, , ,
HTML5-oee DOCTYPE.
. 18.1.
18.1. HTML-
<!DOCTYPE html>
<html>
<head>
<1>. ! </title>
<style>
hi { coloured; font-size:3em; font-family:Arial: }
</style>
</head>
<body>
<hl>BceM </11>

</body>
</html>

414

18. CSS

. 18.1. ,


, ,
- ,
, , .
,
,

(, -
) HTML.
.
,
CSS- @import:
<style>
@import url( 'styles.css');
</style>

styles
, @import, ,
, , ,
. . <style> </style>
,
.
H T M L-.
H T M L- <link>:

css.

4 i n k rel ='stylesheet' type='text A s s ' href ='styles.css'

/>

, @import.,
< , HTML,

415

,
.
<style>.. ,</style>
, CSS, (Pimport
, HTML
, <1 ink>.



, HTML
( ):
<div sty1 = font-styl :itali ; color:blue; '> npMBeT</div>

,
,
.

(ID)

HTM L
<Jiv id= iblue'> npnBeT</div>
, <di >-
, i bl , ,
iblue. CSS-
:
=iblue { font -styl :itali : color:blue;

(#), ,

4 iblue.

1 -------------------------------------------------------------------------;---------------------


,
ID,
:
:iv class='iblue'>npnBeT</div>
, , iblue,
( ,
).
,
:

416

18. CSS

.iblue { font-style:italic; col or:blue: }


(#),
(ID ), ,
(.).

CSS
CSS ,


. CSS- ,
, . ,
hi ,
240 % , :
hi { font-size:240%; }

{ } . ,
( font-size) , ,
,
( 240%). hi
font -size 240%, , <h1>... </ h1>
, 240 % .
, (;), .
, font-size ,
( ,
).


CSS
CSS, .
( H T M L-)
,
.
CSS ,
,
CSS. ,
, , , ,
, .


.
:
hi { font-size:240%; col or:blue: }

417

CSS

* , ,
<hl>, . :
' '1 { font s I/;;0:
lor:blue: }
, :
lor it. /
<(I Ior

40:
blue;

, ,
,

.

,
- ,
.

, CSS
.
:
. { font-/: 240: }
"I { color
: blue: }

- CSS ,
^ *
CSS, .

,
?
"I { color
"I { color

red; }
blue: }

, ,
blue.
,
-, .
CSS, .


CSS- ,
, .
. , , :

418

18. CSS

./* CSS */

:
/*

*/

,
j <
* ( ) .
.


, ,
( ,
, ),

. , ,
, .


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


,
. ,
-. ,
-,
-
(user styles) , Firefox
Internet Explorer . . 18.2
Microsoft Internet
Explorer.

419

. *- - .......................................................
,
/;* * * > t

[
-

MCTOpiM

. ,
CD , w w n *

|(

------ -

-, .
"V'* J I -'- ' ns -'

1'1

f ] * ,- ^- >

, --.

[~ ...

|[ ]

[~). runt
:

.'irMyjtyteiCiv

-. '-

...
j |" : *
I
-
-------------

| [~

[
"

- -----------------------

| [~

| |

1[

. 18.2. Internet Explorer

,
,
. ,
, .


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


, <st lo> .</style>,


, .
.

420

18. CSS


, , 1
.
, :
' <\ href="h ttp ://google.com" sty le="color:green: "> Google^/ -

,
,
,
.


,
.

CSS

, , , CSS,
, . , , ,
.


H T M L-, ,
<> <i>. , ,
, <>.. </>:
{ te x t-a lig n :ju stify ; }


,
. ,
<>. . </> ,
<> . </> ( : <p><b>Hel lo</b> there7p>):
h { lor:red:

,
,

:
1 I I b { .

421

CSS

,
,
.
, ( 1)
( ):
<!DOCTYPE html>
<html>
<head>
<style>
ul ol { list-style-type:lower-alpha: }
</style>
</head>
<body>
<ol>
<>0</>
<></1 i>
<11></11>
</ I>

<ul>
<ol>
<>0</>
<>-</>

<li>Tpn</li>
</ol>
</ul>
</body>
</html>
HTM L -
, <>- <1>- -,
:
1.
2.
3.
a.
b .
c.


,
, ,
.
, ,
, ,
,
( : <><i ><></> </i ></>):
b { color:red; }

422

18. CSS

.
,
, . ,
,
,
:
> b { col or:red: }
HTML- ,
<>
, <>.
,
<1 ^-,
<!>-. ,
<11>-,
<1>-, :
<!DOCTYPE html>
<html>
<head>
<style>
ol > li { font-weight:bold: }
</style>
</head>
<body>
<ol>
<1i >0</1i>
<></>
<1i ></1i >
<ul>
<1i >0</1i>
<></>
<li>Tpn</li>
</ul>
</ol>
</body>
</html>
H T M L- :
1.
2.
3.


,
,

423

* CSS

,
- ,
( ).

* ( +) :

1 * : -color: red: }
,
. , , .
, <> </>
:
<!DCCTYPE html >

<htnr.>
<head>
<style>
i + b (color: red: }
</style>
</head>
<body>
<div>3T0 d iv-.
<i>3T0 , .</i>
.
<> , ,
.</>
</div>

</body>
</html>

,
( : <div id='mydiv>),
CSS ,
:
#mydiv { font - sty ! :i t a li : }


,

, CSS. CSS
,
, :
<div id='myid' ></v> <span id=,myid'>npnBeT</span>


,
myid:
#myid { text-decoration underline:

424

18. CSS

, CSS
:
span#myid { text-decoration:underline:
div#myid { text-decoration:underline:

}
}

(. , ):
span#myid.#myid { text-decoration:underline: }

, JavaScript,
* , ,
getElementByld
.
, .
.


,
, (:
<span class='myc 1ass' >),
, ,
10 ,
:
.myclass { margin-1e ft :: }
H T M L-
, , : <span cl ass='thi scl ass
thatcl ass othercl ass' >. ,
cl ass .


, ,
. ,
, main:
p.main { text-indent:30: }
, main ( :
< cl ass="mai ">), .
, ( <di v cl ass="mai n">),
.


H T M L- ,

, . ,

CSS

425

, ,
type="submit", , 100 :
'type=" submit"'] { width:lOOpx: }
, ,
, ,
:
*orm

iriput[type="submit" ] { width: : }

, * , [class="classname"] , .classname (
* , ).
[id="idname"]
#idname. ,
(#) (.)
, .


*, ,
,
:
* { border:lpx solid green: }
, - ,
- , . ,
, ,
,
, boxout,
, :
#boxout * {border: lpx solid green; }
, . , 3a#boxout
(*), , 1
boxout. ,
( ),
, * CSS-
(
).
1. , boxout.
2. ,
1.
'. p- ,

2, , ,
p-,

426

18. CSS

( . .) ,
2.
\.

, { } ,
3.

,
( . .) .


C S S
,
. ,
,
idname ,
' lassname:
[). # i driame. . lassname { border- b o l l : Ipx d o t t e d orange1. }

. 18.3 ,
.

, -
/

z z z z z z r-

SS Selectors

4-

^ !

selectors.htm

<p>TTris is a paragraph.</p>

P I

<p>Here is a paragraph with some


<tbold text</b> in it.</p>

P b {
color:red;

<ul>

<ii>Thisis aHst
element.</ii>
<li>Tbis is a Kst dement with
<b>bo!d text</b> in it.</ii>

te x t- a lig n : j u s t i f y ;

ul

Li b {
color:blue:

< /u l>
<div id='mydiv>

This is a div with the o f

#mydiv {
f ont-style:italic;

'mx'drv'.

. 18.3. HTML CSS

CSS
C S S
,
(C asc a d in g Style Sheets). ?

CSS

427

,
, ,
,
,
.


. 13
.
1. .
2. .
3. .
.
-. -
, , .
, , ,
,
.
, - ,
,
, .
, , ,
, ,
.


.
,
.
1. .
2. .
3. .
,
.
, .
(
<style>. . </style>). , ,
.
, ,
( <di v styl =..."
*/
di v>), .

428

18. CSS


.
.
1. .
2. .
3. .
,
,
. ,

.
, , ,
.

.



.
[0.0.0]. ,
, ,
[1.0.0].
. ID - (#headiriq,
#main #menu), 13.0 .01:
#heading. ftnain. #menu.

. text.. .quote. . boxout. . news. . comments .


p. blockquote {
f o n t - f a r m I : 1 lines New Ro m a n ' :
fo n t-s i/e
1 4 p t . }

. ,
.
text, .quote,
boxout, .news .comments, |..].
, ,
, .
( blockquote),
: [3.5.2],
.

, ,
352. , ,
, .
,
.

~'-1| ,.

429


_ ;
> , - ' .' . , [11.7.19]
- -*:*
<6 .
.ffio ,
_
" 20 ( , 19 ).
__ =-- - ,
:
I' 19 =
380
>2: / = 2800
_ -::^2o 11 = 88000
- I-1:
= 91180

1
. . , 20 ~ -:.-:;1 . ,
~ : : ,
-^. , , .
: . , CSS ,
_
:
~-Ti. .
^

4
^

, ,
. - : , ,
.

2
- :za
, .

, ! important:
: : 7or:#ff0000 !important: }
( ,
.' !important), ,
~:, . ,
, - ! important
:
:
:

col or:#ff0000 !important: }


color:#ffff00 }

, !important.
,
-. , CSS1,
.

430

18. CSS

<div> <span>
<di v> <span> , v
. <di v>-:uicmciit (
), ,
:
<div style="border:lpx so lid green;" ' / d iv -

<$>- , .
HTM L ,
:
<span style="border: lpx so lid green:">HpnBeT</span>

, <span>-:-uieM0HT
,
. , 18.2, CSS
<di >-, <5>-
,
<span>- <>-6.
18.2. <div> <span>

<!DOCTYPE html>
<html>
<head>
<title>npnMep div span</title>
<style>
div. span { border:lpx so lid black: }
div { background-color:yellow: }
span { background-color:cyan: }
</style>
</head>
<body>
<div>3T0T div</div>
. <div>A div.</div><br />
<span> span.</span>
. <span> span.</span><br />< />
<div>3to div.
</div><br />

<span> span,
</span>
</body>
</html>

,
. 18.4. ,
, <di >-

431

,
.

j D divandspan.htm

[ div~
.
| divT

div,
_________________________________________________________________________

. 18.4. ,

, <$>-,
, ,
.
, , ,
, <di >-
, , <$>- (
).

< d i v > - T e r n ,
, , , . ., ,
<>-, ,
,
( ).

CSS ,
-
. (
, ) , ,
. , .
(p ixel)
.

432

18. CSS

, .
. :
.classname { margin:5px: }
(p o in t) 1/72 .
,
. :
.classname { font-size:14pt: }
(in ch ) 72 , ,

. :
classname { width:3in: }
(centim eter) ,
.
28 . :
.classname { height:2cm; }
(m illim eter) 1/10 ( 3 ).
,
. :
.classname { font-size:5mm: }
(p ica ) ,
12 . :
.classname { font -si ze:Ipc: }
(em) ( ).
CSS,
. :
.classname { font-size:2em: }
() .
. ,
,
,
. :
.classname { width:20ex: }
(percent) (em), ,
. ,
lem, 100 % .
, ,
. :
.classname { height:120^: }

433

. 18.5
.

M easurem ents

measurements.htm

font-size:37px;
font-size:28pt;
font-size:0.39in;
font-size:lcm;
font-size:10mm;
font-size:2.37pc;
font-size:2.37em;
font-size:5.28ex;
font-size:237%;
. 18.5. ,


CSS :
family, style, size weight.
,
- () . .

font-family
.
,

.
,
CSS-:
{. font-family:Verdana. Arial. Helvetica, sans-serif: }

434

18. CSS

,
:
{ font-family:"Times New Roman". Georgia, serif: }
4

------------------------------------------------------ -------

- ,
* Arial, Helvetica, Times New Roman, Times, Courier New Courier,
- . Verdana,
Georgia, Comic Sans MS, Trebuchet MS, Arial Black Impact Mac
PC, , Linux.
, -Palatino, Garamond,
Bookman Avant Garde. ' ,
CSS
, -
.

. 18.6 CSS-.

font-family:Verdana, Arial,
Helvetica, sans-serif;
font-family:'Times New Roman', Georgia,
serif;
. 18.6.

font-style
normal,
ita lic oblique (
sans-serif).
(normal, ita lic oblique),
:
.normal { font-style:normal: }
.ita lic { font-style:italic: }
.oblique { font-style:oblique: }

font-size
, ,
, :

435

.
, , 14 :
{ font, size: 14pt: }


,
, .
, <h4> 20 %
, 40 %:
hi
h2
h3
h4

{
{
{
{

fo n t-s ize :240%:


font-size:200%:
fo n t-size :160%:
fo n t-size :120%:

}
}
}
}

. 18.7 .

F I5
<

^ fontsize.htm

! 5

1
2
3
4

. 18.7. ,

font-weight
, .
, normal bold:
.bold { font-weight:bold: }



, decoration, spacing
al ignment. ,

436

18. CSS

,
font-style font-weight, , ,
text-decoration.

text-decoration, ,
underl ine, 1 i nc -through,
- overline blink.
over, (
, ( ,
):
.over { text-decoration:overline:

. 18.8 ,
.

fontstyIe.htm

(Normal)

(Italic)
(Oblique)
(Bold)
(Overline.)

(Underline)

(Strikeout)

. 18.8.

, , .
,
1i ne-height, 25 % ,
word-spacing 30 3 :
{
line-height
:125%:
word-spacing ::
letter-spacing:3px; }

437

CSS :
left,
right, center
ju sti fy.
:
j

{ te x t-a lig n :ju stify :

:
, capita 1ize,
uppercase
lowercase. upper,
:
upper { text transform-.uppercase: }

text i rident

20 ,
:
( text indent:20; }

. 18.9 :
[j {

I ine height : 150%:


word-spacing : :
letter-spacing:lpx:
j u s t if y
\ text align
j u s t if y :
uppercase { text transform:uppercase:
.indent
{ text indent
20px:

}
}
(
}

, ______________________________ ~ ~ ...................... v ,

F'ont Spacing, Alignment & v

} 4r

C O

TO

suffer

& \

fontspacing.htm

BE,

question:

' _______________

OR

Whether

The

Fortune,

Or

troubles,

And

Slings
to
by

NOT

TO

BE,

'tis

Nobler

in

and

take

Arrows of

Arms

opposing

that

the
to

outrageous

against
end

is

the mind

Sea

of

them

. 18.9. ,

438

18. CSS

CSS
, ,
color background
color ( back
ground). (,
red blue), , RGB
(, # ff0000 #0000ff), ,
CSS- rgb.
16 ,
W 3C ( http://www.w3.org), : aqua, - black,
blue, -, , - fuchsia,
gray,
green, - lime, - maroon, -
navy, ol i ve, purpl , red, si 1ver,
- teal, white yel low.
II),
object:
#object { background-col or:si 1ver: }
<di >-
(
ff , ff , 00 ):
div { color:#ffffOO: }
, ,
rgb,
, :
body { background-color:rgb(0. 255. 255): }

256 ,
rgb
(0) (100), :
rgb(58%, 95%, 74%).
, : rgb(23.4%, 67.6%, 15.5%).


,
. ,
#fe4692 #f49,
, #ff4499.
. ,
. ,
,
.

439

CSS

, , #883366,
*836 ( ),

,

.
, , ,
.
18.3 (
, ),
. 18.10.
18.3.

-!DOCTYPE html >


-html
<head

.1> i pa < / 1i 11
<style>
orangegrad {
background:orange:

background:linear-gradient(top. #fbO. #f50):


background:-moz-1inear-gradient(top. #fb0. #f50):
background:-webkit-1inear-gradient(top. #fb0. #f50):
background:-o-linear-gradient(top. #fb0. #f50):
background:-ms-linear-gradient(top. #fb0. #f50): }

^ / st.y le>
' /head>
body>
<div c la s s = 4 ) r ,(jn g eg rad , >4epHbm
* />

<br

/>

rpaflneHTe</div>

/bod.y>
/htm1>

, CSS- , , -moz-, -webkit-, -- -ms- (


Mozilla, Firefox; WebKit,
Apple Safari, Google Chrome, iOS Android, Opera
Microsoft). CSS- , , ,
, - http://caniuse.com.

, , (top),
(bottom), ( l e f t ) ( r ig h t ) (center),
, (top l e f t )
(center righ t),
(1 inear-gradient), (r a d ia l -gradient)
, , .

440

18. CSS

^ color.htm

. 18.10. ,

' ,

. , ,
(
).


- , ,

, .


,
, ,
. ,
top,
right,
bottom
loft.
( ) .
, II), object.,
, 100
200 , (
, 4
CSS):
#object {
posit Io n : a b s o l u t e :
top

If'It

lOOpx.

)0. [

441


,
. , ,
10 10
:
^object {
positiomrelative:
top
: ;
left
:; }



,
. ,
,
- .
:
#object {
position:fixed;
top
:;
left
:0px; }


18.4 ,
.
18.4.
<!DOCTYPE html>
<html>
<head>
<1></1>
<style>
lobjectl {
position absolute:
background:pink;
width
:100px:
:lOOpx;
height
:100px;
top
:Opx; }
left
#object2 {
position
relative;
background 1ightgreen:
lOOpx;
width
lOOpx;
height
-8px;

top

442

18. CSS

left
: llOpx; }
#object3 {
position :fixed:
background-.yellow;
width
:lOOpx:
height
:lOOpx;
top
:lOOpx:
left
:236px: }
</style>
</head>
<body>
<br /><br /><br /><br /><br />
<div id='objectl' </^1 v>
<div id= object2 </1v>
<div id=,object3'>0HKcnpOBaHHoe ^! v>
</body>
</html>
. 18.11 18.4 ,
, ,
-.
,
, ,
,
.

<

-$

^ positioning.htm

. 18.11.

(
-) , ,
.
,
100 ,

443

8
, 110 ,
.

,
- HTML.
, , ,
, , ,
.
, fi rst-line, first-chi Id first-letter.
(:).
, bigf i rst
:
.bigfi rs t:fi rst-1etter {
font-size:4002;
float
:le f t : }
bigfirst ,
,
, ( float),
.
'over, 1i nk, acti ve vi si ted. anchor-, ,
, - :
5-.link
{ color:blue:
}
5: vi si ted { color:lightblue; }
,
"over,
.
, ,
JavaScript:
5: hover {
color
:white:
background:red: }
background-color
background .
acti ve , ,

, ,
-:
=:active { color:darkblue: }

444

18. CSS

focus,
,
.
, - 2
, :
* :focus { border:2 dotted #888888: }
. 18.12, 18.5 .
,
, .
Tab, ,
. ,
, ,
.
18.5. link focus
<!DOCTYPE html>
<html>
<head>
<ti tl >/ti 11e>
<style>
a :1ink
{color:blue;
}
a:visited {color:gray:
}
a:hover
{col or:red;
}
a:active
{col or:purple;
}
* :focus
{background:yellow; }
</style>
</head>
<body>
<>
Tab ( Shift+Tab)</p> <br /> <br />
< href='http://google.com'> Google'</a><br />
<a href=nowhere> </>< />
<input type='text' />
</body>
</html>

4- 4 G

! 4 pseudodasses.htm

Tab ( Shift+Tab)

Google1
1

. 18.12. ,

445

,
-: http://tinyurl.com/pseudoclasses.

focus *, ,
Internet Explorer ,
, , -, ( )
, Tab,
.

,
.
, . , , offer,
:
offenbefore { contents'Special Offer!

, offer, ,
content .
:after -
(), ,
1i nk. gi f :
ra fte r { u rl(lin k .g if): }


CSS-
. ,
, focus
:
* :focus { border:2 dotted #888888: }
:
focus {

border width:2;
border-style:dotted.
border c o l o r :#ff8800. [

, .

c/i 1 :
4

focus

{ b o r d e r :2 dot 1 <!. }

446

18. CSS

,
.
j ,
;.1 CSS
, , CSS
- .
-: http://tjnyurl.com/shcss.


CSS, , (
19), ,
( ) ,
, ( )
:
body { margin:; }
, .
, . ,
.
,
,

.


.
. , ,
10
. ,
20 .
,
,
.
, . ,
, . ,

. .
margin
margin- left, margin-top, margin-right
margin-bottom. margin , ,
, ,
:

447

~ */
rgi n:lpx:
* 1 ,
- 2 */
~- 2;
* 1 , - 2
- 3 */
"- 2 ;
* 1 , - 2. - 3
- 4 */
~argin;lpx 2 4;
. 18 3 18.6, ,
rgi ( )
, <tabl > ,
<di >-.
10 , 20 ,
30 40 .
18.6.

<!DOCTYPE html>
<html>
<head>
<1></1>
<style>
#objectl {
background
border-style
border-width
font-family
font-size
width
height
padding
margin

lightgreen;
solid;
lpx;

Courier New;
9px;
lOOpx;
lOOpx;
5px;

20px 30px 40px; }

</style>
</head>
<body>
<table borderer cel Ipadding='0 cel lspacing=0 1=''>
<tr>
<td>
<div id=objectl>margin:<br />10 20px 30px 40px;</div>
</td>
</tr>
</table>
</body>
-/html>

448

18. CSS

A \s margin.htm

. 18.13.


, ,
.
. ,
, border, border-left, border-top, border-right border-bottom.
, ,
-color, -style -width.
,
margi , border-wi dth,
:
/* */
border-width:lpx;
/* / / */
border-wi dth;lpx 5 ;
/* , / */
border-width:lpx 5 ;
/* , , */
border-width: lpx 5 15:
. 18.14 ,
. ,
, 1 .
1 ,
5 . 1 ,
5 , 10 .
1 ,
5 ,
10 15 .

449

/ (Q CSS Box model

4* :

| borders.htm

l *

. 18.14.

, ,
.
. ,
.


(
) , () .
, , padding,
Dadding-1eft, padding-top, padding-right padding-bottom.
,
margi border, - paddi ng,
:
* */
Daddingilpx;
* / / */
wadding:1 2;
* , / */
.-adding: 1 2 ;
* , , */
..adding :1 2 4;
11 . 18.15 , 18.7
(
display:tablf1 cell

iv -

450

18. CSS

). ,
. , 10
, , 20 , 30
40 .
18.7.

<!DOCTYPE html>
<html>
<head>
<t i 11></ tl e>
<style>
#objectl {
border-style:solid:
border-width:lpx:
background :orange:
color
:darkred:
font-face
:Arial:
font-size
:12px;
text-align -.justify:
display
.table-cell:
width
:148px:
padding

:10px 20px 30px 40px; }

</style>
</head>
<body>
<div id='objectr>To be. or not to be that is
the question: Whether *tis Nobler in the mind
to suffer The Slings and Arrows of outrageous
Fortune. Or to take Arms against a Sea of
troubles. And by opposing end them.</div>
</body>
</html>

-> e

padding.htin

. 18.15.

451


, , ,
, ,
( ) , ,
, . .,
.
, ,
CSS-,
, , ,
CSS3.


1.
( <style> H TM L)?
2. H T M L-
?
3. H T M L-
?
4. CSS CSS?
5. CSS-: )
) ?
6. CSS-?
7. ?
8. CSS ?
9. CSS ()
?
10. CSS-,
?
,
18.

4
1 ?

CSS
CSS3

CSS 1996 , 1999


2001 .
, CSS1, 2008 . , CSS2,
1998 ;
2007 , 2009 .
2001 CSS3,
, 2009 . , ,
CSS3.
, CSS3 ,
CSS4.
CSS3,
.
,
JavaScript.
CSS3 ,
, JavaScript, ,
CSS (
) , ,
.


,
CSS, .
CSS H T M L-.
, . 19.1.
19.1. CSS-,

* { color:#555; }

b { color:red; }

.classname { color: blue; }

453

#idname { background :cyan; >

span em { colorigreen; >

div > em { background:lime; }

i + b { color:gray; }

a[href='info.htm'] { color:red; }

a:hover { font-weight:bold; }

p::first-letter { font-size:300%; }

CSS3 ,
,
,
, .


CSS2 ' i nfo. htm', href-,
, a[href= i nfo. htm' ],
. CSS3
:$ *.
(=), ,
, , .


, href-,
http: / /webs i te ':
s [ h r e f ' http://websi t e ']
, :
< href=' http://website.com'>
:
< href= 'http://mywebsite.com'>

$

, img-, src-
' . png *:
img[src$='.png']
, :
<img src='photo.png />
:
<img src=' snapshot.jpg' />

454

19. CSS CSS3

*
, ,
. ,
'google' :
a[href*='google']
, HTML:
< href='http://google.com'>
:
< href='http://gmai1.com>

box-sizing
W 3C ,
,
. - ,
, .
, CSS3
box-sizing. ,
, ,
:
box-si zing:border-box;
, ,
( ):
box-si zing:content-box;

---

----------------------------------------------------------------------------------------------

WebKit Mozilla ( Safari Firefox )


4 (-webkit- -moz-), .----
- http://caniuse.com.

CSS3
CSS3 , background-cl i backgroundorigin, ,
,
, .
:
border-box ;
padding-box ;
content-box .

CSS3

455

background-dip
, ()
, . ,
,
, :
:a c k g ro u n d -c lip :b o rd e r-b o x :

, ,
,
, :
: a c k g r o u n d -c l i :paddi n g - b o x ;

,
, :
: a c k g r o u n d - c l i :c o n t e n t - b o x ;

. 19.1 , - Safari:
b a c k g r o u n d - c l i p b o r d e r- b o x ,
p a d d i n g - b o x ,
:ontent-box.

( ,
)
. ,
,
.
,
,
backg ro un d-cl i p pad ding-box.
, ,

( , ),
b ackg ro un d-cl i p c o n t e n t -b o x .

background-origin
,
, ,
. , ,

:
Dackgrou nd -o rig in:bo rd er-bo x;


, :
D a c k g r o u n d -o rig in : p a d d in g - b o x ;

456

19. CSS CSS3

CSS3 Background Clip


file

Edit

View

History

gookmarks

W mdc*

Help

i + ; backgreundclip.htm

. 19.1. CSS3


, :
background-ori gin:content-box:
. 19.1,
background-origin border-box,
padding-box,
content-box. ,
,
,
.

,
. 19.1 ,
, ,
, .

CSS3

457

background-size
,
<img />,
.
( wzv -- , a hh
):
background-si ze:tvwpx /7/?:
,
. ,
, <di v> (
, <span>), ()
, .

auto
,

, auto:
: ackground-size: auto:
, 100 , ,
, .

background,
- http://caniuse.com, ,
, , .


, CSS3, ,
CSS3.
. 19.2.
,
.
CSS-
. 19.1 HTM L CSS,
. 19.2.
19.1.

-DOCTYPE html>
'-html >
<head>
<tit.le>CSS3: ^/1i1 1e>
<style>
.border {
font-famiI : Iimes New Roman'

458

19. CSS CSS3

CSS3:

10 l.hou

:
/

. 19.2. ,

font-stylo
font-size
text-a 1ign
padding
width
height
background

it a lic :
17035:

center:
60px:
350px:
500px:
u r l( b l. g if
ur1( b2.gif
u r l( b3.gif
u r l( b4.gif
u r l( ba.gi f
u r l( bb.gif
u r1( b e.g if
u r l( 'b d .q if

</st.yle>
/head>
body>
<div class='border >
<1> '- /hi
<h2>Hai ::</h2"
<h3>
' /h3-

top
top
bottom
bottom
top
) le ft
) right
) bottom

)
)
)
)
)

le ft
right
le ft
right

no-repeat
no-repeat
no-repeat
no-repeat
repeat-x.
repeat-y.
repeat-y.
repeat x

459

CSS3

<2>:</h2>
<h3>__ /__ /___ </ h3>

</div>
</body>
' /html>

CSS
,
, ,
.
, ,
.
GIF- ,
, .

CSS,
, , ? , ,
.

CSS3
CSS3
, ,
, /
.

border-color
. ,
:
: order-col :#888:

- .
(
):
: order-top-color
:#000:
: o r d e r - le ft - c o lo r :#444:
: ord e r-rig h t-co lo r :#888:
: order-bottom-color:#ccc:

, :
: order - co lor:# f00 #0f0 #880 #00f:

# f 00,
B#0f0,
#880 #00f (, .

460

19. CSS CSS3

).
, .

border-radius
CSS3 -
, , ,
<table> <div>
-
, , . 19.3,
. 10
. HTML 19.2.
19.2. border-radius

<D0CTYPF html
<html"
head
'I it le>CSS3: </title>
- style-
.box {
margin bottom: :
'Courier N
ew . monospace:
font-family :: Courier
New
: 12pt:
font-size
text align
:center:
padding
: :
width
:380px:
:75px;
height
border
: sol id #006:
bl {

moz-border radius
40px
webkit border radius 40px
40px
border-radius
:

b2 {
-moz-border-radius
:40px 40px 2C )x 20px:
-webkit-border-radius:40px 40px 2C >x 20px:
border-radius
:40px 40px 2C
)x 20px:
,b3 {
20px
-moz-border-radius-topi eft
40px
-moz-border-radius-topright
-moz-border-radi us -bottomleft
60px
80px
-moz-border-radius-bottomright
20px
-webkit-border-top-left-radius
40px
-webkit-border-top-right-radius
-webk i t -border -bottom-1eft -rad i us 60px
-webk i t -border -bottom-ri ght-radi us:80px
border-top-1eft -radi us
20px
40px
border-top-ri ght-radi us
border-bottom-left-radius
60px
80px )
border-bottom-right radius
h4 {

461

CSS3

-moz-border-radius-topl eft
:40
:40
-moz-border-radius-topright
-moz-border-radius-bottomleft
:20
-moz-border-radi us-bottomri ght
:20
:40
-webkit-border-top-left-radius
-webk i t -border-top-ri ght-radi us
:40
-webkit-border-bottom-1e ft-rad i us :20
-webk i t -border-bottom-r i ght-ra<di us:20
border-top-1eft -radi us
:40
border-top-ri ght-radi us
:40
border-bottom-left-radius
:20
border-bottom-ri ght-radi us
:20

20:
20;
40:
40:
20:
20:
40:
40;
20:
20:
40:
40: }

</style>
</head>
<body>
<div class='box b l >
border-radius:40px:
</div>
<div class='box b2>
border-radius:40px 40px 20px 20px;
</div>
<div class='box b3>
border-top-left-radius &nbsp:&nbsp:&nbsp::20px;<br/>
border-top-right-radius &nbsp;&nbsp;:40px;<br />
border-bottom-left-radius :60px;<br />
border-bottom-r i ght-radi us:80px;
</div>
<div class=box b4'>
border-top-left-radius &nbsp:&nbsp:&nbsp::40px 20px:<br />
border-top-right-radius &nbsp;&nbsp::40px 20px;<br />
border-bottom-left-radius :20px 40px:<br />
border-bottom-right-radi us:20px 40px:
</div>
</body>
</html>
, , 20
:
border-radius:20px:

( Internet Explorer)
, ( )
, ,
,
, -moz- -webkit-.
, .

462

19. CSS CSS3

b o r d e r - ra di u s: 4 0;

b o r d e r - r a d i u s :40 40 20 20;

border-top-left-radius
:20;
border-top-right-radius
:4 0px;
border-bottom-left-radius :60px;
b o r d e r - b o t t o m- ri gh t -r ad iu s :8Clpx;

border-top- left-radius
:40px
border-top-right-radius
:40px
bord er-bottom-left-radius :2Qpx
b or de r- b o t t o m - r i g h t - r a d i u s :20px

20px;
20px;
40px;
4 0px;

. 19.3.

(
, ):
border-radius: 20 40:


:
border-top-left-radius
:20;
border-top-right-radi us
:40px;
border-bottom-left-radius :60px;
border-bottom-ri ght-radi us:80px;

,
(
):
border-top-left-radius
:40
border-top-right^radi us
:40
border-bottom-left-radius :20
border-bottom-ri ght-radi us:20px

20;
20;
40;
40px;

, .

463



, ,
:
-shadow: 15 15 #888;
15 ( )
, ,
. (
), ,
#888 , (.
CSS 18). . 19.4.

1 ^

j View(100%)-- j

. 19.4. , element

, WebKit Mozilla,

4 -webkit- -moz-.

uy ----------------------------------------------------------------------------------------------


CSS2 , , ,
, ,
overflow hidden, visible, scroll auto.
CSS3
, :
overflow-x:hidden:
Dverf1ow-x:visible:
overflow-y:auto:
Dverflow-y:scroll:

464

19. CSS CSS3

-
, CSS3 - , a Internet
Explorer 10 , .
,
, ()
( ). . 19.5
19.3.

| 19.3.htm

Now is the winter o f our


discontent Made glorious
summer by this sun o f York;
And all the clouds that lour'd
upon our house In the deep
bosom o f the ocean buried.
N ow are our brows bound

with victorious wreaths; Our


bruised arms hung up for
monuments;
Our
stem
alarums changed to merry
meetings,
Our
dreadful
marches
to
delightful
measures. Grim-visaged war

hath smooth'd his wrinkled


front; And now, instead of
mounting barded steeds To
fright the souls o f fearful
adversaries, He capers nimbly
in a lady's chamber To the
lascivious pleasing o f a lute.

. 19.5.

19.3. CSS

<D0CTYPE html>

<html>
<head>
<1> </1>

<style>
.columns {
text-align
:ju s tify :
font-size
:16pt;
-moz-column-count
:3:
-moz-column-gap
:lem;
-moz-column-rule
:lpx solid
black:
-webkit-column-count:3:
-webkit-column-gap :lem;
-webkit-column-rule :lpx solid
black;
column-count
:3:
column-gap
:lem;
column-rule
:lpx solid black: }
</style>
</head>
<body>
<div class=,columns'>

465

Now is the winter of our discontent


Made glorious summer by this sun of York;
And all the clouds that lour'd upon our house
In the deep bosom of the ocean buried.
Now are our brows bound with victorious wreaths:
Our bruised arms hung up for monuments;
Our stern alarums changed to merry meetings.
Our dreadful marches to delightful measures.
Grim-visaged war hath smooth'd his wrinkled front;
And now. instead of mounting barded steeds
To fright the souls of fearful adversaries.
He capers nimbly in a lady's chamber
To the lascivious pleasing of a lute.
</div>
</body>
</html>
.columns
16pt.
,
. ,
, lem,
1 , .

^ --1 -----------------------------------------------------------mW

Mozilla WebKit .


CSS3 :
CSS-
R G B (, , ), R G B A (, ,
, ), HSL (, , ) HSLA (, ,
, ). ,
, .

HSL
hsl
0 359.
, 0
, , 360 720.
,
120 , 0,
120, 240.
,
.

466

19. CSS CSS3

,
100 %. , .
- (
0 %), (
100 %) .
, ,
0 100 %. 50 %
, , (,
0 %) , .
(, 100 %) ,
.
, .
, ,
:
color:hsl(60. 100%. 50%);
-
:
col or:hsl(240, 100%. 40%):
( CSS-,
) ,
, background-color . .

HSLA
,
hsl , ( )
,
0 1. 0 ,
, 1 .
,
30 % :
col or:hsl(60, 100%. 50%. 0.3);
,
82%-
:
col or:hsl(240, 100%. 60%. 0.82);

RGB
, RGB,
# #. ,

467

(
, ):
color:#ffff00:
color:#ffO;
CSS-
rgb, ,
( 255 ff):
color:rgb(255. 255. 0);
,
256, :
color:rgb(1002. 1002. 0):

, . ,
, ,
, , ,
, 0 %
, 40 % 60 %
:
col or:rgb(0%. 602. 402):

RGBA
hsl , rgba () ,
, ,
40%- :
color:rgba(02. 602, 402. 0.4):

opacity
opacity -, hsl
rgba, ( ,
) .

( , 25 %,
, 75 %):
opacity:0.25:
Jf

---

----------------------------------------------------------------------------------------------

WebKit Mozilla . 4 , . ,
*
3?* Internet Explorer, 9, (
100):
fjlter:alpha(opacity='25');

468

19. CSS CSS3

,
CSS3 ,
, , , .

text-shadow
box-shadow
: ,
. , 3
,
4 :
text-shadow: 4 #444:
, . 19.6.
(
Internet Explorer 9 ).

. 19.6.

text-overflow
CSS- overflow , hidden,
text-overflow
, :
text-overf1ow:el 1ipsi s :
, be, or not to be. That is the
question. , , . 19.7,
, . 19.8.

be, or not to be. That is


. 19.7.

be, or not to be. Tha...


. 19.8. ,

469

, .
overf 1ow, ,
overflow:hidden.
white-space:nowrap,
.
, .

word-wrap
- , ,
, , .
text-overflow
word-wrap break-word :
word -wrap:break-word;
, . 19.9 , Honorificabilitudinitatibus ,
(
t ), , overflow ,
.

Honorificabilitudinitatibus
. 19.9.

. 19.10 word-wrap break word


.

Honorificabilitudinit
atibus
. 19.10.

-
- CSS3
, -, ,
,
. -,
@font -face:

470

19. CSS CSS3

@font-face
{
font -family:FontName;
src:url( 'FontName.otf'):
>
url , U R L - .
TrueType (TTF),
OpenType (OTF), Internet Explorer
TrueType, EOT (EOT).
, format,
( OpenType):
@font-face
{
font-family:FontName:
src:url( 'FontName.otf') format('opentype'):
1
( TrueType):
@font-face
{
font-family:FontName:
src:url('FontName.ttf') format( 'truetype'):
}
Internet Explorer EOT-,
@font-face, format.

- Google
-
Google.
- Google (http://google.com/webfonts; . 19.11),
500 .
, ,
H T M L- <1 ink>:
<link href='http://fonts.googleapis.com/css?fami1y=Lobster />
, ,
CSS-:
hi { font-family:'Lobster'. arial. serif: }

, , ,
(, 3D ,
, Web Kit). -

471

<div>-
,
.

httpw'mvv/.google.com/webfcnts^CHoosePlace:
File |dit

yiew Favorites

look

X |[ Google Web Fonts

Help

G o o g le web fonts

K k k sla rt new fonts!

word

sentence

Paragraph ' Bookm ark your Collection

Showing
P review I ext

495
font families

:le s loni collection is vasi

S ize: I 36 1 j px

D ow nload your Collection


Sorting

T re n d in g ] j

^pjQ^feA- f^Q/d coKedio jb 16 v a d


G re a t V ib e s . 1 Style by .^ .. R

Q uick-use

d ? P o p out

Filte rs:
A ll categories

Googles font collection is vast

T hickness
Slant
W id th

[]Poset a!! fi)!.

O xygen

1 Style by V ern o n A d a m s

71 Q uick-use

P o p out

Script:
; Latin

Googles font collection is vast

Styles:

0 font families in your Collection *

Review

1100% -

. 19.11. - Google

transform
( , ,
Mozilla, WebKit, Opera Microsoft;
- http://caniuse.com).
transform ,
, , :
transform:none:

transform
:
matrix - , ;
trans 1ate - ;
scale ;
rotate

skew .

472

19. CSS CSS3

,
LranslateX, sealeY . .

<3^ I
VV ,

WebKit (, Apple Safari, iOS, Google Chrome Android)


-. , Internet
Explorer, Opera Mozilla ,
, .

, , 45,
:
Iransform:rotate(45deg):

,
, ,
:
l.rarisform:scale(1.5. 2) rotate(45deg):

. 19.12 .

. 19.12.

( Internet Explorer 10, )


, .
,
, .
:
trans i tion property
: :
tra n s itio n -d u ra tio n
:
tra n s it io n delay
..
I;ransi t ion t imi nq - f u n d i on ::

473

&
,
I4 Mozilla, WebKit, Opera Microsoft.

LI

-----------------------------------------------------------

,
, height, border-col or . .
CSS- transi ti on-property (
property, , , ).
, :
transi ti on-property:wi dth. height, opacity;
, , ,
( ), all:
transition-property:all:


transit ion-duration .
1,25 :
transition-duration:1.25s;


transi tion-del ay (
),
.
0,1 :
transi ti on-delay :0.1s;
transition-delay (
, ),
, ,
, - .


transi tion-timing-function
.
ease , .
1i near .
ease -i n , .
ease-out ,
.
ease-in-out , , .

474

19. CSS CSS3

ease , (linear)
, - .
, ,
cubic-bezier.
,
, ,
:
transition-timing-function:cubic-bezier(0.25.
transition-timing-function:cubic-bezier(0,
transition-timing-function:cubic-bezier(0.42.
transition-timing-function:cubic-bezier(0.
transition-timing-function:cubic-bezier(0.42.

0.1.
0.
0.
0.
0.

0.25.
1.
1.
0.58.
0.58.

1):
1):
1):
1):
1):


,
, ,
0,3 ,
() 0,2 :
transiti on:a l1 .3s linear .2s:
,
,
.
19.4 , ,
. CSS , ,
, hover ,
180
(. 19.13).
19.4.

, hover

<D0CTYPE html>
<html>
<head>
<ti tl ^ </ti tl >
<style>
fsquare {
position
absolute
top
50px:
50px:
left
width
lOOpx:
height
lOOpx:
2px:
padding
text-align
center:
border-width
lpx:
border-style
solid:

475

background
transition
-moz-transition
-webkit-transition
-o-transition
-ms-transition
#square:hover {
background
-moz-transform
-webkit-transform
-o-transform
-ms-transform
transform
</style>
</head>
<body>
<div id='square>
Square shape<br />
created using<br />
a simple div<br />
element with<br />
a lpx border
</div>
</body>
</html>

<r

orange;
all .8s
all .8s
all .8s
all .8s
all .8s

ease-in-out
ease-in-out
ease-in-out
ease-in-out
ease-in-out

yellow:
rotate(180deg)
rotate(180deg)
rotate(180deg)
rotate(180deg)
rotate(180deg)

| 19.4.htm

. 19.13.


,
. ( Internet Explorer 10 )


.

476

19. CSS CSS3

CSS- , ,

. , ,

.
, CSS
.
CSS,
(D O M )
JavaScript.


1. CSS3

$ *?

2. ?
3. ?
4. ?
5. , CSS-.
6. -
5 3 ?
7. , ?
8. - - Google?
9. CSS- 90?
10. ,

?
,
19.

CSS
JavaScript
, Document Object Model
(D O M ) CSS, ,
JavaScript,

-.
,
,
- , . , , D O M
,
H TM L ,
JavaScript .


getElementByld
13 , $ ,
getElementByld.
, jQuery, $-
.
,
D O M CSS
. ,
$, ,
object (),
( ,
ID, ).


0 :

tunc ( iori 0(nh.i

478

20. CSS JavaScript

return document.getElementById(obj)
}
22
, ,
ID, , ,
20.1.
20.1. 0
function 0(obj)
{
i f (typeof obj == 'object') return obj
else return document.getElementByld(obj)
}

, .
, ID, ,
ID .
,
?

S
,
, S 20.2,
( CSS) .
20.2. S
function S(obj)
{
return 0(obj).style
}

S , Style,
(
) , .
0 ID, , S ID,
.
, , <di v>-:*neMeiiT ID myobj
green ():
<div id='myobj *>Some text</div>
<script>
OCmyobj') . style.color = 'green'
</script>
,
S:
S( 'myobj' ) .color = 'green'

getElementByld

479

, ,
0, , , f red:
fred = 0 (*myobj')
, S,
:
S(fred).color = 'green'
,
ID, , 0,
S, , . ,
( ID ) .


,
- .
.
CSS ,
, myclass:
<div class='myclass>Coflep>KHMoe di v- </a>
<p class='myclass'>Coflep>KHMoe </>
,
, (
class), 20.3. ,
, .
20.3.

function C(name)
{
var elements = document.getElementsByTagName()
var objects = []
for (var i = 0 : i < elements.length : ++i)
i f (elements[i].className == name)
objects.push(elements[i])
return objects
}
no . name ,
.
el ements, ,
getElementsByTagName

:
var elements = document.getElementsByTagName()

480

20. CSS JavaScript

objects,
, :
var objects = []
for ,
elements, i:
for (var i = 0 : i < elements.length ; ++i)
objects ,
className ,
name:
i f (elements[i] .className == name)
objects.push(elements[i ])
, , objects
, ,
name, :
return objects


, ,
,
( )
:
myarray = ('myclass')
, ,
textDecoration ' under 1in e':
for (i = 0 : i < myarray.length ; ++i)
S(myarray[i]).textDecoration = underline'
myarray[]
S ,
textDecorati on ' underl i ne .


0 S ,
. OSC . js (
, , )
Chapter 20 ,
- http://lpmj.net.
- ,
<head> - .
, :
<script src='0SC.js'></script>

CSS JavaScript

481

OSC.js 20.4.
20.4. OSC.js

function 0(obj)
{
i f (typeof obj == 'object') return obj
else return document.getElementById(obj)
}
function S(obj)
{
return 0(obj).style

function C(name)
{
var elements = document.getElementsByTagName('* ')
var objects = []
for (var i = 0 ; i < elements. length ; ++i)
if (elements[i].className == name)
objects.push(elements[i ])
return objects
}

CSS JavaScript
textDecorati on, ,
CSS, : text-decorat ion.
JavaScript
, CSS,
, ,
, .
font -si ze, JavaScript
fontSize:
myobject.fontSize = 16pt'

setAttribute, ( )
CSS:
myobject.setAttribute(font-size'. ' 16pt )

Microsoft Internet Explorer


JavaScript- , CSS.
,
-ms-.

482

20. CSS JavaScript


JavaScript ,
-, , CSS.
, CSS,
JavaScript, setAttribute (
, CSS).
. ,
CSS, .
CSS JavaScript,
20.5,
, <>- , ,
JavaScript, <script> HTML,
<div> (. 20.1).
20.5. CSS JavaScript
<html>
<head>
<title>00paineHne CSS</title>
<script src='0SC.js,></script>
</head>
<body>
<div id=object' >Div-o6beKT</div>
<script>
S('object' ) .border
S ('object').width
S('object' ) .height
S('object' ) .background
S('object') .color
S('object' ) .fontSize
S('object' ) .fontFamily
S('object' ) .fontStyle
</script>
</body>
</html>

=
=
=
=
=
=
=
=

solid lpx red


' lOOpx'
lOOpx'
'#eee'
'blue'
' 15pt'
'Helvetica'
'it a lic '

,
CSS ,
,
JavaScript CSS.


JavaScript ,

, ,
( ) U R L -,
.

CSS JavaScript

20-5.htm

Div

. 20.1. JavaScript

window (
window.name). . 20.1 .
20.1. window

closed

, ,

defaultStatus

document

frames

, i-

history

innerHeight

innerWidth

length

i-

location

name

navigator

opener

outer Height

outerWidth

pageXOffset

pageYOffset

parent

screen


&

484

20. CSS JavaScript

20.1 ()

screenLeft

x
, Mozilla Firefox (
screenX)

screenTop


, Mozilla Firefox ( screenY)

screenX


, Opera, ;
Internet Explorer, 9-

screenY


, Opera, ;
Internet Explorer, 9-

self

the current window

status

top

.
defaul tStatus status ,
(
).
hi story (
, ),
length, , back,
forward go .
, -,
wi ndow. i nnerHei ght wi ndow. i nnerWi dth.

.
screen , avai 1Height,
avai 1Wi dth, col orDepth, hei ght, pi xel Depth wi dth,
.


,
, ,
. .


JavaScript.
, ,
, , ,
, ,
. -
http://tinyurl.com/domproperties.

485

JavaScript

JavaScript
<scri pt>
JavaScript. JavaScript HTML,
.
,
, <img />
20.6. ,
(
).
20.6.

JavaScript

<html>
<head>
< t it l> JavaScri pt</title>
</head>
<body>
<img src='apple.png'
onmouseover="thi s .src='orange.png' M
onmouseout="this.src='apple.png M />
</body>
</html>

this
this.
JavaScript , <i mg />.
. 20.2,
.

( )

| 20.6.htm

. 20.2. JavaScript,

486

20. CSS JavaScript

this JavaScript,
. ,
.


<img />
,
20.7.
20.7.

JavaScript

<html>
<head>
<ti11> JavaScript</title>
<script src='0SC.js'></script>
</head>
<body>
<img id='object src='apple.png' />
<script>
0( 'object') .onmouseover = functionO { this.src = 'orange.png' }
0( 'object') .onmouseout = functionO { this.src = 'apple.png }
</script>
</body>
</html>
ID <img /> HTML,
JavaScript,
.


JavaScript , ,
, .
,
. . 20.2 .
20.2.

onabort

onblur

onchange

onclick

ondbldick

onerror

JavaScript

onfocus

onkeydown

( Shift, Alt, Ctrl Esc)

487

onkeypress

( Shift, Alt, Ctrl Esc)

onkeyup

onload

on mousedown

onmousemove

onmouseout

onmouseover

onmouseup

onsubmit

on reset

on resize

onscroll

onselect

onunload

, .
, , , onsubmit.


JavaScript,
, HTML.
, DO M .
, , <div>.
- 20.8.
D0M
<html>
<head>
<1> <1>
<script src='0SC.js'></script>
</head>
<body>
.< />< />

20.8.

<script>
a le rt( ' 0')
newdiv
= document.createElement( 'di v ')
newdiv.id = NewDiv
document.body.appendChi1d(newdi v)
S(newdiv).border = solid lpx red
S(newdiv).width = lOOpx
S(newdiv).height = lOOpx

488

20. CSS JavaScript

newdiv.innerHTML = " , D0M"


tmp
= newdiv.offsetTop
1 )

newdi v.parentNode.removeChi1d(newdi v)
</script>
</body>
</html>
createElement,
appendChi Id, D O M .
, innerHTML
( HTML). ,
, offsetTop
tmp. D O M
, ,
. , Internet Explorer. . 20.3.

<5-

X fi

20.S.htm

.

,

DOM

J a v a lc iip t

. 20.3. DOM

,
HTML, .

---

---------------------------------------------------------------------------------------------- , , -

4 * , ^>-

DOM.

489


D O M , ,
JavaScript. ,
. , el ement,
:
Iement.pa tNode. removeChiId(e1ement)
parentNode ,
. removeChi Id,
. D O M
, ,
:
pnode = element.parentNode
pnode.removeChi1d(element)
tmp = pnode.offsetTop
element.parentNode (
) pnode, (
) of fsetTop
tmp, DOM .


-
.
onmouseover -
, , CSS,
,
D O .
, ,
( ),
vi sibi 1ity ' hidden':
myobject.visibility = 'hidden'

:
myobject.visibi1ity = 'v is ib le 1
,
( ):
myobject.display = 'none'

:
myobject.display = 'block'

490

20. CSS JavaScript

, innerHTML,
HTML, . :
mylement.. innerHTML = '>3 HTML</b>'

0:
0 ( ' someid ) . innerHTMl

- ' '

:
O f 's o m e i d ' ) . innerHTMl

\
CSS,
* * JavaScript. , 3?* ,
width height. ,
position 'absolute', 'static' 'relative',
( ).


JavaScript , ,

.
, Ajax
, -.
, setTimeout set Interv a l ,
clearTimeout cle arln terval .

setTimeout
setTimeout JavaScript
,
:
setTimeout(dothis. )

dothi s :
function d o th is ()

1' !'):

---j

-----------------------------------------------------------------------------------------------

, alert() ( )
A t , setTimeout, .
------ , ,
, (, alert).

491


, set Timeout
, ,
. :
setTimeout("alert( 'H ello!')". 5000)
,
JavaScript, :
setTimeout("document.write('Start m g '); a le r t('He 11 !') " . S000)

-
, setTimeout,
setTimeout
, , ,
:
setTi meout(doth i s . 5000)
function dothisO
{
setTimeout(dothis. 5000)
a Ie rt( ' !')
}
.

-
- ,
, setTimeout:
handle = setTimeout(dothis. 5000)
, handle,
, :
clearTimeout(handle)
,
, .

setlnterval

setlnterval. , ,
, , ,
, , ,
, .

492

20. CSS JavaScript

20.9 ,
. 20.4.
20.9. ,
<html>
<head>
<1> set Interval </ti 11e>
<script src='0SC.js ></script>
</head>
<body>
: <span id= *time >00:00:00</span><br />

' sc:ript>
set Interval("showtime(0('time')) . 1000)
function showtime(object)

var date - new Date()


object. innerHTML = date.toTimeString() ,substr(0.8)

1
</s c r i p t *

<
-/body>

</html>

20.9.htm

15 44 54

. 20.4.

ShowTime date
Date:
var date = new DateO
innerHTML , showtime ( object),
, ,
toTimeString. 09:57:17
UTC+0530,
substr:
object.innerHTML = date.toT imeStri ng() . substr(0.8)

493


, ,
innerHTML , HTML:
: <span id=,time>00:00:00</span>
<script> setlnterval:
setlnterval( "showtime(0('time') . 1000)
setlnterval ,
, ( 1000
):
showtime(0('time'))
, - JavaScript
( ), JavaScript
00:00:00.


,
setlnterval handl
:
handle = setlnterval( "showti me(0('time'))". 1000)
, :
cl earInterval(handle)

:
setTimeout("clearlnterval(handle)". 10000)
10 (10 ),
.


CSS
.
, 20.10
, , . 20.5.
LEFT 0, .
20.10.

<html>
<head>
< t it l> </1>
<script src=0SC.js'></script>
<style>

494

20. CSS JavaScript

#box {
position :absolute:
background:orange:
border
:lpx solid red: }
</style>
</head>
<body>
<div id='box></div>
<script>
SIZE = LEFT = 0
setlnterval(animate. 30)
function animateO
{
SIZE += 10
LEFT += 3
i f (SIZE == 200) SIZE = 0
i f (LEFT == 600) LEFT = 0
S('box') .width = SIZE + 'px'
S('box') .height = SIZE + 'px'
S('box ) .le ft
= LEFT + px
</script>
</body>
</html>

. 20.5. ,

<head> box ' orange' (


) (border) 'lpx solid r e d
position absolute,
.

495

animate
SIZE LEFT, width,
height left box ( ' '
, ),
30 . 33,33
(1000 / 30 ).
, ,
-.
, , ,
, , , ,
.


1. 0, S ?
2. CSS- .
3. ?
4. -
, ?
5. JavaScript
?
6. ) ) ?
7. ?
8.
?
9. -,
?
10. ( )
50 ?
,
20.

^ 4|
<

, .
,
, , .
M ySQL
, CSS, ,
, D O M , Ajax-, ,
, .
, ,
,
.
, ,
.
,
,
.

. ,
.



, :
;
;
;
;
;
;
;

functions.php

497

;
.
Robins Nest.
,
( functions. php).

-
, ,
-, http://lpmj.net.
, Download 2nd Ed. Examples
( 2- ).
2nd_edi t i on exampl es. zi p,
.
, , Z IP -
robinsnest,
, .
web,
.

functions.php
21.1, f unct i ons. php,
, .
. ,
, .
, ,
, . ,
, , (
8). Sdbuser
$dbpass MySQL.
,
MySQL .
, Robi n s Nest
Sappname. .

:
createTabl
;
queryMysql MySQL,
;

498

21.

destroySession - P H P -
;
sanitizeString ,
;
showProf i 1
About me ( ), .
. ,
, showProfi "I,
user.jpg ( user )
.
About me ( ), .
,

. -
, , ,
,
.
21.1 functi ons.php (
-),
.
21.1. functions.php

<?php // functions.php
Sdbhost
='localhost';
$dbname ='anexistingdb';
Sdbuser
='robinsnest';
Sdbpass
='apassword';
Sappname ="Robin's Nest";

//
//
// ...
// ... ,
// ...
// ... \

mysql_connect(Sdbhost, Sdbuser, Sdbpass) or die(mysql_error());


mysql_select_db(Sdbname) or die(mysql_error());
function createTable(Sname. Squery)
queryMysql("CREATE TABLE IF NOT EXISTS Sname(Squery)");
echo " Sname' < />":

function queryMysql(Squery)
Sresult = mysql_query($query) or die(mysql_error());
return Sresult;

fu n c tio n d e s tro y S e s s io n O

header.php

499

$_SESSION=a():
i f (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(). . timeO-2592000.
session_destroy():
}
function sanitizeString(Svar)
{
$var = strip_tags($var);
$var = htmlentities($var):
$var = stripslashes(Svar):
return mysql_real_escape_string($var);

function showProfile($user)
{
i f (file_exists("Suser.jpg"))
echo "<img src='$user.jpg' a1ign='1e ft' />";
Sresult = queryMysql("SELECT * FROM profiles WHERE user=' Suser'"):
i f (mysql_num_rows($result))
{
$row = mysql_fetch_row($result);
echo stripslashes($row[l])
"<br clear=left /><br />";
}
}
?>

header.php
,
.
header.php, 21.2.
, , ,
functions.php.
.
header.php sessi on start.
12 , ,
, -.
osc. js JavaScript- , S , 20.
,
' user'. , ,
Sloggedin TRUE.

500

21.

$1oggedi i f
.
, Si gn up
Log i ,
. , ,
.
, ,
$user, , ,
.
, , sty 1es css,
. ,

.
21.2. header.php

<?php // header.php
session_start():
echo "<!D0CTYPE html>\n<html><head><script src='0SC. js'x/script^ ":
include 'functions.php';
Suserstr = ' (Guest)';
i f (isset($_SESSI0N['user']))
{
$user = $_SESSION['user'];
$1oggedin = TRUE:
$userstr = " (Suser)";
}
else $1oggedin = FALSE:
echo "<title>$appname$userstr</title><link rel ='stylesheet"'
"href='styles.css' type='text/css' />" .
"</head><body><div class='appname'>$appname$userstr</div>":
i f (Sloggedin)
{
echo <br ><ul class='menu,>" .
"<1i><a href='members.php?vi ew=$user>Home</a></1i >"
"<li><a href='members.php>Members</a></li>" .
"<1i><a href=' friends.php'>Friends</a></1i >".
"<li><a href=,messages.php,>Messages</a></li>,, .
"<li><a href='profile.php>Edit Profile</a></li>" .
"<li><a href='logout.php'>Log out</a></li></ul><br />";
}
else
{
echo ("<br /xul class=,menu'>" .
"<li><a href=,index.php,>Home</a></li>n .
"<li><a href='signup.php>Sign up</a></li>"

setup.php

501

"<li><a href='login.php'>Log in</a></li></ul><br />" .


<span class='info>&#8658; You must be logged in to "
"view this page.</span><br /xbr />"):
11

4
f

<br/>, , ,
.
, -, ,
CSS.

setup.php

M yS Q L-. 21.3, setup,
php,
,
MySQL.
:
members user ( ), pass;
messages id ( ), auth
( ), recip, pm,
message;
friends user ( ),
- friend;

0 prof i 1es user ( ), About me (


) text.
createTable
,
.
,
.
M ySQL DROP TABLE.
21.3. setup.php

<html><head><ti11e>Setting up database</titlex/head><body>
<h3>Setting up...</h3> // ...
<?php // setup.php
1 nclude_once 'functions.ph p ':
createTable('members

502

21.

user VARCHAR(16).
pass VARCHAR(16).
INDEX(user(6))'):
createTableCmessages'.
'id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY.
auth VARCHAR(16).
recip VARCHAR(16).
pm CHAR(l).
time INT UNSIGNED.
message VARCHAR(4096).
INDEX(auth(6)).
INDEX(recip(6))'):
createTable('friends'.
user VARCHAR(16).
friend VARCHAR(16).
INDEX(user(6)).
INDEX(friend(6)) );
createTable('profi1es'.
'user VARCHAR(16).
text VARCHAR(4096).
INDEX(user(6))'):
?>
<br />.. .done. //
</body></html>

index.php
, ,
. .
, ,
.
, M ySQ L- ,
21.4, index.php, ,
.
, . 21.1.
21.4. index.php

<?php // index.php
i nc1ude_once header.php':
echo "<br /><span class='main'>Welcome to Rob-ins Nest.":
//
if ($1oggedin) echo " Suser. you are logged in.":

signup.php

503

11
else
?>

echo ' please sign up and/or log in to join in . :


// , ()

' /span><br />< /></body></ html>

. 21.1.

signup.php
,
, 21.5, signup.php. ,
.
H TM L, .
, .
<5>- '
i nfo1. Ajax-,
,
, .
17.



, JavaScript,
checkUser. JavaScript onBlur,

username. span-

504

21.

( id ' in fo ') ,
, - .
checker.php,
user. Ajax-
<$>-
' i nfo'.
JavaScript P H P -, 16,
.
sanitizeString,
,
, Suser Spass
.
.

,
. ,
.
CSS- fieldname,

. ( checkuser.php)
, . 21.2, ,
Ajax- Robin .
, ,
text password.
21.5. signup.php

?php // signup.php
i nc Iude_once ' header.php' :
echo <<<_END
'-script*
function checkUser(user)
{
if (user.value == '')
{
0( info ).innerHTML - ''
return

params = "user=" + user.value


request - new ajaxRequestO
request.open("POST . "checkuser.php". true)
request.setRequestHeader("Content-type".
"appli cation/x-www-form-ur1encoded")
request.setRequestHeader("Content-1ength". params.1ength)
request.setRequestHeader("Connection". "close")
re q u e s t .o n re ad y s ta te ch an g e = f u n c t i o n O

signup.php

{
i f (this.readyState == 4)
i f (this.status == 200)
i f (this.responseText != null)'
0(' in fo ') .innerHTML = this.responseText

request.send(params)

.function ajaxRequest()

{
try {var request = new XMLHttpRequestO}
catch(e l){
try {request = new ActiveX0bject("Msxml2.XMLHTTP")}
catch(e2){
try {request = new ActiveXObjectCMicrosoft.XMLHTTP")}
catch(e3){
request = false
}}}
return request
}
</script>
<div class=,main'><h3>Please enter your details to sign up</h3>
// , ,
_END;
Serror = Suser = Spass =
i f (isset(S_SESSION['user'])) destroySessionO;
i f (isset($_P0ST[user']))
{
Suser = sanitizeString($_POST[user']);
Spass = sanitizeString(S_POST['pass']);
i f (Suser = "" || Spass == "")
Serror = " < />< />";
else
{
i f (mysql_num_rows(queryMysql("SELECT * FROM members
WHERE user-'Suser"')))
Serror = " < /><br />";
else
{
queryMysql("INSERT INTO members VALUES('Suser'.
'Spass')");
die("<h4>Account created</h4>Please Log in.<br />
<br />");
// .
// ,
}
}

505

506

21.

}
echo <_END
<form method='post' action='signup.php'>$error
<span class= fieldname'>Username</span>
<input type='text maxlength=,16' name= user value='$user'
onBlur='checkllser(this) 7><span id=' info'></span><br />
<span class='fieldname'>Password</span>
<input type='text' maxlength='16' name=pass'
value='Spass' /><br />
_END;
?>
<span class=' fieldname'>&nbsp;</span>
<input type='submit' value='Sign up' />
</form></div><br /></body></html>
^
httpr/Zlocalhost/sigmJp.php

: file

dit

View Favorites

Tools

Robin's Nest (Guest)

JjeJp

Home }[sign up ) [log in )


- You must be logged In to view this page.
Please enter your details to sign up
Usernam e

R o b in ______________ Th is usernam e is available

Passw ord

m ypassw ordl
1Sign

mp

. 21.2.

-- |>


, ,
.
-, MD5 .
12.

checkuser.php
checkuser.php, 21.6,
signup, php. ,

login.php

507

, ,
- .
sani ti zeStri ng queryMysql,
functi ons.php. ,
S P0ST, ' user', - ,
. ,
,
, (Sorry, already taken),
(Username available).
, mysql num rows. ,
, , ,
.
,
H T M L - &#2718; &#2714;.
21.6. checkuser.php

<?php // checkuser.php
i nclude_once 'functi ons.php';
i f (isset($_P0ST['user']))
{
$user = sanitizeString(S_POST[user']):
i f (mysql_num_rows(queryMysql("SELECT * FROM members
WHERE user=,$user'")))
echo "<span class='taken>&nbsp;&#x2718: " .
"Sorry, this username is taken</span>":
// ,
else echo "<span class='available,>&nbsp;&#x2714; ".
"This username is available</span>";
//
}
?>

login.php

logi n.php, 21.7, ,
. , ,
, H T M L -,
, sani ti zeStri ng
MySQL.

( ' user' ' pass')
.
,
.

21.

508

, ,
die. ,
: echo exit.
( ),
, mai .
, ,
. 21.3. ,
<i nput /> password,
.
21.7. login.php

<?php // login.php
i nclude_once 'header.php';
echo "<div class=,main'>
<h3>Please enter your details to log in</h3>":
// , ,
Serror = Suser = Spass =
i f (isset(S_P0ST[user']))
{
Suser = sanitizeStri ng($_P0ST[' user]):
Spass = sanitizeString(S_POST['pass']):
i f (Suser ==
|| Spass = "")
{
Serror = "Not all fields were entered<br />";
//
}
else
{
Squery = "SELECT user.pass FROM members
WHERE user='Suser' AND pass='Spass ":
i f (mysql_num_rows(queryMysql(Squery)) == 0)
{
Serror = "<span class='error'>Username/Password
invalid</span><br /xbr />";
// " - "
}
else
{
$_SESSI0N[user'] = Suser;
S_SESSI0N['pass'] = Spass;
dieC'You are now logged in . .
"Please <a href='members.php?view=Suser'>" .
"click here</a> to continue.<br /><br />);
// . ,
}
}

profile.php

509

}
echo <_END
<form method='post' action='login.php'>$error
<span class='fieldname,>Username</span><input type=text'
maxlength='16 name=,user' value= $user' /xbr />
-span class='fieldname'>Password</spanxinput type*'password*
maxlength='16 name='pass value='$pass' />
_FND:
?>
<br i '
<span 1ass=' fi eldname'>&nbsp:</span>
<input type='submit' value='Login' />
</form><br /></div></body></html>

file

dit

h ttp ://lo calh o st/lo g in .p h p

yiew

Favorites

Tools

-r X j

Robins N e st (6u e t )

------ ^
~
q yv ^

Help

Home|(Sign up)[Login)
=>You roustbe logged in tio vfew thls page.

i I

!\
i
!I

Please enter your details to log in


Username

Robin

Password

. 21.3.

profile.php

. profi 1.php,
21.8. ,
,
, .

510

21.

H T M L -, .
, ,
enctype=' mul ti part/form-data .
, .
<i nput />, fi 1,
. ,
.
,
. , ,
.
.

About Me ( )
' text', ,
POST-. ,
. ,
, (
) .
, ,

, About Me
( ), .
,
, ,
.


, $_FILES
. ,
Ssaveto. ,
JPG. ,
Ji 11 $saveto J i l l . jpg.
, ,
.
,
, JPEG-, PNG- G IF-.
, Stypeok
FALSE,
. ,
Ssrc.
imagecreatefrom, .
,
.

profile.php

511


$w $h ,
,
:
list($w. $h) = getimagesize(Ssaveto):
$max ( 100)
,
, , 100 .
$tw $th .

$.
imagecreatetruecolor,
Stw Sth $tmp.
imagecopyresampled,
, Ssrc, ,
$tmp.
,
imageconvolution, .
, J P E G - ,
$saveto,
, ,
imagedestroy, .


, showProfi le
functions.php, ,
, .
H T M L. , .
CSS ,
, .
, 21.8,
. 21.4. ,
About me ( ).
21.8. profile.php

<?php // profile.php
i nclude_once ' header.php':
i f (!$1oggedin) die():
echo <div class=,main,><h3>Your Profile<-/h3>":
//
i f (i sset($_P0ST['text' I))

512

21.

Stext = sani tizeStri ng($_P0ST['text1]);


Stext = preg_replace(7\s\s+/ . 1 '. Stext);
i f (mysql_num_rows(queryMysql("SELECT * FROM profiles WHERE user='Suser'")))
queryMysql("UPDATE profiles SET text='Stext' where user='Suser'");
else queryMysql("INSERT INTO profiles VALUES('Suser'. 'Stext')"):
}
else
{

Sresult = queryMysql("SELECT * FROM profiles WHERE user='Suser'"):


i f (mysql_num_rows(Sresult))
{
Srow = mysql_fetch_row(Sresult):
Stext = stripslashes(Srow[l]):
}
else $text =

}
Stext = stripslashes(preg_replace('/\s\s+/'. ' '. Stext)):
i f (isset(S_FILES[' image'] [ 'name']))
{
Ssaveto = "Suser.jpg":
move_uploaded_fi1e($_FILES[' image'] [ 'tmp_name'], $saveto):
Stypeok = TRUE;
switch($_FILES['image'] [ 'type'])
{
case "image/gif":
Ssrc = imagecreatefromgif(Ssaveto); break:
case "image/jpeg":
// , JPEG-
case "image/pjpeg": Ssrc = imagecreatefromjpeg(Ssaveto): break:
case "image/png":
Ssrc = imagecreatefrompng(Ssaveto): break;
default:
Stypeok = FALSE; break;
}
i f ($typeok)
{
list($w, Sh) = getimagesize(Ssaveto):
Smax = 100;
Stw = Sw;
Sth = Sh;
i f (Sw > Sh && Smax < Sw)
{
$th = $max / $w * Sh;
$tw = Smax:
}
elseif (Sh > Sw && Smax < Sh)

members.php

513

{
$tw = $max / $h * $w:
$th = Smax:

}
elseif (Smax < $w)

{
Stw = Sth = Smax:

}
$tmp = imagecreatetruecolor($tw. Sth):
imagecopyresampled($tmp. Ssrc. 0. 0. 0. 0. Stw. Sth. Sw. Sh);
imageconvolution(Stmp. array(array(-l. -1. -1).
(-1. 16. -1). (-1. -1. -1)). 8. 0):
imagejpeg(Stmp, Ssaveto);
imagedestroy(Stmp);
imagedestroy(Ssrc);

showProfile(Suser);
echo <_END
<form method='post' action='profile.php' enctype='multi part/form-data'>
<h3>Enter or edit your details and/or upload an image</h3>
// ()
<textarea name='text' cols='50' rows=,3>Stext</textarea><br />
_END;
?>

members.ptu)
members .php, 21.9,

( , ).
: ,
.


GET-, vi ew'.
, , -
, showProfi 1,
.


GET- ' add' ' remove'.
, ,

514

21.

, .
MySQL- fri ends
.

|http://localhost/profile.php________________ ^ X j

file

Edit

View

Favorites

Tools

Robin's Nest (Robin))

Hdp

n s N ^ s t iR o b in )

Home)[Members|[Friends|[Messages{[Edit Profile)[Log out|

Your Profile
Hi, Im Robin. Welcome to my Nest1.

Enter or edit your details and/or upload an image


Hi, I'm Robin. Welcome to my Nest'.

Image:

Browse...

1 Save Profile

$%
. 21.4.

,
, sanitizeString,
MySQL.


SQL-
.
$num.
for

friends ,
.
,
.

members.php

515

$tl ,
, $t2
, .
,
,
, .
,
. ,
. ,
. ,
.
,

.
21.9 ,
. 21.5. ,
,
(follow), ,
recip (),
.
, drop ()
.
21.9. members.php

<?php // members.php
i nclude_once ' header.php';
i f (!$loggedin) die();
echo "<div class=,main,>";
i f (isset($_GET[view ]))
{
$view = sanitizeString($_GET['view']);
i f (Sview == $user) Sname = "Your";
else
Sname = "Sview's";
echo "<h3>Sname Profile</h3>";
showProfile(Sview);
echo "<a class='button' href='messages.php?view=$view,>"
"View Sname messages</a><br /><br />";
die("</div></body></html>");
}
i f (isset($_GET[add']))
{
$add = sanitizeString($_GET['add']):

516

21.

i f (!mysql_num_rows(queryMysql ("SELECT * FROM friends


WHERE user='$add' AND friend='Suser"')))
queryMysql ("INSERT INTO friends VALUES CSadd'. 'Suser')"):
}
elseif (isset(S_GET['remove']))
{
Sremove = sanitizeString($_GET[' remove']):
queryMysql("DELETE FROM friends WHERE user='Sremove' AND friend=Suser
}
Sresult = queryMysql("SELECT user FROM members ORDER BY user"):
Snum
= mysql_num_rows($result):
echo "<h3>Other Members</h3><ul>": II
for (Sj = 0 : Sj < Snum : ++$j)
{
Srow = mysql_fetch_row(Sresult):
i f ($row[0] = Suser) continue:
echo "<li><a href='members.php?view=Srow[0]'>Srow[0]</a>";
Sfollow = "follow": II
Stl = mysql_num_rows(queryMysql("SELECT * FROM friends
WHERE user='$row[0]' AND friend='Suser'")):
St2 = mysql_num_rows(queryMysql("SELECT * FROM friends
WHERE user='Suser' AND friend='$row[0]'"));
i f ((Stl + St2) > 1) echo " &harr: is a mutual friend":
II ,
elseif (Stl)
echo " &larr: you are following":
II
,
elseif (St2)
{ echo " &rarr: is following you":
Sfollow = "recip": }
// ,
i f (!Stl) echo " [< href=members.php?add=".Srow[0]
else
echo " [<a href='members. php?remove='\$row[0]
//

." '>$follow</a>]M:
." >drop</a>]";

}
?>
<br /></div></body></html>

, ,
, ,
About me ( ),
. .

517

friends.php

| h ttp ^ /lo c a lh o s t/m e m b e rs .p h p ? a d d : P


File

dit

View

Favorites

Io o ls

^ S

[|

R obin's N est (Robin)

___

U dp

Home |[Members| |Friends]

Edit ProfileI [Log out)

Other Members

Alex -M Is a mutual friend [drop]


Fred [follow]
Martha [follow]
Martin - you are following [drop]
Mary [follow]
SandraD - is following you [redp]
Trevor [follow]
<uoox . 21.5.

friends.php
friends.php,
, 21.10.
friends, ,
members php, .

, ,
.
, ,
$followers, , ,
Sfol 1owi ng. ,
,
:
Smutual = array_intersect(Sfollowers. Sfollowing):
array intersect ,
, , .
$mutual.
array di f f Sfol 1owers Sfol 1owi ng,
, :
Sfol lowers = arraydi f f (Sfol 1owers. Smutual);
Sfollowing = array_diff($following, Smutual):

518

21.

$mutual ,
$fol 1owers , (
), $fol 1owi ng ,
( ).

. . 21.6.
si zeof .
, (
). ,
$namel, $name2 $name3
, () ,
Your () You are (),
.
,
.
21.10.

friends.php

<?php // friends.php
i nclude_once 'header.php':
i f (!$1oggedin) die():
i f (isset(S_GET[' view'])) $view = sanitizeString($_GET['view']):
else
$view = Suser;
i f (Sview == Suser)
{
Snamel = Sname2 = "Your":
//
Sname3 =
"You are": //
}
else
{
Snamel = "<a href=,members.php?view=$view,>$view</a> s";
Sname2 = "Sview's":
Sname3 = "Sview is";
1
echo "<div class=main,>";
// ,
//
// showProfile(Sview):
Sfol lowers = arrayO:
Sfol lowing = arrayO ;
Sresult = queryMysql("SELECT * FROM friends WHERE user='Sview'"):
Snum
= mysql_num_rows(Sresult):
for (Sj - 0 ; Sj < Snum ; ++$j)

friends.php

$row
= mysql_fetch_row(Sresult);
$followers[$j] = $row[l]:
}
Sresult = queryMysql("SELECT * FROM friends WHERE friencKSview'"):
Snum
= mysql_num_rows(Sresult):
for (Sj = 0 ; Sj < Snum : ++$j)
{
Srow
= mysql_fetch_row(Sresult):
Sfollowing[Sj] = $row[0]:
}
Smutual
Sfollowers
Sfollowing
Sfriends

= array_intersect($followers. Sfollowing):
= array_diff($followers. Smutual):
= array_diff(Sfollowing. Smutual):
= FALSE:

if (sizeof(Smutual))
{
echo "<span class='subhead'>Sname2 mutual friends</span><ul>":
//
foreach(Smutual as Sfriend)
echo "<li><a href='members.php?view=$friend'>Sfriend</a>":
echo "</ul>":
Sfriends = TRUE:

i f (sizeof(Sfollowers))
{
echo "< span class='subhead'>Sname2 followers</span><ul>":
// ...
foreach(Sfollowers as Sfriend)
echo "<li><a href=members.php?view=Sfriend'>Sfriend</a>":
echo "</ul>":
Sfriends = TRUE:
}
i f (sizeof(Sfollowing))
{
echo "< span class='subhead'>Sname3 following</span><ul>":
// ...
foreach(Sfollowing as Sfriend)
echo "<li><a href='members.php?view=Sfriend'>Sfriend</a>":
echo "</ul>":
Sfriends = TRUE:

i f (!Sfri ends) echo "<br />You dont have any friends yet.<br /><br />"
//

519

520

21.

echo "< class='button' href=,messages.php?view=$view,>" .


"View $name2 messages</a>";
?>
</div><br /></bodyx/html>

| h t tp :/ / lo c a lh o s t/ fr ie n d s .p h p P ~ S X 1 1 Robin's Nest (Robin)

... -IP,,!!

file

d it

View

Favorites

lo o k

(of

*&;,>,;,

H elp

Home)|Members| Friends] Messages!| Edit Profile)[Log out|


Your mutual friends
Alex

Your followers
SandraD
You are following
Martin

View Your messages]


Uoo%
. 21.6,

messages.php
, messages.php, 21.11.

POST-, ' text'. ,
messages. ,
' pm .
. , .
,
(private)
(public) . :
, ,
.
MySQL. ,
, whispered ()
.

messages.php

521

, :
(refresh the messages) ,
, (view the user's
friends). Snamel $name2,


)().
. 21.7.
, , ,
, (erase)
.
21.11. messages.php

<?php // messages.php
i nclude_once header.php':
i f (!$1oggedin) die():
i f (isset($_GET['view'])) Sview = sanitizeString($_GET['view']);
else
Sview = Suser:
i f (isset($_P0ST[text']))
{
$text = sanitizeString($_POST['text']):
i f ($text != "")
{
$pm = substr(sanitizeString($_POST['pm']).0.1):
$time = timeO:
queryMysql("INSERT INTO messages VALUES(NULL. 'Suser'.
'$view'. '$pm'. Stime. '$text')"):
}
}
i f (Sview != '')
{
i f (Sview == Suser) Snamel = Sname2 = "Your ; //
else
{
Snamel = "<a href=,members.php?view=$view,>$view</a>,s";
Sname2 = "Sview's":
}
echo "<div class='main,><h3>Snamel Messages</h3>";
//
showProfile(Sview);
echo <_END
<form method=,post action='messages.php?view=Sview>
Type here to leave a message:<br />
// ,

522

21.

<textarea name='text' cols=,40' rows=,3,></textareaxbr />


Public<input type='radio' name='pm' value='0 checked='checked' />
Private<input type='radio' =' value='l' />
<input type='submit' value='Post Message' /></form><br />
//
_END;
i f (isset($_GET['erase']))
{
$erase = sanitizeString($_GET['erase']);
queryMysql("DELETE FROM messages WHERE id=$erase AND recip='Suser'");
}
Squery = "SELECT * FROM messages WHERE recip='Sview' ORDER BY time DESC":
Sresult = queryMysql(Squery);
Snum
= mysql_num_rows(Sresult):
for (Sj = 0 ; Sj < Snum : ++$j)
{
Srow = mysql_fetch_row(Sresult);
i f (Srow[3] == 0 || Srow[l] Suser || Srow[2] == Suser)
{
echo date('M jS \'y g:ia :'. $row[4]):
echo " <a href='messages.php?view=$row[l]>$row[l]</a> ":
i f ($row[3] == 0)
echo "wrote: &quot;$row[5]&quot; ";
//
else echo "whispered: <span class='whisper'>"
"&quot:$row[5]&quot:</span>
//
i f ($row[2] == Suser)
echo "[<a href=messages.php?view=$view" .
"&erase=$row[0]>erase</a>]":
//
echo "<br />":
}
}
}
i f (!$r>um) echo "<br /><span class='info>No messages yet</span><br
/><br />";
//
echo "<br />< class='button' href=,messages.php?view=$view>Refresh messages</a>".
//
"<a class='button href='friends.php?view=$view'>\/iew Sname2 friends</a>":?>
</div><br /></body></html>

523

logoutphp

file

& )\ http;//localhost/messages.php?viev\
Edit

View

favorites

lo o k

- X Robins Nest (Robin)

Help

[Hom e) M em bers) ( Frien ds)(M essages][Edit Profile) Log but)

Your Messages
Hi, I'm Robin. W elcome to my Nest'.

Type here to leave a message:

Public Private [P o st Message j


Apr 17th '12 10:49am: Alex wrote: "This seem s to be working
w ell..." [erase]
Apr 6th '12 12:52pm: Mary whispered: "Hiya\n[erase]
[ Refresh m essages ] [View Your frie n d s)
100%

. 21.7.

logout.php
1ogout.php, 21.12,
.
, cookie. . 21.8,
.
, ,
, ,
. ,
JavaScript ,
, .
21.12. logout.php
<?php // logout.php
i nclude_once 'header.php';
i f (isset($_SESSI0N['user']))
{
destroySessionO:

524

21.

echo "div class=main'>You have been logged out. Please " .


"<a href='index.php'>click here</a> to refresh the screen.";
// . ...
// ... ,
}
else echo "<div class=main'><br />" .
"You cannot log out because you are not logged in":
// .
//
?>
<br /><br /></div></body></html>
!
IK
|^) http://localho5tflogout.php
File fdit View 1
Favorites loots Help

2
X | Robin'sNest(Robin)

X):':

{Ju

Home) Members) Friends] Messages) Edit Profile) Log out)


i
j!

You have been loaaed out. Please click here to refresh the screen.

;il__
||

*Uoo% - ;J
. 21.8.

styles.css
, , 21.13.
.
*
.
body , ,
.
html H TM L.
i mg , .
1i , .button <>,
<1i >, , button.
1i :ahover .button:hover
<1i> , button,
.
.appname , appname,
, , ,
.

styles.css

525

.f i el dname , fi el dname,
.
.mai , .
. i nfo : ,
, ,
.
.menu 1i , .button <1i >
, button, , ,
, , ,
( ).
.subhead .
.taken, .available, .error .whisper ,
.
21.13.
/* styles.css */
* {
font-family:verdana.sans-seri f ;
font-size :14pt; }
body {
width
:700px;
position relative:
margin
:7px auto;
background;#f8f8f8;
border
;lpx solid #888; }
html {
background;#fff }
img {
border
:lpx solid black;
margin-right
;15px;
-moz-box-shadow
:2px 2px 2px #888;
-webkit-box-shadow;2px 2px 2px #888;
box-shadow
:2px 2px 2px #888; }
l i a, .button {
text-decoration:none; }
li a;hover, .button;hover {
col or;green; }
.appname {
text-align ;center;
background ;#eb8:
color
:#40d;

526

21.

font-fami 1 :helveti ca;


font-size :20pt;
padding
:4px; }
.fieldname {
float:left;
width:120px; }
.main {
margin-left:40px; }
.info {
background
color
border
padding
margin-left

lightgreen;
blue;
lpx solid green;
5px ;
40px; }

.menu li , .button {
display
padding
border
background
color
margin-right
border-radius
-moz-box-shadow
-webkit-box-shadow
box-shadow

inline;
4px 6px;
lpx solid #777;
#ddd;
#d04;
8px;
5px;
2px 2px 2px
2px 2px 2px
2px 2px 2px #888;

.subhead {
font-weight:bold; }
.taken, .error {
col or:red; }
.available {
color:green; }
.whisper {
font-style:italic;
color
:#006600; }
, , . -
, ,
- , , - ,
.
,
, ,
.
, .