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

2-

-
-
2012

681.3.068+800.92PHP
32.973.26-018.1
89

, . .
89

PHP / . . , . . .
2- ., . . .: -, 2012. 400 .: .
ISBN 978-5-9775-0445-4
PHP,
Web-. , . PHP 5
.
. PHP- Web Apache MySQL, ,
AJAX, jQuery. HTTP-, ReWrite, PHP.
Web-, , Flash PDF, .
Web-
681.3.068+800.92PHP
32.973.26-018.1

:

.
.

30.09.11.
70 1001/16. . . . . 32,25.
1500 .
"-", 190005, -, ., 29.
-
77.99.60.953..005770.05.09 26.05.2009 .
.

" ""
199034, -, 9 , 12

ISBN 978-5-9775-0445-4

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

............................................................................................................................ 9
....................................................................................................................... 10
............................................................................................................................... 10

1. Web- Apache, PHP


MySQL ............................................................................................................. 11
1.1. , PHP- ............................................................................ 11
1.2. PHP .................................. 12
1.3. ........................................................................................................ 12
1.3.1. PHP ........................................................................................................ 13
1.3.2. Apache .................................................................................................... 13
1.3.3. MySQL ................................................................................................... 14
1.4. Web- Apache ............................................................................................ 14
1.5. ............................................................................................ 19
1.6. Web- Apache ................................................. 22
1.7. Apache ........................................................................... 24
1.8. PHP ....................................................................................................................... 24
1.9. , Web- ............................................................ 29
1.10. MySQL .................................................................................................... 30
1.11. MySQL .............................................................................. 35
1.12. MySQL ............................................................................... 42
1.13. MySQL ..................................................................... 43
1.14. my.ini ......................................................................................... 44
1.15. PHP MySQL .................................................................................................. 48
1.16. mysql ............................................................................ 50
1.17. ................................................................................................. 53

2. ......................................................... 55
2.1. PHP .......................................................................................................................................... 55
2.1.1. php.ini ........................................................... 55
2.1.2. PHP ................................................................................................ 56
2.1.3. ............................................................................................ 59
2.1.4. PHP- ................................................................................. 64
2.1.5. ............................................................................................... 66

2.1.6. ....................................................................................... 67
2.1.7. ................................................................................................ 67
2.1.8. ....................................................................................................... 68
2.1.9. ............................................................... 74
2.1.10. ......................................................................................................... 78
2.1.11. .......................................................................................................... 79
2.1.12. ........................................................................................ 79
2.1.13. ....................................................................................................... 80
2.1.14. ....................................................................................... 81
2.1.15. php.ini Apache ..................................................... 81
2.1.16. PHP .......................................................... 83
2.1.17. PHP ........................................................................ 86
2.1.18. ..................................................................... 89
2.2. Apache ..................................................................................................................................... 92
2.2.1. .htaccess ............................................................................ 92
2.2.2. ......................................................................... 93
2.2.3. ........................................................................................... 95
2.2.4. PHP- HTML- .................................................................... 98
2.2.5. Web- Apache .................................................................... 98
2.2.6. ........................................................................................................... 100
2.2.7. ....................................................................................... 101
2.2.8. ............................................................................................. 103
2.2.9. ............................................................................................... 103
2.2.10. URL- ................................................................................ 105
2.3. MySQL .................................................................................................................................. 116
2.3.1. mysql............................................................................................ 116
2.3.2. ......................................................................... 120
2.3.3. MySQL ..................................................................................... 121
2.3.4. .............................................................. 122
2.3.5. ......................... 127
2.3.6. ............................................................... 128
2.3.7. .................................................... 128
2.3.8. phpMyAdmin............................................................................................ 131

3. ........................................................................................................ 133
3.1. ................................................................................................................. 134
3.1.1. array() .................................................................................................. 134
3.1.2. ................................................................... 136
3.1.3. : ........................................................................ 137
3.1.4. ....................................................... 137
3.1.5. ............................................................................................. 141
3.2. .................................................................................................... 142
3.3. ........................................................................................ 145
3.4. ? ..................................................................................................... 147
3.5. ? ....................................................................................... 147
3.6. ?................................................................... 148
3.7. ? ........................................................................... 149
3.8. ................................................................................................... 151
3.9. ................................................................................................... 152

3.10. ........................................................................................... 152


3.11. .............................................................................................................. 154
3.12. .................................................................... 157
3.13. ..................................................................... 159
3.14. ........................................................ 159
3.15. ......................................................................................................... 162
3.16. .......................................................................................... 170
3.17. ................................................................................................ 173
3.18. $_GET...................................................................................... 174
3.19. ................................................................................................... 178
3.20. $_POST.................................................................................... 181
3.21. . $_FILES................................... 182
3.22. ................................................................... 186
3.23. Cookie. $_COOKIE ................................................................. 188
3.24. Cookie ? ....................................................................... 191
3.25. . $_SESSION ................................................................ 192
3.26. . $_SERVER .............................................................. 195
3.26.1. $_SERVER['DOCUMENT_ROOT'] ........................................................ 196
3.26.2. $_SERVER['HTTP_ACCEPT'] ................................................................ 196
3.26.3. $_SERVER['HTTP_ACCEPT_LANGUAGE'] ......................................... 197
3.26.4. $_SERVER['HTTP_HOST'] ..................................................................... 198
3.26.5. $_SERVER['HTTP_REFERER'] ............................................................. 198
3.26.6. $_SERVER['HTTP_USER_AGENT'] ...................................................... 199
3.26.7. $_SERVER['REMOTE_ADDR'] .............................................................. 199
3.26.8. $_SERVER['SCRIPT_FILENAME'] ........................................................ 200
3.26.9. $_SERVER['SERVER_NAME'] ............................................................... 200
3.26.10. $_SERVER['REQUEST_METHOD'] .................................................... 201
3.26.11. $_SERVER['QUERY_STRING'] ............................................................ 201
3.26.12. $_SERVER['PHP_SELF'] ..................................................................... 202
3.26.13. $_SERVER['REQUEST_URI'] .............................................................. 202

4. ....................................................................................... 203
4.1. .................................................................................................................. 203
4.2. ....................................................................... 208
4.3. , .......................................................... 209
4.4. .............................................................................................. 210
4.5. ...................................................................................................................... 217
4.6. ........................................................................................................................ 220
4.7. ...................................................................................................... 221
4.8. ................................................................. 222
4.9. .................................................................................................... 225
4.10. ................................................................ 227
4.11. ........................................................................... 229
4.12. ............................................................................................... 230
4.13. ................................................................... 231
4.14. .............................................................................................................................. 233
4.15. ...................................................................... 234
4.16. ........................................................................................ 238
4.17. .................................................... 240

4.18. ......................................................................... 241


4.19. , ............................................................. 242

5. ................................................................................ 243
5.1. ................................................................................................. 243
5.2. .................................................................................................................. 244
5.3. HTTP- .............................................................................................. 248
5.4. ............................................................. 252
5.5. CURL ................................................................................................................ 252
5.6. ............................................................................................... 259
5.7. Yandex ................................................................................................. 260
5.8. Google .................................................................................................. 261
5.9. .................................................................................. 262
5.10. POST ..................................................................................... 266
5.11. ............................................................................................................. 269
5.12. ................................................................................. 272
5.13. cookie .................................................................................................................. 273
5.14. IP- ..................................................................... 276
5.15. IP- ..................................................................... 278
5.16. IP- .............................................................................. 278
5.17. ....................................................................................... 281
5.18. ........................................................................................... 282
5.19. .......................................................... 285

6. MySQL ...................................................................................... 288


6.1. SQL ...................................................................................................................... 288
6.2. , ........................................................ 289
6.3. , .................................................................. 291
6.4. . INSERT................................................................... 295
6.5. ............................................................................................ 297
6.6. . SELECT ............................................................................. 298
6.6.1. . AS ..................................................... 298
6.6.2. . WHERE.......................................................... 299
6.6.3. . ORDER BY ................................................. 300
6.6.4. ....................................................................... 301
6.6.5. . LIMIT ...................................................... 301
6.7. . UPDATE ........................................................................... 302
6.8. . DELETE ............................................................................... 303

7. MySQL ........................................................................ 305


7.1. ............................................................................. 305
7.2. ............................................................................................................................. 307
7.3. MySQL .................................................................................................................. 310
7.3.1. MySQL ........................................................................................................... 310
7.3.2. ................................................................................. 311
7.3.3. ............................................... 312
7.3.4. ........................................................................................... 313
7.3.5. ............................................................................................... 313
7.3.6. ................................................................................ 315
7.3.7. IP- ........................................................................... 316

7.4. ....................................................................................... 317


7.5. ............................................................................................................. 318
7.6. , .................................................... 322
7.6.1. IN .................................................................................................... 322
7.6.2. ANY ................................................................................................. 324
7.6.3. ALL ................................................................................................. 325
7.7. . HAVING ................................................................. 326
7.8. SELECT ................................................................................... 328
7.9. .................................................................................. 330
7.10. DELETE .................................................................................... 331
7.11. ................................................................................... 333

8. PHP MySQL .............................................................................................. 335


8.1. .............................................................................. 335
8.2. ............................................................................................................. 338
8.3. SQL- ................................................................................................. 339
8.4. .......................................................................................... 341
8.5. ................................................................................................ 348
8.6. . SQL-............................................................................. 350

9. PHP AJAX.................................................................................................. 357


9.1. AJAX .................................................................................................................... 357
9.2. jQuery ................................................................................................................... 358
9.3. .............................................................................................................. 360
9.4. ................................................................................ 362
9.5. .................................................................................... 366
9.6. AJAX- ......................................................................................... 367
9.7. POST ....................................................................................... 372
9.8. ............................................................................................ 377
9.9. ....................................................................................... 380

10. PHP ........................................................ 383


10.1. ................................................................................................................................. 383
10.2. ...................................................................................................................... 385
10.3. ................................................................................................ 386
10.4. ........................................................................................ 387
10.5. ................................................................................................ 389

.................................................................................................................. 391
.............................................................................................. 392


, , , : , , , . ( -
, PHP 5/6, ).
, , . ,
Web-
, . Web-
. PHP,
, , , ,
PHP AJAX-.
,
Web-.
Web- Apache , ,
, , HTML, CSS JavaScript. ,
PHP .
, , . ,
,
. ,
PHP .

10


IT-
SoftTime, :
http://www.softtime.ru ;
http://www.softtime.org ;
http://www.softtime.info ;
http://www.softtime.biz .

,
PHP- http://www.softtime.ru/forum/.
http://www.softtime.org/forum/.
, PHP, , Web-,
. Web-, , . http://www.softtime.ru/
php5/index.php.

"-",
.
, , SoftTime.

Web- Apache,
PHP MySQL
, , .
Web-.

1.1. , PHP-
PHP . Web .
.
Web- HTML-
Web-, HTTP ,
. ,
PHP, Web- Apache.
PHP CGI-, , Web-,
PHP- . , PHP-
, . ,
.

. Web- Apache PHP
MySQL.
PHP, Web- Apache, MySQL-
UNIX- , . , UNIX.

12

, -.

1.2.
PHP
PHP, , Web-, , ,
Web-. Web, ,
, , . Web- , . ,
, Web- ,
. ,
. ,
PHP, Web- Apache MySQL, Denwer, http://www.denwer.ru/.

http://
www.softtime.ru/article/index.php?id_page=9. httpd.conf ( Apache) php.ini ( PHP). http://www.softtime.ru/forum/index.php?id_forum=5.

1.3.
(. 1.1).
1.1. PHP, Apache MySQL

Web-

PHP

http://www.php.net

Web- Apache

http://www.apache.org

MySQL

http://dev.mysql.com

, ,
.

Web- Apache, PHP MySQL

13

1.3.1. PHP
http://www.php.net,
downloads, http://www.php.net/
downloads.php. PHP
Complete Source Code, .
Windows Binaries, http://windows.php.net/download/.
Which version do I choose?
Visual Studio 6 Visual Studio 9. Web- Apache
VC6.

VC9 Web- Windows IIS.

Non Thread Safe Thread Safe. Thread Safe


PHP , Non Thread Safe
CGI-. , PHP (Thread Safe).
(Installer), PHP.
, PHP. ; . ,
(Russian Federation).
.

http://www.php.net PHP, .
documentation (http://www.php.net/docs.php) downloads
(http://www.php.net/download-docs.php). , .
Windows chm-,
.

1.3.2. Apache
, Web- Apache. http://www.apache.org, Download (http://www.
apache.org/dyn/closer.cgi).
HTTP- FTP-, Web- Apache.
, Apache httpd,
UNIX-. , :
httpd-2.2.15.tar.gz Linux,

14

httpd-2.2.15-win32-x86-openssl-0.9.8m-r2.msi

x86 Windows (win32) c SSL (openssl-0.9.8m-r2)


Apache (httpd) 2.2.15 .

Apache Windows
http://www.sai.msu.su/apache/httpd/binaries/win32/.

1.3.3. MySQL
MySQL http://dev.mysql.com/
downloads/.
MySQL:
MySQL 5.1 MySQL;
MySQL 5.5 , .
, - ,
(Generally Available Release) .
( Windows),
. Windows ( 32- 64- ):
MSI Installer Essentials ,
;
MSI Installer MySQL, ;
ZIP Archive MySQL .
MSI Installer ,
Windows-. .
MySQL
MySQL-,
http://dev.mysql.com/downloads/gui-tools/5.0.html.

1.4. Web- Apache


Apache Windows . , Apache. ,
, .
Microsoft Visual
Studio. ,
.

Web- Apache, PHP MySQL

15

httpd__win32_*_.msi
Microsoft Installer (. 1.1). ,
Next, (. 1.2).

. 1.1. Web- Apache

. 1.2.

16


Apache , (. 1.3).

. 1.3.

, . 1.4, :
, .
,
localhost. ,
IP- 127.0.0.1 Apache- httpd.conf
IP- 0.0.0.0, .
,
(80 8080).

localhost IP- 127.0.0.1, . IP- 127.0.0.1
(. . 1.5).

HTTP 80, ,
, 8080. 8080 , 80 Web- (, Skype).
(. 1.5): Typical Custom, .
(. 1.6) ,

Web- Apache, PHP MySQL

17

C:\Program Files\Apache Group. , ,


, C:\www\Apache2.2 (. 1.7).

. 1.4.

. 1.5.

18

. 1.6. Web-

. 1.7. Web-

, Install .
, Windows Apache.
ApachMonitor.

Web- Apache, PHP MySQL

19


ApachMonitor , .
, bin Apache.

, http://localhost.
"It works!" (. 1.8).

. 1.8. Web- Apache

1.5.
Web- Apache ,
. ,
HTML- PHP-. ,
HTML- PHP- ,
.
Web- IP-,
, . , http://localhost DNS- http://site.dev, http://project.dev . .
RU ( )
http://site.ru http://project.ru, ,
.
IP- 127.0.0.1,
Windows Vista Windows 7 IP- - . IP- 127.0.0.2.
C:/Windows/system32/drivers/etc/hosts.
, IP- ( 1.1).

20
1.1. hosts
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#

(C) (Microsoft Corp.), 1993-1999


HOSTS, Microsoft TCP/IP Windows.
IP- .
. IP-
,
. IP- .
,
(, ),
'#'.
:
102.54.94.97
38.25.63.10

127.0.0.1
127.0.0.1
127.0.0.1
127.0.0.1

rhino.acme.com
x.acme.com

#
# x

site.dev
www.site.dev
project.dev
www.project.dev

host . Apache,
.

www , IP- Apache ,
.

, Web- Apache,
conf, . httpd.conf. , #, .
1.2 , Include.
httpdvhosts.conf, extra.
1.2. httpd.conf
# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Web- Apache, PHP MySQL

21

httpd-vhosts.conf .
NameVirtualHost , IP- :
NameVirtualHost 127.0.0.1:80


IP- , Apache. ,
Web- , 80
8080. :
http://localhost:8080/index.html, , 80.

<VirtualHost>,
( 1.3).
1.3. <VirtualHost>
<VirtualHost 127.0.0.1:80>
ServerAdmin kuznetsov@softtime.ru
DocumentRoot D:/data
ServerName site.dev
ServerAlias www.site.dev
ErrorLog logs/dummy-host.example.com-error_log
CustomLog logs/dummy-host.example.com-access_log common
</VirtualHost>

,
NameVirtualHost. 1.3 ServerAdmin
.
Web- .
DocumentRoot
. D:\data\,
http://site.dev/.

,
.

ServerName , . ServerAlias ,
, www.
ErrorLog CustomLog (log-),
Web- Apache .
, httpd.conf <Directory /> 1.4.

22
1.4. , <Directory />
<Directory />
Options All
AllowOverride All
Order deny,allow
</Directory>

, Web-
(. . 1.61.7).

D:\data\ index.html ( 1.5).
1.5. index.html
index.html www.site.dev

,
http://www.site.dev, , . 1.9.

. 1.9. www.site.dev

1.6.
Web- Apache
80 (. . 1.4),
Apache .
| | | | . , . 1.10, Apache2.2. , .
Windows
. ,
(. 1.10), (. 1.11) .

Web- Apache, PHP MySQL

. 1.10. Windows

. 1.11. Web- Apache

23

24

1.7. Apache
Windows , Apache
:
Apache k start ();
Apache k restart ();
Apache k stop Apache k shutdown ().

bin Apache (C:\www\


Apache2.2\bin\). k
Apache. Apache k install Apache k uninstall Apache2.2.
Apache help
Apache.

, | | | . D:,
cd, , cd C:\www\Apache2.2\bin.

Apache -t Apache
.
"Syntax OK". , , :
Syntax error on line 57 of C:/www/Apache2.2/conf/ httpd.conf:
ServerRoot takes one argument, Common directory of server-related files.

Apache2.2 , , Web- NET:


NET START Apache2.2 ;
NET STOP Apache2.2 .

1.8. PHP
php--win32-installer.msi
Microsoft Installer (. 1.12).
, Next, (. 1.13). PHP (. 1.14).
, Web ,
Apache 2.2.x Module (. 1.15). Web- Apache (. 1.16).

Web- Apache, PHP MySQL

. 1.12. PHP

. 1.13.

25

26

. 1.14. PHP

. 1.15.

Web- Apache, PHP MySQL

27

. 1.16. ,
Web- Apache

, (. 1.17).
.

, , PHP,
PHP php.ini.

, Install PHP
httpd.conf. , , , 1.6.

, UNIX, /, \.

1.6. PHP httpd.conf


AddType application/x-httpd-php .php
PHPIniDir "C:/Program Files/PHP/"
LoadModule php5_module "C:/Program Files/PHP/php5apache2_2.dll"

28

. 1.17.

AddType php PHP. php ,


PHP-,
. PHPIniDir PHP php.ini, LoadModule
PHP Web- Apache 2.2.
. , , , http://site.dev/, http://sive.dev/
index.php. index.html.
, index.php,
httpd.conf DirectoryIndex 1.7.

httpd.conf .

1.7.
DirectoryIndex index.php index.html index.htm

DirectoryIndex , , index.htm, index.php3, index.phtml . .


PHP- PHP- index.php ( 1.8).

Web- Apache, PHP MySQL

29

1.8. PHP-
<?php
phpinfo();
?>

phpinfo() PHP. PHP


Web-, , . 1.18.

. 1.18. phpinfo()

, , phpinfo(),
php.ini. Loaded
Configuration File. , ,
, PHP (, ).

MySQL ,
http://www.softtime.ru/forum/index.php?id_forum=5.

1.9. ,
Web-
, ,

30

Web- . (
) , Web-

.
php.ini, , 1.9.
1.9. php.ini
[PHP_BZ2]
extension=php_bz2.dll
[PHP_CURL]
extension=php_curl.dll
[PHP_GD2]
extension=php_gd2.dll
[PHP_IMAP]
extension=php_imap.dll
[PHP_MBSTRING]
extension=php_mbstring.dll
[PHP_MYSQL]
extension=php_mysql.dll
[PHP_MYSQLI]
extension=php_mysqli.dll
[PHP_OPENSSL]
extension=php_openssl.dll
[PHP_PDO_MYSQL]
extension=php_pdo_mysql.dll
[PHP_PDO_ODBC]
extension=php_pdo_odbc.dll
[PHP_SOCKETS]
extension=php_sockets.dll

Web- , , . ,
,
. ,
.

php.ini 2.

1.10. MySQL
Windows
. , . 1.19.

Web- Apache, PHP MySQL

31

. 1.19.


MySQL Firewall,
, , MySQL .
MySQL , Firewall
3306 ( , ).

Next,
, . 1.20, :
Typical ();
Complete ();
Custom ().

, , .
Custom Next (. 1.21)
. , , . ,
This feature will be installed on local hard drive.
MySQL, .
, ,
. 1.21, , Change.

C:\Program Files\MySQL\MySQL Server 5.1\.

32

. 1.20. MySQL

. 1.21.

, ,
:\MySQL\. Change, :\MySQL\ (. 1.22).
MySQL , .
, -

Web- Apache, PHP MySQL

33

. , mysql
. MySQL,
:\mysql\data\mysql mysql. , , .

. 1.22. , MySQL-

. 1.23.

34

. 1.24.

, . 1.23. Install (. 1.24).



(. 1.25). , .

. 1.25. http://www.mysql.com

Web- Apache, PHP MySQL

35

1.11. MySQL
MySQL .
, , , | | MySQL | MySQL
Server 5.1 | MySQL Server Instance Config Wizard. ,
.
(. 1.26). Next
(. 1.27), :
Detailed Configuration ();
Standard Configuration ().

. 1.26. MySQL MySQL Server Instance Configuration Wizard

(Detailed
Configuration). Next MySQL (. 1.28) :
Developer Machine ( );
Server Machine ();
Dedicated MySQL Server Machine ( ).

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

36

. 1.27.

. 1.28. MySQL

, . 1.29, , . .

MySQL Server Instance Configuration Wizard :\MySQL5\my.ini, .

. 1.29 , , :
MyISAM InnoDB. ,
MyISAM ,

Web- Apache, PHP MySQL

37

, InnoDB , . , MyISAM
InnoDB. InnoDB , . MyISAM.
, , , . 1.30.

. 1.29.

. 1.30. InnoDB

38

(. 1.31) ,
. ( ) ,
20, 500 , .

. 1.31.

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


,
.

(. 1.32) ,
MySQL- ( 3306). MySQL, , . . 3306 MySQL.

Web- Apache, PHP MySQL

39


, MySQL-
MySQL, , , MySQL-.

(. 1.33).
cp1251, Windows-.

. 1.32. , MySQL

. 1.33. MySQL-

40

Windows MySQL ,
mysqld.exe
.
, . 1.34, .
Install As Windows Service , Service Name. ,
MySQL- , MySQL 5, . Launch the
MySQL Server automatic
, ,
.
. ,
.
Include Bin Directory in Windows PATH C:\MySQL\bin PATH,
.

. 1.34. MySQL-

(. 1.35) .
MySQL ,
Modify Security Settings
. root ( ).
Create An Anonymous Account . , .

Web- Apache, PHP MySQL

41

. 1.35.

MySQL- MySQL Server Instance


Configuration Wizard . 1.36.

. 1.36. MySQL Server Instance Configuration Wizard

Execute
C:\MySQL\my.ini MySQL.


MySQL ,
http://www.softtime.ru/forum/index.php?id_forum=3.

42

1.12. MySQL
MySQL ,
MySQL.
, | |
MySQL | MySQL Server 5.1 | MySQL Command Line Client.
, . 1.37.
<Enter>. mysql>,
:
SELECT VERSION();

. 1.37. MySQL Command Line Client

,
5.1.37-community (. 1.38).

EXIT.

MySQL cp1251, Windows-1251, MySQL Command Line


Client . my.ini, MySQL. MySQL . 1.10
1.11, C:\MySQL\my.ini.

my.ini . 1.14.

MySQL Command Line Client,


my.ini ,
default-character-set [mysqld]
[mysql] [client].

Web- Apache, PHP MySQL

43

. 1.38. SELECT VERSION()

1.13.
MySQL
MySQL, Apache (. . 1.6), , , |
| | | . MySQL ,
(. . 1.34). , .
MySQL (. 1.39).
, .

. 1.39.

44

. . :
Windows , ,
. , .

, MySQL- , mysqld.exe
.

1.14. my.ini
MySQL , .
. MySQL
ps -Af ,
. ,
. , --defaults-file 1.10 MySQL, my.ini
C:\mysql5\my.ini.

MySQL- ,
--standalone, , , .

1.10. --defaults-file
C:\mysql\bin\mysqld.exe --defaults-file="C:\mysql5\my.ini" --standalone

MySQL ,
. ,
MySQL --verbose --help. , . , --user
-u.
, my.ini,
. my.ini ,
, .
, my.ini
, . .
. # ;,
. .

Web- Apache, PHP MySQL

45

Windows ini ( C:\Windows\


C:\mysql5\), cnf ( C:).
UNIX- ,
, cnf.
MySQL, , mysql, SQL mysqldump . ., , MySQL. , [_]. ,
, , .
. 1.2 .
1.2. my.ini my.cnf

[mysqld]

MySQL

[server]

MySQL

[mysqld-4.0]

MySQL 4.0

[mysqld-4.1]

MySQL 4.1

[mysqld-5.0]

MySQL 5.0

[mysqld-5.1]

MySQL 5.1

[mysqld_safe]

mysqld_safe

[safe_mysqld]

mysqld_safe

[mysql.server]

mysql.server

[mysqld_multi]

mysqld_multi

[client]

[mysql]

mysql

[mysqldump]

SQL- mysqldump

[mysqlhotcopy]

[mysqld]
, , , ,
.
[client]
. , (,

46

),
,
.
1.11 my.ini,
Windows.
1.11. my.ini
# MySQL-
[mysqld]
# TCP/IP, MySQL-, 3306
# ,
port=3306
# MySQL-, ,
# ,
basedir="C:/mysql5/"
# ,
# , . .
# basedir
datadir="C:/mysql5/Data/"
#
# Windows-1251,
#
# latin1 ( )
default-character-set=cp1251
# ,
key_buffer_size = 128M
# ,
max_allowed_packet = 8M
# ,
query_cache_size = 64M
#
max_connections = 200

# MySQL
[client]
# IP- , ,
# IP- ,
# ,
# , Apache 80 ( 8080), MySQL, , 3306
port=3306

Web- Apache, PHP MySQL

47

# MySQL-
[mysqld]
# TCP/IP, MySQL-, 3306
# ,
port=3306
# MySQL-, ,
# ,
basedir="C:/MySQL/"
# ,
datadir="C:/Documents and Settings/All Users/Application Data/MySQL/MySQL
Server 5.1/Data/"
#
# Windows-1251,
#
# latin1 ( )
default-character-set=cp1251
# MySQL
# ,
# , ,
# ,
# .
#
default-storage-engine=MYISAM
# ,
key_buffer_size = 128M
# ,
max_allowed_packet = 8M
# ,
query_cache_size = 64M
#
max_connections = 200

my.ini, 1.11,
. .

48

1.15. PHP MySQL


Web- Apache, MySQL-
PHP, PHP MySQL. PHP , MySQL,
. PHP
MySQL:
php_mysql ;
php_mysqli - .

, php.ini , 1.12.
, .
1.12. MySQL-
...
extension=php_mysql.dll
extension=php_mysqli.dll
...

Web- Apache. php_mysql.dll php_mysqli.dll libmysql.dll , PHP. Web-


Apache
php.ini,
libmysql.dll .
, , C:\Windows\system32.
php_mysql 1.13. PHP
MySQL, MySQL-.
1.13. php_mysql
<?php
// MySQL
$dblocation = "localhost";
//
$dbname = "test";
//
$dbuser = "root";
//
$dbpasswd = "";
//
$dbcnx = mysql_connect($dblocation, $dbuser, $dbpasswd);

Web- Apache, PHP MySQL

49

if (!$dbcnx) {
exit( "<p> ,
.</p>" );
}
//
if (! mysql_select_db($dbname, $dbcnx) ) {
exit( "<p> ,
.</p>" );
}
// SQL-
$query = "SELECT VERSION()";
$res = mysql_query($query);
//
if(!$res) exit(" ".mysql_error());
//
echo mysql_result($res, 0);
?>

php_mysqli 1.14. ,
MySQL-.
1.14. php_mysqli
<?php
// MySQL
$dblocation = "localhost";
//
$dbname = "test";
//
$dbuser = "root";
//
$dbpasswd = "";
// mysqli,
//
$mysqli = new mysqli($dblocation, $dbuser, $dbpasswd, $dbname);
if (mysqli_connect_errno()) exit(" ");
//
echo $mysqli->server_info;
//
$mysqli->close();
?>

50

1.16.
mysql
MySQL , . MySQL
Web-, PHP-, ,
, .
MySQL. mysql, . 1.12 MySQL-.
MySQL.
: | | MySQL | MySQL Server 5.1 | MySQL Command Line
Client.
mysql MySQL Command Line Client - . , , MySQL (, mysqldump,
SQL-), . , : | | |
. , . 1.40.

, .
,
.

. 1.40.

bin
MySQL. :
cd C:\mysql5\bin

Web- Apache, PHP MySQL

51

:
C:\mysql5\bin>


MySQL , cd , , D:. ,
,
bin, cd.

, bin, .
, , . , dir.
bin ,
MySQL C:\Program Files.
mysql.
.
, . bin ( . 1.40 C:/mysql/bin), OK
.
C:\mysql\bin.
mysql ,
C:\mysql\bin PATH.
bin .

UNIX- /bin,
/usr/sbin, PATH . - MySQL , , PATH.

,
: ,
, . . . 1.41 %SystemRoot% , Windows.
,
. PATH, ,
.
Windows
, , : | |
| . , . 1.42.

52

. 1.41.

. 1.42.

Web- Apache, PHP MySQL

53

,
, . 1.43.
PATH
bin MySQL.
PATH ( ). PATH .

. 1.43.

1.17.
. MySQL
cp866 (DOS), .
chcp, , . ,
Windows-1251, :
chcp 1251

. Lucida
Console.

54

, , MySQL-
latin1, .
, , ,
MySQL- SQL-,
1.15.
1.15.
SET NAMES cp1251;


, , PHP-. 1.16 MySQL.
1.16. MySQL
<?php
// MySQL
$dblocation = "localhost";
//
$dbname = "test";
//
$dbuser = "root";
//
$dbpasswd = "";
//
$dbcnx = mysql_connect($dblocation, $dbuser, $dbpasswd);
if (!$dbcnx) {
exit( "<p> ,
.</p>" );
}
//
if (! mysql_select_db($dbname, $dbcnx) ) {
exit( "<p> ,
.</p>" );
}
//
@mysql_query("SET NAMES cp1251");
?>


, Web-, PHP, Web- Apache
MySQL.

2.1. PHP
2.1.1. php.ini
php.ini . , , [PHP], ,
:
directive = value

directive , value . ,
(;),
.
value. . ,
none.
php.ini [PHP], , : (
[MySQL] [PostgresSQL]) , (,
[Date] [Session], ).
PHP Web- , php.ini Web-.
PHP CGI-,
.
PHP
:

56

, PHPIniDir httpd.conf

Web- Apache ( , Apache 2.2);


, PHPRC ( PHP 5.2);
( Web-);
C:\Windows\ Windows -

.
PHP- Web-, php.ini -c, :
php.exe -c C:/PHP/php.ini D:/scripts/file.php

[PHP].

2.1.2. PHP
. 2.1 . , .
2.1.

engine

(On) (Off) PHP- Web- Apache

short_open_tag

(On) (Off)
<? <?php

asp_tags

(On) (Off) ASP- <%


%> <?php ?>. PHP 6

precision

, , ,
printf(), sprintf()

output_buffering

(On) (Off) .
, ,

engine On, Off , PHP- Web-. PHP-


HTML- ,
(. 2.1).
short_open_tag asp_tags ,
PHP-. short_open_tag,
<?, (On). , PHP- XML-, <?xml ?>.

57

. 2.1. PHP-

asp_tags, ASP <% %>, .


PHP 6, ASP-
asp_tags .
precision ,
. 2.1 , .

precision , .

2.1.
<?php
echo 10.23456;
echo "<br />";
echo 10.23456E+20;
?>

precision 4, :
10.23
1.023E+21

precision , :
10.23456
1.023456E+21

output_buffering, , . PHP-

58

, .
, , , ,
HTTP-, . output_buffering 2.2.
2.2. HTTP-
<?php
echo "hello world!";
session_start();
?>

HTTP- (, SID- cookies,


HTTP- Set-Cookie).
(. 2.2).

. 2.2. HTTP-

(output_buffering = On) php.ini,


, HTTP- ,
(. 2.3).
On output_buffering
, , . "hello world!"
12 , output_buffering 12
2.2 , 12
.

59

. 2.3. HTTP-

2.1.3.
Web- . : . Web-. PHP
, .
PHP UNIX-
. UNIX ,
, ( ). : , .
:
;
;
.
:
r ;
w / ;
x , -

( ).
: rwxr--r--. ,
, ,
. UNIX- .
4, 2, 1.
: 6 (4 + 2)
, 7 (4 + 2 + 1)
. 0755 ,
(rwx),
(r-x).

60

,
( ). safe_mode_gid
: On,
.
, file_get_contents(), put_get_contents(),
fopen(), fwrite(), fread(), include, include_once, require
require_once. ,
(
PEAR PHP-).
, safe_mode_include_dir: ,
,
.
PHP- , ,
system(), exec(), shell_exec() (. 2.4).

. 2.4.

,
, , . safe_mode_exec_
dir , .
, ( Web-)
.
Web- , (, PHP) .
GET-. GET-, Web-
QUERY_STRING GET-.
PHP
$_SERVER $_GET. -

61

, PHP-, ,
(. 2.5).

,
, .

. 2.5. PHP Apache

, , safe_mode_allowed_env_vars.
, PHP_:
safe_mode_allowed_env_vars = PHP_

safe_mode_protected_env_vars
,
safe_mode_allowed_env_vars ( ).
. 2.2 , PHP.
2.2.

safe_mode

(On) (Off) , PHP

safe_mode_gid

:
-

safe_mode_include_dir

, ,

62

2.2 ()

safe_mode_exec_dir


system(), exe() . .

safe_mode_allowed_env_vars

,
PHP- . ,

safe_mode_protected_env_vars

,
safe_mode_allowed_env_vars


. dir ( Windows) ls -l ( Linux).
shell_exec(),
( 2.3).
2.3.
<?php
$text = shell_exec("dir");
echo "<pre>";
echo htmlspecialchars(convert_cyr_string($text, 'd', 'w'));
echo "</pre>";
?>

, echo shell_exec("dir") . ,
<br /> , <pre> </pre>. , cp866 (DOS). convert_cyr_string(). dir
<DIR>, . htmlspecialchars()
, <DIR>.
. 2.6 .
php.ini safe_mode, 2.3 ,
shell_exec()
(. 2.7).

63

. 2.6. dir

. 2.7.

PHP ,
, (. 2.3).
2.3.

open_basedir

, PHP-

disable_functions

disable_classes

64

open_basedir ,
PHP-
( ). . ,
open_basedir = "D:/main/pro"

"D:/main/pro" D:/main/pro/,
D:/main/projects/ D:/main/progress/.
pro, "D:/main/pro/".

open_basedir Web-,
PHP ,
(. . 2.1.15).

disable_functions , . ,
set_time_limit() putenv():
disable_functions

= "set_time_limit,putenv"

2.1.4. PHP-
PHP , PHP- (. 2.4).
2.4. PHP-

highlight_string($code
[, $return])

PHP- $code
. $return
true,

highlight_file($filename
[, $return])

PHP- $filename, .
$return true,

test.php,
( 2.4).
2.4. test.php
<?php
if (!$flag)
{
//
echo "Hello";

65

$var = 1;
}
else echo "";
?>

2.5 highlight_file(), test.php .


2.5. highlight_file()
<?php
highlight_file("test.php");
?>

. 2.8 2.5.

. 2.8. highlight_file() PHP-

( HTML-),
true,
( 2.6).
2.6. highlight_file()
<?php
$code = highlight_file("test.php", true);
//
...
//
echo $code;
?>

66

,
: ,
, , . .
php.ini , . 2.5.

highlight.bg , PHP 6.0.

2.5. PHP-

highlight.string

, (#DD0000)

highlight.comment

, (#FF9900)

highlight.keyword

, (#007700)

highlight.bg

, (#FFFFFF)

highlight.default

PHP-,
(#0000BB)

highlight.html

HTML-, (#000000)

HTML-, . . span
<span style="color: #0000BB">$var = 1;</span>

#RRBBGG,
(R), (B) (G) ( 0 255).
, HTML: red, blue . .

2.1.5.
. ,
. 2.6,
.

clearstatcache() .

2.6.

realpath_cache_size

, 16

realpath_cache_ttl

, 120

67

2.1.6.

(. 2.7).
2.7.

ignore_user_abort

(On),

expose_php

(On) (Off) ,
PHP HTTP-

2.1.7.
, .
, .

. 2.8 . ,
.

2.8.

max_execution_time

( ), . 0, . 30

max_input_time

( ), GET-, POST- . 1, 60

memory_limit

30
, max_execution_time. , , (. 2.9).
, memory_limit. , .


GDLib.

68

. 2.9.

. 2.10.

. 2.10 ,
.

2.1.8.

PHP. . 2.9 .
2.9.

error_reporting

display_errors

(On) (Off)

display_startup_errors

(On) (Off) .

log_errors

(On) (Off) , error_log

log_errors_max_len

,
. 0

69
2.9 ()

ignore_repeated_errors

(On) (Off) ( ,
)

track_errors

(On), $php_errormsg

error_log

. .
syslog,
syslog UNIX Windows


, . ,
.
, php.ini 2.7.
2.7.
;
error_reporting = E_ALL & ~E_NOTICE
;
display_errors = On
;
log_errors = On
; 1
log_errors_max_len = 1024
;
error_log = "D:/php.log"

, , ,
php.log; error_log syslog,
( 2.8).
2.8.
;
error_reporting = E_ALL & ~E_NOTICE
;
display_errors = On
;
log_errors = On
; 1
log_errors_max_len = 1024
;
error_log = syslog

70

: | | | | . PHP (. 2.11).
(. 2.12).

. 2.11.

. 2.12.

71

error_reporting.
, PHP .
. . -
, , =, (Notice). 2.9
$user, .
2.9. $user
<?php
echo $user;
?>

$user
"Notice: Undefined variable: user" (": ") (. 2.13).

. 2.13. ,

, PHP. PHP
error_reporting php.ini.
PHP : ,
, , . . . 2.10 ,
PHP , php.ini, .

72

2.10.

E_ERROR

, .

E_WARNING

E_PARSE

E_NOTICE

.
, ,

E_CORE_ERROR

16

,
PHP

E_CORE_WARNING

32

(),
PHP

E_COMPILE_ERROR

64

, PHP

E_COMPILE_WARNING

128

(), PHP

E_USER_ERROR

256

,
trigger_error()

E_USER_WARNING

512

()
, trigger_error()

E_USER_NOTICE

1024

,
trigger_error()

E_STRICT

2048

,
PHP-

E_RECOVERABLE_ERROR

4096

,
, set_error_handler(). ,
E_ERROR

E_ALL

8191

2.10 php.ini,
PHP (E_ALL), (E_NOTICE).

. 2.10 ,
, . . .

2.10. php.ini
<?php
...
error_reporting
...
?>

E_ALL & ~E_NOTICE

73


|, ~, !,
^ &.

error_reporting PHP .
Web-
, :
error_reporting([$level])

$level, PHP. ( ).
2.11 error_reporting()
PHP.
2.11. error_reporting()
<?php
error_reporting (E_ALL & ~E_NOTICE)
?>

php.ini , , , , ( 2.12).
2.12. ,
<?php
//
error1();
?>

E_ERROR,
, . 2.14.

. 2.14.

74

2.1.9.
,
, , , . . 2.11 .

PHP 6 , register_globals, register_
long_arrays magic_quotes_gpc.

2.11.

arg_separator.output

URL, PHP.
HTML &, XHTML
&amp;

arg_separator.input

, URL.
-, &, . .
PHP GET- POST-
$_GET $_POST

register_globals

(On) (Off) ,
GET- POST-, cookies

variables_order

register_globals.
EGPCS: , GET-, POST-, cookies Web-
( $_SERVER)

request_order

$_REQUEST
.
, $_REQUEST
. , GP: GET-,
POST-

register_long_arrays

(On) (Off) ,

register_argc_argv

(On) (Off) $argv $argc, .


PHP , .
Web-

auto_globals_jit

(On), $_SERVER .
(Off) $_SERVER
, , .
auto_globals_jit ,
register_globals, register_long_arrays
register_argc_argv

75
2.11 ()

post_max_size

POST-,
PHP-

magic_quotes_gpc

(On) (Off) " "


magic_quotes_runtime

(On) (Off) " "


, (, , system())

magic_quotes_sybase

(On) (Off) " " Sybase: '


'', \'

auto_prepend_file

, PHP-. , include

auto_append_file

,
PHP-. ,
include. exit(),

default_mimetype

MIME- HTTP- Content-Type. "text/html"

default_charset

HTTP- Content-Type.
HTTP-,

register_globals GET/POST-, cookies .


GET- id : index.php?id=17.
, 2.13.
2.13. GET-
<?php
echo $_GET['id'];
?>

register_globals On, GET $id ( 2.14).


2.14. GET- id register_globals
<?php
echo $id;
?>

76

, PHP- - . 2.15 ,
$access 1, , 0, .
2.15.
<?php
if ($_POST['name'] == "name" && $_POST['pass'] == "pass")
{
$access = 1;
}
if ($access)
{
//
}
?>

2.15 GET- POST- access , , , , . ,


,
$access , , , . ,
PHP 6, register_globals php.ini.
magic_quotes_gpc,
" ". , , SQL SQL- ,
. - : ( Sysbase) '
\', ''.
. PHP-
, "
" . get_magic_
quotes_gpc(), TRUE, , FALSE . 2.16 .

mysql_escape_string() mysql .

77

2.16.
magic_quotes_gpc
<?php
...
if (!get_magic_quotes_gpc())
{
// " "
$_POST['name'] = mysql_escape_string($_POST['name']);
$_POST['pass'] = mysql_escape_string($_POST['pass']);
}
...
?>

2.16, " " , if


, . PHP 5.3,
magic_quotes_gpc php.ini, get_magic_quotes_gpc()
FALSE.
auto_prepend_file auto_append_
file, PHP-
PHP-.
PHP-: php_start.php ( 2.17) php_end.php ( 2.18), "Start PHP" "End PHP".

, auto_prepend_file auto_append_file, , , , . .

2.17. php_start.php
<?php
echo "Start PHP<br />";
?>
2.18. php_end.php
<?php
echo "End PHP<br />";
?>

auto_prepend_file php_start.php, auto_append_file php_end.php:


auto_prepend_file = D:/php_start.php
auto_append_file = D:/php_end.php

78


, include-
( 2.19).
2.19. index.php
<?php
echo "Contents<br />";
?>

2.19 . 2.15.

. 2.15. 2.19

php_end.php , PHP
. , ,
exit(), php_end.php .

2.1.10.
, , file Web- (. 2.12).
2.12.

file_uploads

(On) (Off) HTTP


( file)

upload_tmp_dir

upload_max_filesize

79

2.1.11.
, ,
(. 2.13).
2.13.

allow_url_fopen

(On) (Off)
( http://)

allow_url_include

(On) (Off)
include require ( http://)

from

FTP-. e-mail

user_agent

USER_AGENT, PHP
URL ,

default_socket_timeout

2.1.12.
PHP . , . . 2.14 .
2.14.

extension_dir

extension

, extension

, PHP 5, . , MySQL
(GDLib),
php.ini.
extension. ( #) .
MySQL :
extension=php_mysql.dll

80


(php_mcrypt.dll) , C:\Windows\system32. C:\php, .

, :
extension_dir = "C:\Program Files\PHP\ext"

2.1.13.
[Session] php.ini ,
. . 2.15
.
2.15.

session.save_handler

,
files (
).
( )

session.save_path

session.use_cookies

(On) (Off) cookies


SID. , SID GET-

session.cookie_secure

(On), cookies SID


(https://, HTTP
SSL-)

session.use_only_cookies

(On), PHP cookies


SID, GET-

session.name

,
session_name()

session.auto_start

(On) (Off)
PHP-.
session_start()

session.cookie_lifetime

cookies SID. 0, cookies,


session.cookie_path

ookie SID , /, , ookie


session.cookie_domain

cookies

session.serialize_handler

. php, , serialize()

81
2.15 ()

session.gc_probability

" " . session.gc_probability/session.gc_divisor.


1

session.gc_divisor

" " . session.gc_probability/session.gc_divisor.


100

session.gc_maxlifetime

, "
". 1440

2.1.14.
[Date]
(. 2.16).

. 2.16 date_sunrise(), date_sunset()
date_sun_info().

2.16.

date.timezone

date.default_latitude

date.default_longitude

date.sunrise_zenith

(90 )
date_sunrise()

date.sunset_zenith

(90 )
date_sunset()

2.1.15. php.ini Apache


php.ini. , php.ini ,
,
. php.ini httpd.conf
.htaccess.

82

php.ini httpd.conf .htaccess, , AllowOverride


<Directory /> Options All ( 2.20).
2.20. AllowOverride httpd.conf
<Directory />
Options All
AllowOverride All
Order deny,allow
</Directory>

http.conf Web Apache, .htaccess ( ).


PHP httpd.conf .htaccess :
php_admin_value php.ini;
php_admin_flag php.ini (. . ,

On Off);
php_value php.ini;
php_flag php.ini (. . , -

On Off);
php_admin_value php_admin_flag php_value php_flag httpd.conf. , , .htaccess. php_value
php_flag , .
2.21 open_basedir
"/www". , PHP /www,
, , .
2.21. PHP /www
<Directory /www>
php_admin_value open_basedir /www
</Directory>

, open_basedir , ,
, PHP,
( 2.22).

83

2.22.
#
<VirtualHost 127.0.0.1:80>
ServerAdmin suport@domain1.ru
DocumentRoot "/www/domain1/"
ServerName domain1.ru
php_admin_value open_basedir "/www/domain1/"
ErrorLog "/www/domain1/logs/domain1-error.log"
CustomLog "/www/domain1/logs/domain1-access.log" common
</VirtualHost>
#
<VirtualHost 127.0.0.1:80>
ServerAdmin suport@domain2.ru
DocumentRoot "/www/domain2/"
ServerName domain2.ru
php_admin_value open_basedir "/www/domain2/"
ErrorLog "/www/domain1/logs/domain2-error.log"
CustomLog "/www/domain1/logs/domain2-access.log" common
</VirtualHost>

.htaccess php_value
php_flag. .htaccess , httpd.conf,
. .htaccess,
, , FTP- .
2.23 register_long_arrays,
,
auto_prepend_file, PHP- include.utils.php.

auto_prepend_file
.

2.23. .htaccess
php_flag register_long_arrays on
php_value auto_prepend_file /www/domain/include/include.utils.php

2.1.16. PHP
, Apache
php.ini, PHP- . PHP -

84

, PHP
(. 2.17).
2.17. PHP

ini_set($varname, $newvalue)

$varname $newvalue.
.
, FALSE

ini_get($varname)

$varname

ini_get_all($extension)


$extension

ini_restore($varname)

$varname,
, php.ini

2.24
PHP.
2.24. PHP
<?php
// post_max_size
echo ini_get("post_max_size");
// post_max_size
ini_set("post_max_size", "32M");
//
ini_restore("post_max_size");
?>

, (. . 2.1.3),
php_admin_value httpd.conf (. . 2.1.15).
, , PHP
(. 2.18).
2.18.

memory_get_usage()

php_sapi_name()

PHP Web-. PHP CGI-, "cgi",


"apache"

85
2.18 ()

php_uname([$mode])

, PHP. $mode , uname

phpinfo()

PHP, ,
PHP-

phpversion([$extension])

PHP. , $extension

memory_get_usage(),
, ,
memory_limit, .

. 2.16. phpinfo()

86

php_uname() ,
PHP-.
:
's' ;
'n' ;
'r' PHP;
'v' ;
'm' , , i386;
'a' .

2.25 phpinfo(), PHP


.
2.25. phpinfo()
<?php
phpinfo();
?>

phpinfo() . 2.16.

2.1.17. PHP
PHP Web-,
, , ,
. .
UNIX-
, , PHP- #! ( 2.26).

# PHP ( shell-) , #! ( bang line, hash-bang shebang) .
, UNIX- : Perl, , PHP Python.
Web-, . UNIX-
, ,
. .
#!/usr/bin/php #!/usr/bin/sh #!/usr/bin/perl. , /usr/bin bang line
.

87

2.26. PHP-
#!/usr/bin/php
<?php
// PHP-
?>

Windows #! ,
.
.
, php PHP. PHP- . (. 2.17).

. 2.17.

. .
C:\PHP\php.exe (. 2.18).

PHP : php.exe, php-cgi.exe phpwin.exe. php-cgi.exe Web-, -

88

PHP-, PHP . php.exe , , . php-win.exe


PHP- .
, PHP- ,
.

. 2.18.

PHP-
CLI, . 2.19. PHP-
<Enter> .
,
index.php, C:\
hello, "Hello world!" ( 2.27).
2.27. index.php
<?php
//
$fd = fopen("C:/hello","w");
//
fwrite($fd, "Hello world!");
//
fclose($fd);
?>

89

. 2.19. PHP- PHP

,
<Enter> index.php
C:\ hello.

2.1.18.
UNIX cron,
. PHP-.
Windows XP , UNIX- .
Web-
Windows, UNIX
cron.
cron Windows http://
www.nncron.ru/download.shtml. cron
nnCron, Windows-, nnCron LITE
,
crontab. nnCron LITE, . . cron.tab UNIX-

90

cron -. http://www.nncron.ru/
download.shtml
cron.tab nnCron.
cron, . UNIX
chmod.
UNIX :
;
;
.
:
r ;
w / ;
x , -

( ).
, : rwxr--r--. UNIX-
. 4, 2, 1. , 6 (4 + 2) , 7
(4 + 2 + 1) . 0755 , (rwx), (r-x). index.php rwxr-xr-x (0755), :
chmod 755 index.php

PHP, , ,
, 2.28.
2.28.
<?php
chmod("index.php", 0755);
?>

PHP- Windows, php PHP-, . . . 2.1.17.


cron.tab.

nnCron Windows, cron.tab
C:\Program Files\cron.tab, UNIX cron.tab , , \etc. (

91

cron.tab UNIX .)

cron.tab .
cron.tab- , #. :
_ _


059;
023;
_ 131;
112;
_ 07 (0 7 );
, , , d:/mail/
reserve.php.

* , ,
0 23 * * * d:/main/reserve.php

d:/main/reserve.php 23:00. .
0 0,8,16 * * * d:/main/cleanup.php

d:/main/cleanup.php 0:00, 8:00 16:00.



,
, . . 0 0, 8, 16 * * * d:/main/cleanup.php .

0,30 18-23 * * * /home/root/check.php

/home/root/check.php 18:00 23:00.

0/10 * * * * /home/root/log.php

/home/root/log.php 10 .
.

- . , ,
- .

92

2.2. Apache
2.2.1. .htaccess
Apache .htaccess Web-
.
, httpd.conf,
.htaccess. , , AccessFileName,
.htaccess ( 2.29).
2.29. AccessFileName httpd.conf
AccessFileName .htaccess

.htaccess ,
, Files, , .ht ( 2.30), .
2.30. , .ht
<Files ~ "^\.ht">
Order allow,deny
Deny from all
Satisfy All
</Files>

.htaccess.
AllowOverride, ,
.htaccess. , <Directory /> .
AllowOverride
: All, None, AuthConfig, FileInfo, Indexes, Limit, Options. , ( 2.31).
2.31.
<Directory />
Options FollowSymLinks Indexes MultiViews
AllowOverride AuthConfig FileInfo Indexes Limit Options
</Directory>

93

All , .htaccess, None, , .


AllowOverride .htaccess ,
. 2.19.
2.19. AllowOverride

AuthConfig

.htaccess ( AuthDBMGroupFile,
AuthDBMUserFile, AuthGroupFile, AuthName, AuthType, AuthUserFile Require)

FileInfo

.htaccess , (AddEncoding, AddLanguage, AddType,


DefaultType, ErrorDocument LanguagePriority)

Indexes

.htaccess , (AddDescription, AddIcon,


AddiconByEncoding, AddIconByType, DefaultIcon, DirectoryIndex,
FancyIndexing, HeaderName, IndexIgnore, IndexOptions RenameName)

Limit

.htaccess , (Allow, Deny Order)

Options

.htaccess , (Option XBitHack)

2.2.2.
, META- , Apache , ISO-8859-1.
HTTP-:
Content-Type: text/html; charset=ISO-8859-1

, , , cp1251 (. 2.20).

. 2.20.

94

, . 2.20, .htaccess
AddDefaultCharset, ( 2.32).
2.32.
AddDefaultCharset Windows-1251

cp1251
(Windows-1251),
META- (. 2.21).

. 2.21.

AddDefaultCharset . 2.20.
2.20. , AddDefaultCharset

ISO-8859-1

ISO-8859-15

Windows-1252

CP850

CP866

(DOS)

Windows-1251

(Windows)

KOI8-R

(UNIX)

UTF-8

8- Unicode

UTF-7

7- Unicode

UCS-2

16- Unicode

95

2.2.3.
, , http://localhost/,
http://localhost/index.php, Web- Apache DirectoryIndex ( 2.33).
2.33. DirectoryIndex
DirectoryIndex index.html index.php

Web- Apache , DirectoryIndex, . , ? 403 (. 2.22).

. 2.22. ,

Web- Apache,
Options Indexes MultiViews
, ,
(. 2.23).
, , .htaccess.

,
AllowOverride httpd.conf Indexes.

HeaderName ReadmeName ,
HTML- . , up.html down.html,
2.34 2.35.

96

. 2.23.

2.34. up.html
<h3 style="color: red"> </h3>

2.35. down.html
<h3 style="color: red"> </h3>

,
. 2.24.
, .htaccess index , 2.36.
2.36.
AddDefaultCharset Windows-1251
HeaderName up.html
ReadmeName down.html

, . 2.24, down.html up.html, , .


.
IndexIgnore.
.htaccess , 2.37,
down.html up.html.

. 2.24.

. 2.25.
.htaccess

97

98

2.37.
AddDefaultCharset Windows-1251
HeaderName up.html
ReadmeName down.html
IndexIgnore up.html down.html

.htaccess 2.37
. 2.25.

2.2.4. PHP- HTML-


PHP- HTML- , , HTML-,
PHP. , . .
, HTML-
. HTML- PHP.
HTML- .htaccess ,
2.38, HTML- PHP- ,
php.
2.38. PHP- HTML-
RemoveHandler .html .htm
AddType application/x-httpd-php .php .htm .html .phtml

2.2.5. Web- Apache


Web- HTTP HTTP/1.1. ,
:
100199 .
, .
;
200299 .
, , , , ;
300399 . ,
, ( , );
400499 . ,
;

99

500599 . ,

( , -
.htaccess).
HTTP- 4xx 5xx,
. . 2.26
Internet Explorer 404 .

. 2.26. HTTP- 404

, ,
, .
,
, . ErrorDocument, HTTP-, , .
,
( 2.39).

ErrorDocument .htaccess AllowOverride FileInfo.

2.39. ErrorDocument
ErrorDocument 404 " , , %s"
ErrorDocument 403 /errors/403.html
ErrorDocument 401 http://www.mysite.ru/index.php

,
( HTTP- 401).

100

2.2.6.
Redirect,
, ,
, . .htaccess 2.40 http://localhost/index.php
http://www.softtime.ru/index.php.

, , ,
HTTP- 3xx.

2.40. Redirect
Redirect / http://www.softtime.ru/

Redirect HTTP- 302: . HTTP- . 2.21, Redirect.


2.21. Redirect

HTTP-

Permanent

301

HTTP- ,

Temp

302

HTTP- ,
( )

See other

303

HTTP- ,

Gone

410

HTTP- ,

, ,
, Permanent ( 2.41).
2.41. Permanent
Redirect Permanent / http://www.softtime.org/

HTTP ( 2.42).
2.42. HTTP- (3xx)
Redirect 301 / http://www.softtime.org/

2.41 2.42 . HTTP-


301 302 ,

101

.htaccess RedirectTemp RedirectPermanent,


Redirect Temp Permanent.

2.2.7.
, ,
, , .

allow deny . .htaccess
httpd.conf deny allow, order:
order deny,allow

(deny) ,
(allow).
:
order allow,deny

2.43 .htaccess,
IP- 127.0.0.1.
2.43. IP- 127.0.0.1
order deny,allow
deny from all
allow from 127.0.0.1

order deny
allow. deny from all
IP-. IP- 127.0.0.1 allow from 127.0.0.1.
,
: IP- .htaccess
127.0.0.1 127.0.0.2. HTTP- 403 (. 2.27).
, , IP-, , 2.44.
2.44. IP- 127.0.0.1
deny from 127.0.0.1

IP- IP-,
IP- ( 2.45).

102

. 2.27.

2.45. 127.0.0.1127.0.0.255
deny from 127.0.0

, .
2.45 2.46 .
2.46.
deny from 127.0.0.1/255.255.255.0

, CIDR- ( 2.47).
2.47. CIDR-
deny from 127.0.0.1/24

, , , 2.48.
2.48.
deny from all

, , , PHP, - , . . .htaccess
.

103

2.2.8.
.
,
, txt. <Files> ( 2.49).
2.49. <Files>
<Files "*.txt">
deny from all
</Files>

<Files> . ,
config.php .htaccess, 2.50.
2.50. config.php
<Files "config.php">
deny from all
</Files>

. 2.51 2.50.
2.51.
<Files ~"*.php$">
deny from all
</Files>

2.2.9.
.
, .htaccess, .htpasswd
. .htpasswd htpasswd, bin Web- pache.

.htpasswd .
, , , .ht, , .

104

-c, MD5 -m. , . . -cm ( 2.52).


2.52. .htpasswd
htpasswd -cm .htpasswd user

user
.htpasswd. password
, -b ( 2.53).
2.53. .htpasswd
htpasswd -cmb .htpasswd user password

2.53 :
user:$apr1$8U2.....$Jehmbz8MGSSzxKQZxHUEs/

.
.htpasswd ,
-c , . . .
, ,
.htaccess , 2.54.

.htpasswd .htaccess .
. , .

2.54. .htaccess
AuthType Basic
AuthName "Password Access"
AuthUserFile ////.htpasswd
require valid-user

, .htaccess .htpasswd, (. 2.28).


,
, . <Files> ( 2.55).

105

. 2.28.

2.55.
<Files "*.zip">
AuthType Basic
AuthName "Password Access"
AuthUserFile ////.htpasswd
require valid-user
</Files>

2.2.10. URL-
Web- Apache
. : , . CGI (http://site.dev?category=news&year=2011&month=12&day=27&page=1)
,
, ,
(http://site.dev/news/2011/12/27/).
, GET-
mod_rewrite.

2.2.10.1. mod_rewrite
Apache . ,
, .
mod_rewrite, URL-.
httpd.conf (#) :
LoadModule rewrite_module modules/mod_rewrite.so

106

Options <Directory /> :


Options Indexes FollowSymLinks MultiViews

.htaccess
URL.

2.2.10.2. GET-
, URL http://localhost/
index.php?id=1, http://localhost/1/. .htaccess
, 2.56.

, http://localhost/index.php?id=1,
http://localhost/index.php, : http://localhost/1/. . ,
mod_rewrite "" .

2.56.
RewriteEngine On
RewriteBase /
RewriteRule ^([0-9]+) /index.php?id=$1

http://localhost/1/ http://localhost/54/
http://localhost/index.php?id=1
http://localhost/index.php?id=54 . . ,
index.php ( 2.57).
2.57. index.php
<?php
echo $_GET['id'];
?>

, 2.57. RewriteEngine (On) , . . ( , mod_rewrite Web-). mod_rewrite, .


, RewriteEngine On , mod_rewrite,

107

(
5xx ).
RewriteBase ,
. 2.57
URL .
RewriteRule .
,
, Web- .
, .
$1
. , http://localhost/nnn/, id:
http://localhost/index.php?id=nnn. $2 ,
$3 . .
, ,
(. 2.22).

-, .
,
. . " ". ,

http://www.softtime.ru/forum/index.php?id_forum=6.

2.22.

[0-9]

0 9

[A-Z]

[0-9A-Z]

, ,

\b

\w

\s

(, ,
. .)

\t

108

2.22 ()

\n

\r

\077

\x9f

1 0

{n}

{n,}

{n,m}

n m

^ , . ,
2.56 http://localhost/abc/14/,
^ ( 2.58),
id
14.
2.58.
RewriteEngine On
RewriteBase /
RewriteRule ([0-9]+) /index.php?id=$1

, 2.59
, , , http://localhost/
abc/256/14/ http://localhost/index.php?id=256.
id .
$, , . ,
http://localhost/abc/256/14 2.59 http://localhost/index.php?id=14.
id .
2.59.
RewriteEngine On
RewriteBase /
RewriteRule ([0-9]+)/$ /index.php?id=$1

109

.
, :
[abc]

, : a, b, c.
, , , , .
, . :
[a-z]

, , , ,
.
, :
[0-9]

[0123456789]

.
, .
, ?, + *,
:
? , ;
* , 0;
+ .

. :
xy{2} , x yy;
xy{2,} , x y (

);
xy{2,6} , x y.

, ,
:
x(yz){2,6} , x -

yz;

110

x(yz)* , x -

yz.
|
.
abc|

, abc .
, . . , , "ru", "com" "net":
ru|com|net

.htaccess RewriteRule,
.

2.2.10.3. 2006/07/20
http://localhost/2006/
07/20/ http://localhost/index.php?year=2006&month=07&day=20. , ,
. .htaccess ( 2.60).

, 2.60 RewriteRule , .htaccess .
.

2.60. YYYY/MM/DD GET-


RewriteEngine On
RewriteBase /
RewriteRule ^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/$
/index.php?year=$1&month=$2&day=$3

2.60
index.php ( 2.61).
2.61. index.php
<?php
echo " ".$_GET['year']."<br>";
echo " ".$_GET['month']."<br>";
echo " ".$_GET['day']."<br>";
?>

111

2.61, ,
RewriteRule, ,
$1, $2 $3. , ,
[0-9]{4} , . . , http://localhost/2006/07/20/ http://
localhost/06/07/20/. [0-9]{1,2} , . . http://localhost/2006/07/20/ http://localhost/2006/7/20/
.

2.2.10.4. -
. 2.22 , .
,
? .
http://localhost/index.html/,
http://localhost/index.php.
, 2.62.
2.62.
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html /index.php

2.2.10.5. RewriteRule
RewriteRule , .
, , [R]. ,
, , [L,R]. ,
.htaccess 2.62 2.63,
index.php index.html
index.php.
2.63. [R]
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html /index.php [R]

RewriteRule . 2.23.
: , , [R], , , [redirect].

112

2.23. RewriteRule

C | chain

, .
,
, ,
, C,

E=var:value | env=var:value


GET- var value

F | forbidden

,
403 (HTTP Forbidden)

G | gone

,
410 (HTTP Gone)

L | last

, ,
RewriteRule,

N | next


RewriteRule.
, .
,

NC | nocase

NS | nosubreq

P | proxy

QSA | qsappend

(,
=)

R [=HTTP-] | redirect

, , . HTTP , 302 (Move Temporarily)

S=n | skip=n

, n

T=MIME-type |

MIME-

2.2.10.6.
GET-
.
http://site.dev/catalog.php
http://site.dev/catalog.php?id_catalog=12
http://site.dev/catalog.php?id_catalog=12&id_position=366

113

.
12.
366 12. :
http://site.dev/catalog/
http://site.dev/catalog/12/
http://site.dev/catalog/12/366/

,
[L],
.
, . . mod_rewrite . 2.64
.
2.64. RewriteRule
RewriteEngine On
RewriteBase /
RewriteRule ^catalog/([0-9]+)/([0-9]+)/
/catalog.php?id_catalog=$1&id_position=$2 [L]
RewriteRule ^catalog/([0-9]+)/ /catalog.php?id_catalog=$1 [L]
RewriteRule ^catalog/ /catalog.php?id_catalog=$1 [L]

2.2.10.7. mod_rewrite
mod_rewrite . ,
. <VirtualHost> ( 2.65),
( 1 9, 9
).
2.65. mod_rewrite
<VirtualHost 127.0.0.1:80>
...
RewriteLog logs/rewrite.log
RewriteLogLevel 9
...
</VirtualHost>

2.2.10.8. . RewriteCond
RewriteRule ,

114

RewriteCond. , http://site.dev/news/54/ http://site.dev/news.php?id=54 ( 2.66).


2.66.
RewriteEngine On
RewriteBase /
RewriteRule ^news/([0-9]+)/$ news.php?id=$1 [L]


GET-.
, , . GET- page, http://site.dev/news/54/?page=2.
GET- ,
. , , . 2.2.10.6,
, CGI- ?page=2.
RewriteRule
, . . GET-
. RewriteCond ,
%{_} ( 2.67).
2.67. GET-
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} page=([0-9]*)
RewriteRule ^news/([0-9]+)/ /news.php?id=$1&page=%1 [L]
RewriteRule ^news/([0-9]+)/$ news.php?id=$1 [L]

RewriteRule, RewriteCond,
, RewriteCond.
RewriteRule RewriteCond,
.
2.67 RewriteCond
QUERY_STRING, Web- Apache
. GET- page, ,
RewriteRule. RewriteRule RewriteCond, %1, %2,
, . .

115

. 2.24 . PHP- $_SERVER.


2.24.
Web- Apache

HTTP_USER_AGENT

(, ) ,

HTTP_REFERER

HTTP_COOKIE

Cookie-, ,
HTTP- Set-Cookie

HTTP_HOST

, .
, HTTP Host , ,

HTTP_ACCEPT

DOCUMENT_ROOT

, ,

SERVER_NAME

, , HTTP_HOST

SERVER_ADDR

IP-

REMOTE_ADDR

IP-

REQUEST_METHOD

HTTP-, (
, GET, POST HEAD)

REQUEST_FILENAME

QUERY_STRING

,
GET-

2.2.10.9.
,
.
. RewriteCond ,
, RewriteRule
.
2.68 RewriteCond (!-f) (!-d), ,
RewriteRule.

116
2.68.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule new/(.*) new/index.php?run=$1 [L]

2.68,
RewriteCond -f ( ) -d ( ),
!.

2.2.10.10.
, , , .
, .
.

, , , .ru,
, , softtime.ru.

, site.dev/news news.site.dev,
site.dev/company company.site.dev. RewriteRule
RewriteCond. 2.69 news.test.dev test.dev/news/.

, DNS. SERVER_NAME ,
.

2.69.
RewriteEngine on
RewriteBase /
RewriteCond %{SERVER_NAME} ^news.test.dev$
RewriteRule index.php news/index.php [L]

2.3. MySQL
2.3.1. mysql
. 1.16 MySQL-
mysql.

117

mysql
.
root, ,
.
:
mysql u root

. 2.29. mysql>, .

. 2.29. mysql> mysql

user
hello CREATE USER, 2.70. mysql>,
. 2.30.
2.70. user
CREATE USER user IDENTIFIED BY 'hello';

mysql . mysql exit quit


(. 2.30).
mysql u user
(. 2.31). user, .
-p, .
.

118

. 2.30. user hello

. 2.31.

, :
mysql uuser phello
mysql u user phello

p , . . .
, p . mysql
Enter password:, (. 2.32).
SQL- (exit, quit, use) . , . 2.33 SQL-,
MySQL .

119

. 2.32.


MySQL 5.0,
, //, DELIMITER //, --delimiter=name.

. 2.33.

,
, , , mysql>,
.
, . , . ,
( ), mysql
. (1 row in set )
.
. 2.71 .

120
2.71.

SELECT VERSION(), CURRENT_DATE;
select version(), current_date;
SeLeCt vErSiOn(), current_DATE;

,
<Enter> ,
mysql . mysql> ->
(. 2.33). , mysql , , . mysql , , (")
(') (. 2.34).

. 2.34. ,

. 2.34, mysql> ">. ,


'>. , \c.
,
< > < > ( );
<Esc>.

2.3.2.
,
root, ,
2.72.

121

2.72.
SET PASSWORD FOR user = PASSWORD('password')

root, --skip-granttables ( my.ini skip-granttables [mysqld]),


( mysql) . SET PASSWORD - , root.
MySQL
--skip-grant-tables.

mysqladmin, mysqladmin -u root password "password".

2.3.3. MySQL
,
'username'@'host', username , host ,
username MySQL. ,
'root'@'127.0.0.1' 'wet'@'62.78.56.34' ,
root , , wet
IP- 62.78.56.34.
MySQL , , .

%, root@127.0.0.1.


IP- 127.0.0.1 ,
, SQL-.
IP- 127.0.0.1 localhost, IP- , 'root'@'127.0.0.1' :
'root'@'localhost'.

IP- - , 'softtime.ru',
'root'@'softtime.ru'
, , root, , softtime.ru.
127.0.0.1 62.78.56.34
'wet' MySQL 158.0.55.62,
: 'wet'@'127.0.0.1', 'wet'@'62.78.56.34'

122
'wet'@'158.0.55.62'.

,
, . %. , 'wet'@'%' 'wet' MySQL . % ,
'wet'@'%.softtime.ru' MySQL
softtime.ru. 'wet'@'62.78.56.%'
'wet' , IP-
62.78.56.0 62.78.56.255.
host %, , 'wet'@'%' 'wet' .

2.3.4.
CREATE USER , , . . MySQL, , ,
.
GRANT REVOKE: GRANT
, REVOKE . , GRANT, , .
REVOKE DROP USER.
GRANT , 2.73.
2.73. GRANT
GRANT ALL ON *.* TO 'wet'@'localhost' IDENTIFIED BY 'pass';

2.73 wet pass.


MySQL (localhost)
(ALL) (*.*). , ALL.

GRANT , ,
60 .
16 .

'wet'@'localhost'
REVOKE, 2.74.

123

2.74. REVOKE
REVOKE ALL ON *.* FROM 'wet'@'localhost';

ALL, (
GRANT OPTION ),
, . 2.25.
2.25. ,
GRANT REVOKE

ALL [PRIVILEGES]


GRANT OPTION, WITH GRANT OPTION

ALTER


ALTER TABLE

ALTER ROUTINE

CREATE

CREATE TABLE

CREATE ROUTINE

CREATE TEMPORARY TABLES

CREATE USER


CREATE USER, DROP USER, RENAME USER REVOKE ALL PRIVILEGES

CREATE VIEW


CREATE VIEW

DELETE

DELETE

DROP

DROP TABLE

EVENT

EXECUTE

FILE


SELECT...INTO OUTFILE LOAD DATA INFILE

INDEX

, , CREATE INDEX DROP INDEX

INSERT


INSERT

LOCK TABLES


LOCK TABLES UNLOCK TABLES.
SELECT

PROCESS

SHOW FULL PROCESSLIST

REFERENCES

RELOAD

FLUSH
,

REPLICATION CLIENT

124

2.25 ()

REPLICATION SLAVE

SELECT


SELECT

SHOW DATABASES

MySQL
SHOW DATABASES

SHOW VIEW

SHOW CREATE VIEW

SHUTDOWN

mysqladmin
shutdown

SUPER

CHANGE MASTER, KILL, PURGE MASTER LOGS SET GLOBAL

TRIGGER

UPDATE


UPDATE

USAGE

" "

GRANT OPTION

, GRANT REVOKE

. editor
, , , , 2.75.
2.75. editor
GRANT SELECT, INSERT, DELETE, UPDATE ON *.* TO editor;

,
,
INSERT UPDATE ( 2.76). DELETE
SELECT, .
2.76. INSERT UPDATE
GRANT INSERT, UPDATE ON *.* TO program;

, , 2.77.
2.77.
GRANT ALL ON *.* TO superuser;
GRANT GRANT OPTION ON *.* TO superuser;

125


, . . ALL
. 2.25
( 2.78).
2.78. ALL GRANT OPTION
GRANT ALL, GRANT OPTION ON *.* TO superuser;
ERROR 1064: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '
GRANT OPTION ON *.* TO superuser' at line 1

ON GRANT ,
, . 2.26.
2.26.
ON

ON *.*

ON *

USE,
ON *.*,
, GRANT

ON db.*


db

ON db.tbl

tbl db

ON db.tbl

tbl db.
SELECT, INSERT, UPDATE

EXECUTION, FILE, PROCESS, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE,


SHOW DATABASES, SHUTDOWN SUPER
. : SELECT,
INSERT, UPDATE, DELETE, CREATE, DROP, GRANT OPTION, INDEX ALTER. GRANT ALL,
. GRANT ALL ON db.* , FILE RELOAD.
2.79 editor (test).
2.79.
GRANT ALL ON test.* TO editor;

126


, IDENTIFIED BY , .

,
SHOW DATABASES, SHOW DATABASES.
. 2.80 , manager
user test.
2.80.
GRANT ALL ON test.user TO manager;

, SHOW TABLES.
% _,
, LIKE, . .
. , _ , , , . , list_user GRANT
, 2.81.
2.81. _
GRANT ALL ON 'list\_user'.* TO 'wet'@'localhost';

GRANT OPTION
.
, SQL
WITH GRANT OPTION, . WITH GRANT OPTION ( 2.82).
2.82. WITH GRANT OPTION
GRANT ALL ON test.* TO 'wet'@'localhost' WITH GRANT OPTION;

2.82 wet
GRANT ALL test . wet . , ,

127

GRANT OPTION, , .
GRANT OPTION, . . , , , .
REVOKE ( 2.83). GRANT ,
TO FROM, IDENTIFIED BY, REQUIRE
WITH GRANT OPTION .
2.83. REVOKE
REVOKE DELETE, UPDATE ON shop.* FROM 'wet'@'localhost';

, REVOKE ,
, DROP USER.

SHOW GRANTS ( 2.84). ,
, .
2.84. SHOW GRANTS
SHOW GRANTS;
+---------------------------------------------------------------------+
| Grants for root@localhost
|
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |

2.84, 'root'@'localhost' ,
DROP USER.

2.3.5.

WITH GRANT GRANT OPTION
, , . MAX_CONNECTIONS_
PER_HOUR, MAX_QUERIES_PER_HOUR, MAX_UPDATES_PER_HOUR MAX_USER_CONNECTIONS . 2.85 wet
shop, 10 MySQL 1000 , 200
UPDATE, 3 .

128

2.85.
GRANT ALL ON shop.* TO 'wet'@'localhost' IDENTIFIED BY 'pass'
WITH MAX_CONNECTIONS_PER_HOUR 10
MAX_QUERIES_PER_HOUR 1000
MAX_UPDATES_PER_HOUR 200
MAX_USER_CONNECTIONS 3;

0 ( ), , .

2.3.6.
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.1/Data/. C , , , D.
C , .
MySQL
(. 1.13).
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server
5.1/Data/ , , D:/mysql. my.ini [mysqld], datadir ( 2.86).
2.86. my.ini
...
[mysqld]
...
datadir="D:/mysql/"
...


my.ini MySQL- . MySQL mysql , . .
.

2.3.7.


. : SQL-.

129

2.3.7.1.
MyISAM ( MySQL) ,
.

.

,
, , :
frm , , , . .;
MYD (
MYData);
MYI ( MYIndex).

,
, MySQL-
.
, . FLUSH TABLES ( 2.87).
2.87.
FLUSH TABLES WITH READ LOCK;

, , .
,
UNLOCK TABLES ( 2.88).
2.88.
UNLOCK TABLES;

MySQL
mysqlhotcopy. ,
: base
/to/new/path ( 2.89).
2.89. mysqlhotcopy
mysqlhotcopy base /to/new/path

130

2.3.7.2. SQL-
, MySQL
, , ,
. SQL-. SQL- SQL-, .
SQL- mysqldump.
, base,
, 2.90.
2.90. base
:\mysql\bin> mysqldump u root base > base.sql

2.91, mysqldump
u. ,
-p. base, . ( ),
( 2.90 base.sql). >. > >>,
,
.
--databases ( B)
, ( 2.91).
2.91.
:\mysql5\bin> mysqldump u root -B base mysql > base_mysql.sql

, 2.91, base
mysql base_mysql.sql.
MySQL-, --all-databases A ( 2.92).
2.92. MySQL-
mysqldump u root --all-databases > all_databases.sql

SQL- mysql ( 2.93).

131

2.93. mysql
mysql u root test < base.sql

2.93 base.sql
mysql, base test.
SQL- , . SOURCE,
, SQL- ( 2.94).

SOURCE SQL-
bin. .

2.94. SOURCE
mysql> SOURCE base.sql;

2.3.8. phpMyAdmin
MySQL Web- phpMyAdmin.

phpMyAdmin Web http://www.phpmyadmin.net/.

phpMyAdmin
config.inc.php $cfg['Servers'][$i]['host'],
$cfg['Servers'][$i]['user'], $cfg['Servers'][$i]['password']
. ""
, MySQL.
"localhost".
$cfg['PmaAbsoluteUri'] phpMyAdmin:
Web- ,
phpMyAdmin,
http://localhost/phpMyAdmin.
phpMyAdmin
MySQL, :
.
,
.

config.inc.php PHP-, . $i. phpMyAdmin
, $cfg['Servers'][0], $cfg['Servers'][1] . .

132

MySQL 4.1,

phpMyAdmin . cp1251, $cfg['DefaultLang'] $cfg['DefaultCharset']:
$cfg['DefaultLang'] = 'ru-win1251';
$cfg['DefaultCharset'] = 'windows-1251';

SQL- phpMyAdmin MySQL 4.1 UTF8. ,


$cfg['AllowAnywhereRecoding'] true:
$cfg['AllowAnywhereRecoding'] = true;


. . . PHP , PHP
, .
, .
3.1 $arr ,
"Hello", "world".
3.1.
<?php
// $arr
$arr[] = "Hello";
$arr[] = "world";
//
echo $arr[1]; // world
?>

, . $arr[0] , $arr[1] . .
, , . PHP .
, . 3.2
$arr ,
first, second.

134
3.2.
<?php
// $arr
$arr['first'] = "Hello";
$arr['second'] = "world";
//
echo $arr[1]; // world
?>

, .

3.1.
PHP , , .
, . , PHP.

3.1.1. array()
.
array(),
. 3.3 $arr,
, 0 2.
3.3. array()
<?php
$arr
echo
echo
echo
?>

= array("Hello ", "world", "!");


$arr[0]; // Hello
$arr[1]; // world
$arr[2]; // !

3.3 echo. $arr


"Array". print_r(). 3.4
$arr.
print_r() HTML- <pre> </pre>,
.

135

3.4. print_r()
<?php
$arr = array("Hello ", "world", "!");
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.4
$arr:
Array
(
[0] => Hello
[1] => world
[2] => !
)

3.3 3.4, , , C- . ,
. array()
=>. 3.5
$arr 10, 11 12.
3.5.
<?php
$arr = array(10 => "Hello ", "world", "!");
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.5
$arr:
Array
(
[10] => Hello
[11] => world
[12] => !
)


$arr 3.5 09 13 , (. .

136

, NULL). php.ini
(Notice),
.

,
( 3.6).
3.6.
<?php
$arr = array(10 => "Hello ", 9 => "world", 8 => "!");
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.6
$arr:
Array
(
[10] => Hello
[9] => world
[8] => !
)

3.1.2.

( 3.7).
3.7.
<?php
$arr[10] = "Hello ";
$arr[11] = "world";
$arr[12] = "!";
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.7 3.5. ,
( 3.8).

137

3.8.
<?php
$arr[] = "Hello ";
$arr[] = "world";
$arr[] = "!";
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.1.3. :
(. . int, float, string boolean) array.
, 0 , ( 3.9).
3.9.
<?php
$var = "Hello world";
$arr = (array) $var;
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.9
$arr:
Array
(
[0] => Hello world
)

3.1.4.
array(), , . . 3.1.
3.1.

array([...])

138

3.1 ()

array_fill ($start_index,
$num, $value)

, $num ,
$value.
$start_index

range($low, $high [, $step])

$low $high
$step

explode($delimiter,
$str [, $limit])

, $str,
, $delimiter.
$limit

,
array_fill(), :
array_fill($start_index, $num, $value)

, $num ,
$value. $start_index ( 3.10).
3.10. array_fill()
<?php
//
$arr = array_fill(5, 6, "Hello world!");
//
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.10 :
Array
(
[5] => Hello world!
[6] => Hello world!
[7] => Hello world!
[8] => Hello world!
[9] => Hello world!
[10] => Hello world!
)


range(),
:
range($low, $high [, $step])

139

$low , $high . $step , . 3.11 6 ,


0 5.
3.11. range()
<?php
$arr = range(0, 5);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.11 :
Array
(
[0]
[1]
[2]
[3]
[4]
[5]
)

=>
=>
=>
=>
=>
=>

0
1
2
3
4
5

, , ,
range() ( 3.12).

range() .

3.12. range()
<?php
$arr = range(0, 1, 0.2);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

3.12 :
Array
(
[0] => 0
[1] => 0.2

140
[2]
[3]
[4]
[5]

=>
=>
=>
=>

0.4
0.6
0.8
1

. explode(), :
explode($delimiter, $str [, $limit])

,
$str, , $delimiter.
$limit
. () . explode() 3.13.

,
implode().

3.13. explode()
<?php
$str = " e-mail";
$arr = explode(" ", $str);
echo "<pre>";
print_r ($arr);
echo "</pre>";
?>

3.13 :
Array
(
[0] =>
[1] =>
[2] => e-mail
)

3.13 $str $arr


. explode() , , ,
", " "\r\n".
, , , ,
, explode() .

141

3.1.5.
, . ,
array(). 3.14
$ship.
3.14.
<?php
$ship = array(
" " => array("","",""),
" " => array("","",""),
" " => array("","-","")
);
echo "<pre>";
print_r($ship);
echo "</pre>";
?>

:
Array
(
[ ] => Array
(
[0] =>
[1] =>
[2] =>
)
[ ] => Array
(
[0] =>
[1] =>
[2] =>
)
[ ] => Array
(
[0] =>
[1] => -
[2] =>
)
)

3 3, . .
, . , , . .

142

,
$ship[' '][0] "".

3.2.
, print_r() ( 3.15).
3.15. print_r()
<?php
$arr = array(1, 2, 3);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

, .
, for while. foreach.
for :
for(begin; condition; body)
{
;
}

begin ( )
, . , ,
. , . -
(condition) , -
, condition (TRUE), ,
(FALSE). - ,
. body .
3.16 for.
3.16. for
<?php
$number = array("1", "2", "3");
for($i=0; $i < count($number); $i++)

143

{
echo $number[$i];
}
?>

3.16 : 123.
count()
(. . 3.3),
. 3.16 $number
3.
foreach,
:
foreach($array as [$key =>] $value)
{
;
}

$array ,
$key, $value. ( 3.17).

foreach ,
.

3.17. foreach
<?php
$number = array("first" => "1",
"second" => "2",
"third" => "3");
foreach($number as $index => $val) echo "$index = $val <br>";
?>

3.17 :
first = 1
second = 2
third = 3

$index ( 3.18).
3.18. foreach
<?php
$number = array("first" => "1",
"second" => "2",
"third" => "3");

144
foreach($number as $val)
{
echo $val; // 123
}
?>

foreach,
( 3.19).
3.19.
<?php
$ship = array(
" " => array("","",""),
" " => array("","",""),
" " => array("","-","")
);
foreach($ship as $key => $type)
{
//
echo "<b>$key</b><br>";
foreach($type as $ship)
{
//
echo "<li>$ship</li><br>";
}
}
?>

3.19 . 3.1.

. 3.1.

145

3.3.
.
count()
. , , . 3.2.
3.2.

count ($array [, $mode])

$array. $mode
COUNT_RECURSIVE, ,

sizeof()

count()

array_count_values ($input)


,
, $input

count(), :
count ($array [, $mode])

$array. 3.20 .
3.20. count()
<?php
$car = array("",
"",
"",
"");
echo count($car); // 4
?>

, ( 3.21).
3.21. count()
<?php
$arr = array(
array(1, 2, 3, 4),
array(5, 6, 7, 8)
);

146
echo count($arr);
// 2
echo count($arr[0]); // 4
?>

2, . . 2 array(1, 2, 3, 4) array(5, 6, 7, 8). array(1, 2, 3, 4), , count().


, ( ), $mode
COUNT_RECURSIVE ( 3.22).
3.22.
<?php
$arr = array(
array(1, 2, 3, 4),
array(5, 6, 7, 8)
);
echo count($arr, COUNT_RECURSIVE); // 10
?>

array_count_values(), :
array_count_values ($array)

, , $array ( 3.23).

$array ,
.

3.23. array_count_values()
<?php
$array = array (1, "hello", 1, "world", "hello");
$new = array_count_values ($array);
echo "<pre>";
print_r($new);
echo "</pre>";
?>

147

3.23
$new:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

3.4. ?
PHP , .
, : . , , ( ), FALSE.
, , is_array() ( 3.24).
3.24. is_array()
<?php
$arr = array(1, 2, 3);
if(is_array($arr)) echo " <br />";
else echo " <br />";
if(is_array($arr[0])) echo " <br />";
else echo " <br />";
?>

3.5. ?
, . . , , isset() ( 3.25).
3.25. isset()
<?php
$arr = array(5 => 1, 2, 3);

148
for($i = 0; $i < 10; $i++)
{
if(isset($arr[$i])) echo " \$arr[$i] <br>";
else echo " \$arr[$i] <br>";
}
?>

3.25 :

$arr[0]
$arr[1]
$arr[2]
$arr[3]
$arr[4]
$arr[5]
$arr[6]
$arr[7]
$arr[8]
$arr[9]

3.6.
?
, ,
. foreach (. . 3.2),
array_keys(), :
array_keys($arr [, $search_value [, $strict]])

$arr.
$search_value, ,
$search_value. $strict TRUE, $search_value
===, ==. 3.26 .
3.26. array_keys()
<?php
//
$arr = array(0 => 100, "color" => "red");
//
$key = array_keys($arr);

149

//
echo "<pre>";
print_r($key);
echo "</pre>";
?>

:
Array
(
[0] => 0
[1] => color
)

3.27 $search_value. "blue",


array_keys() .
3.27. "blue"
<?php
//
$arr = array("blue", "red", "green", "blue", "blue");
//
$key = array_keys($arr, "blue");
//
echo "<pre>";
print_r($key);
echo "</pre>";
?>

:
Array
(
[0] => 0
[1] => 3
[2] => 4
)

3.7. ?
isset()
, ,
.

150

in_array()
:
in_array($value, $arr [, $strict])

, $value $arr,
TRUE, , FALSE . $strict TRUE, $search_value === (. .
, ),
( 3.28).
3.28.
<?php
$number = array(0.57, '21.5', 40.52);
if (in_array(21.5, $number)) echo " 21.5 ";
else echo " ";
?>

:
21.5

, '21.5' , . . , $number. .
===,
== $strict TRUE ( 3.29).
3.29.
<?php
$number = array(0.57, '21.5', 40.52);
if (in_array(21.5, $number, true)) echo " 21.5 ";
else echo " ";
?>

, . . ,
in_array() (float), (string). 21.5 , (. . ):
if (in_array('21.5', $number, true))

151

3.8.
: .
.
. 3.3.
3.3.

array_key_exists ($key, $arr)

TRUE, $arr $key,


FALSE

array_search($value, $arr
[,$strict])

$value $arr , , ,
FALSE. $strict
TRUE,
$value ===,
==


array_key_exists(), :
array_key_exists ($key, $arr)

TRUE, $key $arr ( 3.30).


3.30.
<?php
$arr = arr("first_numb" => 1, "second_numb" => 2);
if (array_key_exists("first_numb", $arr) echo "";
?>

array_search(), :
array_search ($value, $arr [, $strict])

$value $arr , , , FALSE. $strict TRUE,


$value ===,
==. 3.31.

152

3.31. array_search()
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);
// $key = 1;
?>

3.9.
array_sum()
:
array_sum($arr)

. array_sum() 3.32.
3.32. array_sum()
<?php
$arr = array(1,2,3,4,5);
$sum = array_sum($arr);
echo $sum; // 15
?>

3.10.

rand(), .
rand() :
rand ([$min, $max]);

$min $max , . rand()


, 0,
( 3.33).
3.33.
<?php
//
$arr = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
//
$index = rand(0, count($arr) 1);

153

//
echo $arr[$index];
?>

, 3.25, ,
0 . array_rand() (. 3.4), $arr.
:
array_rand ($arr [, $num_req])

$arr. $num_req
, $arr, $num_req 1,
$arr ( 3.34).
3.4.

array_rand ($arr [, $num_req]) )

. $num_req ,
$arr, $num_req 1,
$arr

shuffle ($arr) )

$arr

3.34. array_rand()
<?php
//
$arr = array("", "", "", "", "");
$rand_keys = array_rand($arr, 2);
echo "<pre>";
print_r($rand_keys);
echo "</pre>";
?>

shuffle() (. 3.4), :
shuffle ($array)

3.35 .

154
3.35. shuffle()
<?php
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
shuffle($arr);
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

shuffle() :
Array
(
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
)

=>
=>
=>
=>
=>
=>
=>
=>
=>
=>

7
9
8
1
3
10
2
4
5
6

3.11.
+, ,
( 3.36).

+, +=.

3.36. +
<?php
$fst = array(1 => "one", 2 => "two");
$snd = array(3 => "three", 4 => "four");
$sum = $fst + $snd;
echo "<pre>";
print_r($sum);
echo "</pre>";
?>

155

3.36
$sum:
Array
(
[1]
[2]
[3]
[4]
)

=>
=>
=>
=>

one
two
three
four

, ( 3.37).
3.37.

<?php
$fst = array("one", "two");
$snd = array("three", "four", "five");
$sum = $fst + $snd;
echo "<pre>";
print_r($sum);
echo "</pre>";
?>

3.37
$sum:
Array
(
[0] => one
[1] => two
[2] => five
)

,
+ (. 3.5).
3.5.

array_merge ($array1 [, $array2


[, ...]]) )

$array1, $array2, ...


array_merge_recursive ($array1
[,$array2, [, ...]]) )

$array1, $array2, ...


3.38 array_merge().

156


array_merge() .

3.38. array_merge()
<?php
$fst = array("one", "two");
$snd = array("three", "four", "five");
$sum = array_merge($fst, $snd);
echo "<pre>";
print_r($sum);
echo "</pre>";
?>


$sum:
Array
(
[0]
[1]
[2]
[3]
[4]
)

=>
=>
=>
=>
=>

one
two
three
four
five

PHP array_merge_recursive()),
array_merge() + ( 3.39).
3.39. array_merge_recursive()
<?php
$ar1 = array("color" => array ("favorite" => "red"), 5);
$ar2 = array(10, "color" => array ("favorite" => "green", "blue"));
$sum = array_merge_recursive ($ar1, $ar2);
echo "<pre>";
print_r($sum);
echo "</pre>";
?>

3.39
$sum:
Array
(
[color] => Array

157
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue

)
[0] => 5
[1] => 10
)

3.12.

, ,
.
, PHP
array_walk(), :
array_walk ($arr, $funcname [, $userdata])

$funcname $arr. $userdata


.
: , $userdata. . $funcname ,
, , ,
@ array_walk().
. , , ( 3.40).

array_walk() array_walk_recursive(), .

3.40. array_walk()
<?php
$name = array ("m"=>"maksim", "i"=>"igor", "s"=>"sergey");
function print_array ($item, $key)
{
echo "$key=>$item<br>\n";
}

158

/* print_array
$name */
array_walk ($name, 'print_array');
?>

:
m => maksim
i => igor
s => sergey

array_map())
. :
array_map ($callback, $arr1 [, ...])

$callback , . , , , array_map(). 3.41


$arr $cub, $arr.
3.41.
<?php
//
//
function cube($n)
{
return $n*$n*$n;
}
//
$arr = array(1, 2, 3, 4, 5);
//
$cub = array_map("cube", $arr);
//
echo "<pre>";
print_r($cub);
echo "</pre>";
?>

:
Array
(
[0] => 1
[1] => 8

159

[2] => 27
[3] => 64
[4] => 125
)

3.13.

, , . array_unique()), :
array_unique ($array)

3.42 .
3.42.
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
echo "<pre>";
print_r($result);
echo "</pre>";
?>

$result:
Array
(
[a] => green
[0] => red
[1] => blue
)

3.14.

, ,
( 3.43).
3.43. ,
<?php
// , ,
function get_date($time)

160

{
return array(date("Y", $time), date("m", $time), date("d", $time));
}
//
$arr = get_date(time());
// $arr
echo "<pre>";
print_r($arr);
echo "<pre>";
?>

get_date()
UNIXSTAMP, date() (,
) . , 3.43 $arr:
Array
(
[0] => 2010
[1] => 05
[2] => 12
)

, , ,
. PHP list(). 3.44 get_date() $year, $month $day, , .
3.44. list()
<?php
// , ,
function get_date($time)
{
return array(date("Y", $time), date("m", $time), date("d", $time));
}
//
list($year, $month, $day) = get_date(time());
echo " $year<br />";
// 2010
echo " $month<br />"; // 05
echo " $day<br />";
// 12
?>

, list() , . 3.45

161

get_date(), . list()
$year, $month $day , .
3.45. list()
<?php
// , ,
function get_date($time)
{
return array("year" => date("Y", $time),
"month" => date("m", $time),
"day"
=> date("d", $time));
}
//
list($year, $month, $day) = get_date(time());
echo " $year<br />";
// Notice: Undefined offset
echo " $month<br />"; // Notice: Undefined offset
echo " $day<br />";
// Notice: Undefined offset
?>

list() ,

list() . , ,
, . , ,
( 3.46).
3.46.
<?php
// , ,
function get_date($time)
{
return array(date("Y", $time), date("m", $time), date("d", $time));
}
//
list(, $month) = get_date(time());
echo " $month<br />"; // 05
?>

162

3.15.
PHP
(. 3.6).
3.6.

sort ($array [, $sort_flags]) )

$array .
$sort_flags :
SORT_REGULAR ;
SORT_NUMERIC ;
SORT_STRING ;
SORT_LOCALE_STRING ,

rsort ($array [, $sort_flags])

$array

asort ($array [, $sort_flags])

$array
-

arsort ($array [, $sort_flags] )

$array -

natsort ($array)

"" $array,

natcasesort ($array)

"" $array,

ksort ($array [, $sort_flags])

$array
-

krsort ($array [, $sort_flags])

$array
-

usort ($array, $cmp_function)

$array $cmp_function

uasort ($array, $cmp_function)

$array $cmp_function -

uksort ($array, $cmp_function)

$array

$cmp_function -

array_multisort ($ar1 [, $arg


[, ... [, ...]]])

sort() $arr :
sort($arr [, $sort_flags])

163

$sort_flags , ( ). :
SORT_REGULAR ;
SORT_NUMERIC ;
SORT_STRING ;
SORT_LOCALE_STRING ,

.
3.47 sort().
3.47.
<?php
$number = array("2", "1", "4", "3","5"); //
echo " : <br>";
for($i=0; $i < count($number); $i++)
{
echo "$number[$i] ";
}
sort($number); //
echo "<br> : <br>";
for($i = 0; $i < count($number); $i++)
{
echo "$number[$i] ";
}
?>

:
:
2 1 4 3 5
:
1 2 3 4 5

.
--. ,
:
array("one",
"two",
"abs",
"three",
"uic",
"for",
"five"),

164

sort :
[0]
[1]
[2]
[3]
[4]
[5]
[6]

=>
=>
=>
=>
=>
=>
=>

abs
five
for
one
three
two
uic

rsort() :
rsort ($arr [, $sort_flags])

sort(). 3.48 rsort().


3.48.
<?php
$number = array("2", "1", "4", "3","5"); //
echo(" : <br>");
for($i=0; $i < count($number); $i++)
{
echo "$number[$i] ";
}
rsort($number); //
echo "<br> : <br>";
for($i=0; $i < count($number); $i++)
{
echo "$number[$i] ";
}
?>

:
:
2 1 4 3 5
:
5 4 3 2 1

asort() :
asort ($arr [, $sort_flags])

asort() $arr ,
( ) ( ) . $sort_flags , sort().
sort() , asort()

165

( 3.49), sort() ( ).
3.49. assort()
<?php
$arr = array("a" => "one",
"b" => "two",
"c" => "three",
"d" => "four");
asort($arr);
foreach($arr as $key => $val)
{
echo " $key => $val ";
}
?>

:
d => four a => one c => three b => two

, "-" . sort(),
:
0 => four 1 => one 2 => three 3 => two

arsort() asort(),
, .
arsort($arr [, $sort_flags])

ksort() ,
, . :
ksort ($arr [, $sort_flags])

$sort_flags , sort(). 3.50


ksort().
3.50.
<?php
$arr = array("a"
"d"
"c"
"b"
);
ksort($arr);

=>
=>
=>
=>

"one",
"four",
"three",
"two"

166

foreach($arr as $key => $val)


{
echo (" $key => $val ");
}
?>

:
a => one b => two c => three d => four

krsort() ( ). ksort().
:
krsort ($arr [, $sort_flags])

natsort() "" :
natsort($arr)

,
. .

file1.txt
file10.txt
file2.txt
file12.txt
file20.txt

("")
:
file1.txt
file10.txt
file12.txt
file2.txt
file20.txt

:
file1.txt
file2.txt
file10.txt
file12.txt
file20.txt

natsort(),
( 3.51).

167

3.51.
<?php
$arr_first = $arr_second =
array( "file12.txt",
"file10.txt",
"file2.txt",
"file1.txt");
sort($arr_first);
echo " <br>";
echo "<pre>";
print_r($arr_first);
echo "</pre>";
natsort($arr_second);
echo "<br> <br>";
echo "<pre>";
print_r($arr_second);
echo "</pre>";
?>

Array
(
[0]
[1]
[2]
[3]
)

=>
=>
=>
=>

file1.txt
file10.txt
file12.txt
file2.txt


Array
(
[3] => file1.txt
[2] => file2.txt
[1] => file10.txt
[0] => file12.txt
)

array_multisort() .
:
array_multisort($ar1 [,$arg [, ... [, ...]]] )

, array_multisort(),

168
array_multisort(arr1, $arr2, , $arrN)

$arr1[0]

$arr2[0]

$arrN[0]

$arr1[1]

$arr2[1]

$arrN[1]

$arr1[2]

$arr2[2]

...

...

...

$arr1[n]

$arr2[n]

$arrN[n]

...

$arrN[2]

. 3.2. array_multisort()

. ,
(. 3.2).
3.52 $arr1 $arr2.
3.52. array_multisort()
<?php
$arr1 = array(3, 4, 2, 7, 1, 5);
$arr2 = array("world", "Hello", "yes", "no", "apple", "wet");
array_multisort($arr1, $arr2);
echo "<pre>";
print_r($arr1);
print_r($arr2);
echo "</pre>";
?>

3.52 :
Array
(
[0]
[1]
[2]
[3]
[4]
[5]
)

=>
=>
=>
=>
=>
=>

1
2
3
4
5
7


Array
(
[0]
[1]
[2]
[3]
[4]
[5]
)

169

=>
=>
=>
=>
=>
=>

apple
yes
world
Hello
wet
no

, , ,
.
array_multisort() , (. 3.7).

SORT_ASC SORT_DESC, SORT_REGULAR, SORT_NUMERIC SORT_
STRING .

3.7. , array_multisort()

SORT_ASC

SORT_DESC

SORT_REGULAR

SORT_NUMERIC

SORT_STRING

3.53 ,
.
3.53.
<?php
$arr1 = array(3, 4, 2, 7, 1, 5);
$arr2 = array("world", "Hello", "yes", "no", "apple", "wet");
array_multisort($arr1, SORT_DESC, SORT_NUMERIC, $arr2);
echo "<pre>";
print_r($arr1);
print_r($arr2);
echo "</pre>";
?>

170

3.53 :
Array
(
[0]
[1]
[2]
[3]
[4]
[5]
)
Array
(
[0]
[1]
[2]
[3]
[4]
[5]
)

=>
=>
=>
=>
=>
=>

7
5
4
3
2
1

=>
=>
=>
=>
=>
=>

no
wet
Hello
world
yes
apple

3.16.

. (
),
, .
. 3.3 ,
.

. 3.3.

171

$comments,
3.54. ,
"text",
"id_parent" .
3.54.
<?php
$comments = array(
1 => array(
"text" => " ",
"id_parent" => 0),
2 => array(
"text" => " ",
"id_parent" => 1),
3 => array(
"text" => " ",
"id_parent" => 2),
4 => array(
"text" => " ",
"id_parent" => 1),
5 => array(
"text" => " ",
"id_parent" => 4),
6 => array(
"text" => " ",
"id_parent" => 3)
);
?>

$comments, ,
$parents, ( 3.55).
3.55. $parents
<?php
//
$parents = array();
foreach($comments as $id => $elements)
{
$parents[$elements['id_parent']][] = $id;
}
echo "<pre>";
print_r($parents);
echo "</pre>";
?>

172

$parents ,
, .
$parents $comments :
Array
(
[0] => Array
(
[0] =>
)
[1] => Array
(
[0] =>
[1] =>
)
[2] => Array
(
[0] =>
)
[4] => Array
(
[0] =>
)
[3] => Array
(
[0] =>
)
)

2
4

. , ,
( 3.56).
$comments $parents global, ,
.
3.56.
<?php
...
// $id_parent
// $indent

function print_hierarchy($id_parent = 0, $indent = "")
{
// $comments $parents
//
//
global $comments, $parents;

173

// ,
// $id_parent ,
if(!isset($parents[$id_parent])) return;
// ,
// $id_parent
for($i = 0; $i < count($parents[$id_parent]); $i++)
{
//
echo "<div style='padding-left:{$indent}px'>".
$comments[$parents[$id_parent][$i]]['text']."</div>";
//
//
print_hierarchy($parents[$id_parent][$i], $indent + 20);
}
}
// ,
print_hierarchy();
?>

print_hierarchy() 3.56 , $id_parent .


0, . $indent , .
CSS- padding-left. , , 20 . 3.56 . 3.3.

3.17.
PHP
, PHP Web-.
, global.
Web- PHP
Web. . 3.8 .
3.8.

$_GET

, ( GET)

$_POST

, POST ( HTTP-)

$_FILES

POST

174

3.8 ()

$_COOKIE

, HTTP- Set-Cookie

$_REQUEST

$_GET, $_POST $_COOKIE

$_SESSION

$_SERVER

, Web-, HTTP-

$_ENV

, $_SERVER

$GOBALS

(
), , , , global

3.18. $_GET
GET- (?).
http://localhost/index.php?id=1
URL id=1 GET- id 1. GET- $_GET. . 3.57 GET- id.

HTTP, PHP, GET , . $_GET, , $_SERVER['QUERY_STRING'], GET-.

3.57. GET- id_forum


<?php
echo $_GET['id']; // 1
?>

GET, &:
http://localhost/index.php?id =1&number=2&page=10

175

URL GET-: id 1,
number 2 page 10 ( 3.58).
3.58. $_GET
<?php
echo "<pre>";
print_r($_GET);
echo "</pre>";
?>

3.58 $_GET:
Array
(
[id] => 1
[number] => 2
[page] => 10
)

GET- , $_GET . ,
http://localohost/index.php?id[]=1&id[]=2&id[]=10
3.58 :
Array
(
[id] => Array
(
[0] => 1
[1] => 2
[2] => 10
)
)

, 0,

.
http://localhost/index.php?id[a]=1&id[b]=2&id[c]=10
3.58 :
Array
(
[id] => Array
(
[a] => 1

176
[b] => 2
[c] => 10
)
)

GET- URL
(, ), URL .
PHP (. 3.9).
3.9. URL

urlencode($str)

$str, ,
, ,
, %. +

urldecode($str)

urlencode(), , %

rawurlencode($str)

$str, ,
, ,
, %. urlencode(),
+, %20

rawurldecode($str)

rawurlencode() , , %

parse_url($url [, $component])

$url ,
.
$component
: PHP_URL_SCHEME, PHP_URL_HOST,
PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH,
PHP_URL_QUERY PHP_URL_FRAGMENT,

http_build_query ($formdata [,
$numeric_prefix [,
$arg_separator]])


$formdata.
$numeric_prefix, GET. $arg_separator GET-, &

3.59 test.php, GET- phrase


", !".
3.59. urlencode()
<?php
echo "<a href='test.php?phrase=".
urlencode(", !")."'></a>";
?>

177

HTML-
:
<a href='test.php?phrase=%CF%F0%E8%E2%E5%F2%2C+%EC%E8%F0%21'></a>

GET-
, , . .
parse_url(),
:
scheme , , http, https, ftp . .;
host ;
port ;
user ;
pass ;
path ;
query , (?);
fragment , #.

3.60 URL
parse_url().
3.60. parse_url()
<?php
$url = 'http://user:pass@www.site.ru/path/index.php?par=value#anch';
$arr = parse_url($url);
echo "<pre>";
print_r($arr);
echo "<pre>";
?>

$arr:
Array
(
[scheme] => http
[host] => www.site.ru
[user] => user
[pass] => pass
[path] => /path/index.php
[query] => par=value
[fragment] => anch
)

178

parse_url() , .
:
PHP_URL_SCHEME , , http, https, ftp . .;
PHP_URL_HOST ;
PHP_URL_PORT ;
PHP_URL_USER ;
PHP_URL_PASS ;
PHP_URL_PATH ;
PHP_URL_QUERY , (?);
PHP_URL_FRAGMENT , #.

3.61 parse_url()
PHP_URL_HOST .
3.61. parse_url()
<?php
$url = 'http://user:pass@www.site.ru/path/index.php?par=value#anch';
echo parse_url($url, PHP_URL_HOST); // www.site.ru
?>

3.19.
.

, .
.
, ( 3.62), ,
. GET ( GET- page).
$start $end ,
.
3.62.
<?php
$language[] = "PHP";
$language[] = "++";
$language[] = "Java";


$language[]
$language[]
$language[]
$language[]
$language[]
$language[]
$language[]
$language[]
$language[]
$language[]
$language[]

179
=
=
=
=
=
=
=
=
=
=
=

"Ruby";
"Python";
"Perl";
"JavaScript";
"Visual Basic";
"Fortran";
"Pascal";
"Assembler";
"Lisp";
"Haskell";
"C#";

//
$pnumber = 2;
// ,
if(isset($_GET['page'])) $page = intval($_GET['page']);
else $page = 1;
//
$total = count($language);
//
$number = (int)($total/$pnumber);
if((float)($total/$pnumber) $number != 0) $number++;
// $language
//
$start = (($page 1)*$pnumber + 1);
// $language
//
$end = $page*$pnumber + 1;
if($end > $total) $end = $total;
//
for($i = $start; $i < $end; $i++)
{
echo $language[$i]."<br />";
}
//
for($i = 1; $i <= $number; $i++)
{
//
if($i != $number)
{
if($page == $i)

180
{
//
echo "[".(($i 1)*$pnumber + 1)."-".$i*$pnumber."]&nbsp;";
}
else
{
echo "<a href='index.php?page=$i'>[".
(($i 1)*$pnumber + 1)."-".$i*$pnumber."]</a>&nbsp;";
}
}
// ,
// $temp
else
{
if($page == $i)
{
//
echo "[".(($i 1)*$pnumber + 1)."-".($total 1)."]&nbsp;";
}
else
{
echo "<a href='index.php?page=$i'>[".
(($i 1)*$pnumber + 1)."-".($total 1)."]</a>&nbsp;";
}
}
}
?>

3.62 . 3.4.

. 3.4.

181

3.20. $_POST
GET ,
, ,
, .
,
, POST, GET HTTP-, HTTP-.
- POST HTML-, <form> method "post"
( 3.63). HTML- :
first second , .
3.63. HTML-
<form action='index.php' method='post'>
<input type='text' name='first' /><br>
<input type='text' name='second' /><br>
<input type='submit' value="">
</form>

action <form> ,
.
, , .
, $_POST. 3.64
HTML-, .
3.64. $_POST
<?php
// HTML-
if(!empty($_POST))
{
echo "<pre>";
print_r($_POST);
echo "</pre>";
exit();
}
?>
<form action='index.php' method='post'>
<input type='text' name='first' /><br>
<input type='text' name='second' /><br>
<input type='submit' value="">
</form>

182

, $_POST. ,
HTML-, - ,
.

3.21. .
$_FILES
POST, $_POST, ,
$_FILES.
, HTML ,
( ).
:
<input type='file' />

type name, .
3.65.
3.65. HTML- (index.html)
<html><head><title> </title></head><body>
<h2><b> </b></h2>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="filename"><br>
<input type="submit" value=""><br>
</form>
</body>
</html>

entype ,
. ,
entype multipart/form-data. application/x-www-form-urlencoded.
, .
, , . 3.5.
HTTP-, , , , php.ini ( upload_tmp_dir).

183

. 3.5.

$_FILES , file, :
$_FILES['filename']['name'] ( -

);
$_FILES['filename']['size'] ( );
$_FILES['filename']['type'] ( MIME- );
$_FILES['filename']['tmp_name'] ( ,

).
3.66 upload.php,
temp.


is_uploaded_file(),
($_FILES['filename']['name']) TRUE FALSE
.

3.66. (upload.php)
<html>
<head>
<title> </title>
</head>
<body>
<?php
if (move_uploaded_file($_FILES['filename']['tmp_name'],
"temp/".$_FILES['filename']['name']))
{
echo " ";
}

184

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

move_uploaded_file(),
, ,
.

temp , ,
" ".
3.67 .
3.67.
<html>
<head>
<title> </title>
</head>
<body>
<?php
if (move_uploaded_file($_FILES["filename"]["tmp_name"],
"temp/".$_FILES["filename"]["name"]))
{
echo " <br>";
//
echo " : <br>";
echo " : ";
echo $_FILES["filename"]["name"];
echo "<br> : ";
echo $_FILES["filename"]["size"];
echo "<br> : ";
echo $_FILES["filename"]["tmp_name"];
echo "<br> : ";
echo $_FILES["filename"]["type"];
}
else
{
echo " ";
}
?>
</body>
</html>

185

. 3.6.

, . 3.6.
, . , 3 , , 3.68.
3.68.
<?php
if ($_FILES['filename']['size'] > 3*1024*1024)
{
exit " ";
}
if (copy(_FILES['filename']['tmp_name'],
"temp/".$_FILES['filename']['name']))
{
echo " <br>";
}
else
{
echo " ";
}
?>

upload_max_filesize, 2 :
if ($_FILES['filename']['size'] > upload_max_filesize)


upload_max_filesize
php.ini.

186

3.22.

Web-, (. 3.7).

9 AJAX- .

. 3.7. HTML-

, JavaScript, HTML- ( 3.69). ,


, Web-,
files, , .

Web- , HTML-,
. HTML- .

3.69.
<?php
if(!empty($_FILES))
{
// HTML-
//
for($i = 0; $i < count($_FILES['filename']['name']); $i++)
{
//
// /files Web-
if (!move_uploaded_file($_FILES['filename']['tmp_name'][$i],
"files/".$_FILES['filename']['name'][$i]))

187

{
echo " ";
}
}
// ,
// $_POST
//
header("Location: index.php");
exit();
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input class='files' type='file' name='filename[]' /></td>
<td><input type='button' name='drop'
value=' &minus; ' onclick='dropline(this);' />
<input type='button' value=' + '
onclick='addline(this);' /></td></tr>
<tr><td><input type='submit' value='' /></td><td></td></tr>
</table>
</form>
<script language='JavaScript1.1' type='text/javascript'>
<!-function dropline(btn)
{
if(document.getElementById)
{
while (btn.tagName != 'TR') btn = btn.parentNode;
btn.parentNode.removeChild(btn);
}
}
function addline(btn)
{
if(document.getElementById)
{
while (btn.tagName != 'TR') btn = btn.parentNode;
var newTr = btn.parentNode.insertBefore(
btn.cloneNode(true),
btn.nextSibling);
thisChilds = newTr.getElementsByTagName('td');
for (var i = 0; i < thisChilds.length; i++)
{
if (thisChilds[i].className == 'files')
thisChilds[i].innerHTML =
'<input class="files" type="file" name="filename[]" />';

188
}
}
}
//-->
</script>

HTML- file. HTML- ,


,
$_POST['_'][]. HTML- file att[],
$_POST['att']. 0. , $_FILES ,
. move_uploaded_
file() files.

3.23. Cookie.
$_COOKIE
HTTP-, , . ,
, , ,
, .
, . HTTP cookie, : , - .
Cookies ,
, , . "cookie"
, , ,
. cookie
, .
cookie setcookie(), :
setcookie($name [, $value [, $expire [, $path [, $domain [, $secure]]]]])

:
$name cookie;
$value , cookie name;
$expire , 0 00 1 1970 .

cookie ;

189

$path , cookie;
$domain , cookie;
$secure , , cookie

HTPPS. 0,
cookie
HTTP.
setcookie() TRUE cookie
FALSE . cookie , Web-, $_COOKIE cookie.
cookie HTTP-, setcookie()

echo(), print() . ., HTML-. cookie
3.70. cookie
$_COOKIES.

cookie , cookie; cookie , . .
, .
cookie.

3.70.
<?php
//
error_reporting(E_ALL & ~E_NOTICE);
// cookie
$_COOKIE['counter']++;
// cookie
setcookie("counter", $_COOKIE['counter']);
// cookie
echo " $_COOKIE[counter] ";
?>

, 3.70, . 3.8.
3.70 cookie counter,
.
cookie time() mktime() ( 3.71).

190

. 3.8. cookies

3.71. cookie
<?php
// Cookie 10
setcookie("name", "value", time() + 600);
// cookie 25 2010
setcookie("name", "value", mktime(0,0,0,1,25,2010));
// cookie 18:00 25 2010
setcookie("name", "value", mktime(18,0,0,1,25,2010));
?>


, 32- ,
1901 2038.
cookie , , ,
2100. cookie .

cookie ,
(, /web), ( 3.72).
3.72. cookie
<?php
setcookie("name", "value", time() + 600, "/web");
?>

cookie , , 3.73.

191

3.73. cookie
<?php
setcookie("name", "value");
?>


, cookie ,
.

Cookie setcookie(), HTTP-


Set-Cookie header() ( 3.74).
3.74. cookie
<?php
$cookie = "Set-Cookie: name=value; ".
"expires=Thu, 30-Aug-2008 13:00:04 GMT; ".
"path=/; ".
"domain=www.softtime.ru";
header($cookie);
?>

3.24. Cookie ?
cookies . Web-, cookie,
, , cookies .
, , , cookies. 3.75.
3.75. , cookies
<?php
//
// (http://www.softtime.ru/info/articlephp.php?id_article=23)
error_reporting(E_ALL & ~E_NOTICE);
if(!isset($_GET['probe']))
{
// cookie "test"
if(setcookie("test","set"));
// ,
// cookie
header("Location: $_SERVER[PHP_SELF]?probe=set");
}

192
else
{
if(!isset($_COOKIE['test']))
{
echo "
cookies";
}
else
{
echo "Cookies ";
}
}
?>


$_SERVER , Web . $_SERVER['PHP_SELF'], . , phpinfo().

3.75 cookies
setcookie() cookie. setcookie() , ,
cookie.
GET- probe set, ,
, , -
$_COOKIE['test']. , cookies ,
.

3.25. .
$_SESSION
cookie , "/", , .
, cookies. .
.
,
, (SID),
, cookies, .
PHP-, . .
php.ini session.
cookie_lifetime .

193

, cookies, . Cookies
, . ( )
, ( , , . .). ,
, ( )
. ( ) ( on-line . .).
.
session.save_path php.ini
, ;
Web- . , .
, cookie
SID, . session_start().
, .
, setcookie(), session_start() , . . SID cookie, . . HTTP- SetCookie.

session.auto_start php.ini
1, , session_start().


$_SESSION. 3.76 index.php $_SESSION .
3.76. $_SESSION
<?php
//
session_start();
//
$_SESSION['name'] = "value";
//
$arr = array("first", "second", "third");
$_SESSION['arr'] = $arr;

194
//
echo "<a href='other.php'> </a>";
?>

, session_start(),
$_SESSION. 3.77 other.php, ,
index.php.

$_SESSION , , . . , serialize(), .

3.77. $_SESSION
<?php
//
session_start();
// $_SESSION
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>

:
Array
(
[name] => value
[arr] => Array
(
[0] => first
[1] => second
[2] => third
)
)

, session_destroy(), :
session_destroy()

TRUE FALSE
. , , , unset(),
$_SESSION . -

195

, session_destroy(), TRUE FALSE .



$_SESSION:
unset($_SESSION['name'])

session_id(),

:
session_id([$id])

.
$id ,
. session_id()
session_start() ( 3.78).
3.78.
<?php
//
session_start();
//
echo session_id();
?>

3.78 :
a27e8c4724f07cae913c50e55cea1b38

3.26. .
$_SERVER
PHP ,
. PHP
, , . ,
$_SERVER PHP- Web- Apache. Web-.
$_SERVER.

$_SERVER print_r(), ,
phpinfo(), PHP-.

196

3.26.1. $_SERVER['DOCUMENT_ROOT']
$_SERVER['DOCUMENT_ROOT'] . , , , .
httpd.conf DocumentRoot, "D:/main" ( 3.79), $_SERVER['DOCUMENT_ROOT']
"D:\main".
3.79.
NameVirtualHost 127.0.0.1:80
<VirtualHost 127.0.0.1:80>
ServerAdmin admin@localhost
DocumentRoot "D:/main"
ServerName localhost
ErrorLog logs/ error_log
CustomLog logs/ access_log common
</VirtualHost>

3.26.2. $_SERVER['HTTP_ACCEPT']
$_SERVER['HTTP_ACCEPT'] . HTTP- Accept, .
:
image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/
x-shockwave-flash, application/vnd.ms-excel, application/msword, */*

Accept ,
. , .
* . , */* , type/* type.

.

.

q, 0 1 ,
. q
.

197


q 1. ,
.

Accept:
Accept: audio/*; q=0.2, audio/basic

audio/* ( ), 0,2. audio/basic, , 1.


:
audio/basic, audio-,
,
80 %.

RFC2616, HTTP,
http://www.ysn.ru/docs/cie/RFC/2616/index.htm.

:
Accept: text/plain; q=0.5, text/html,
text/x-dvi; q=0.8, text/x-c


, $_SERVER['HTTP_ACCEPT']
, Accept:.

: text/html
text/x-c , , ,
, text/x-dvi, ,
text/plain.

3.26.3. $_SERVER['HTTP_ACCEPT_LANGUAGE']
$_SERVER['HTTP_ACCEPT_LANGUAGE']
. HTTP- AcceptLanguage, . :
Accept-Language: ru, en; q=0.7

:
, .
$_SERVER['HTTP_ACCEPT_LANGUAGE'] , Accept-Language:
ru, en; q=0.7

$_SERVER['HTTP_ACCEPT_LANGUAGE']
, . . ( ).

198

3.26.4. $_SERVER['HTTP_HOST']
$_SERVER['HTTP_HOST'] , , , ,
$_SERVER['SERVER_NAME'].
(http://), :
www.sofftime.ru


-
www.softtime.ru, softtime.ru.

3.26.5. $_SERVER['HTTP_REFERER']
$_SERVER['HTTP_REFERER'] , . . index.php ( 3.80) page.php ( 3.81).
3.80. index.php
<?php
echo "<a href=page.php> PHP</a><br>";
echo " \$_SERVER['HTTP_REFERER'] ".
$_SERVER['HTTP_REFERER']
?>

page.php ,
index.php ( 3.81).
3.81. page.php
<?php
echo "<a href=index.php> PHP</a><br>";
echo " \$_SERVER['HTTP_REFERER'] ".
$_SERVER['HTTP_REFERER']
?>

. 3.9.

199

,
, (. 3.9).

3.26.6. $_SERVER['HTTP_USER_AGENT']
$_SERVER['HTTP_USER_AGENT'] .
: "Mozilla/4.0 (compatible; MSIE 6.0;
Windows NT 5.1)". "MSIE 6.0" ,
Internet Explorer 6.0. "Windows
NT 5.1" , Windows XP.

Windows 2000 $_SERVER['HTTP_USER_AGENT'] : "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)')",
Windows XP "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)".

Opera, $_SERVER['HTTP_
USER_AGENT'] : "Mozilla/4.0 (compatible; MSIE
5.0; Windows 98) Opera 6.04 [ru]". "MSIE 6.0" , , Opera Internet Explorer
Windows. , , , Internet Explorer , "MSIE 6.0" "Opera".
, , Windows 98.
Netscape $_SERVER['HTTP_USER_
AGENT'] : "Mozilla/5.0 (X11; U; Linux i686;
en-US; rv:1.4) Gecko/20030624 Netscape/7.1".
"Netscape". , ,
, Linux,
, Pentium IV,
X-Window. , .

3.26.7. $_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_ADDR'] IP- . 127.0.0.1. IP- -,
. -,
IP- $_SERBER['HTTP_X_
FORWARDED_FOR'].

200


- ,
: , ,
. . - -, IP- , HTTP_X_FORWARDED_FOR.

3.26.8. $_SERVER['SCRIPT_FILENAME']
$_SERVER['SCRIPT_FILENAME']
.
Windows, d:\main\test
\index.php, . . , UNIX- /, : /var/share/www/test/index.php.

3.26.9. $_SERVER['SERVER_NAME']
$_SERVER['SERVER_NAME'] , , , . :
www.softtime.ru

$_SERVER['SERVER_NAME'] $_SERVER['HTTP_HOST'].
$_SERVER , IP- , , Web- HTTP. $_SERVER['SERVER_ADDR'],
$_SERVER['SERVER_PORT'], $_SERVER['SERVER_SOFTWARE'] $_SERVER['SERVER_PROTOCOL']
. 3.82 .
3.82 . 3.10.

. 3.10. 3.82

201

3.82. $_SERVER
<?php
echo
echo
echo
echo
echo
?>

" ".$_SERVER['SERVER_NAME']."<br>";
"IP- ".$_SERVER['SERVER_ADDR']."<br>";
" ".$_SERVER['SERVER_PORT']."<br>";
"Web- ".$_SERVER['SERVER_SOFTWARE']."<br>";
" HTTP- ".$_SERVER['SERVER_PROTOCOL']."<br>";

3.26.10. $_SERVER['REQUEST_METHOD']
$_SERVER['REQUEST_METHOD'] , : GET POST ( 3.83).
3.83.
<?php
echo $_SERVER['REQUEST_METHOD']; // GET
?>

3.26.11. $_SERVER['QUERY_STRING']
$_SERVER['QUERY_STRING'] , ,
:
http://www.mysite.ru/test/index.php?id=1&test=wet&id_theme=512

$_SERVER['QUERY_STRING'] ?. , , 3.84, ?,
.
3.84 . 3.11.

. 3.11. 3.84

202

3.84. $_SERVER['QUERY_STRING']
<?php
echo $_SERVER['QUERY_STRING'];
?>

3.26.12. $_SERVER['PHP_SELF']
$_SERVER['PHP_SELF'] , :
http://www.mysite.ru/test/index.php?id=1&test=wet&id_theme=512

$_SERVER['PHP_SELF'] /test/index.php.
, $_SERVER['SCRIPT_NAME'].

3.26.13. $_SERVER['REQUEST_URI']
$_SERVER['REQUEST_URI'] , , :
http://www.mysite.ru/test/index.php?id=1&test=wet&id_theme=512

$_SERVER['REQUEST_URI'] /test/index.php?id=
1&test=wet&id_theme=512. ,
, $_SERVER, 3.85.
3.85.
<?php
echo "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>


.
- . ,
.
, , . ,
.

4.1.
, (. 4.1).
4.1.

fopen($filename, $mode [,
$use_include_path [,
$context]])

$filename $mode. , , . $use_include_path


. , FALSE.
$context HTTP-,

fclose($handle)

, fopen().
$handler
. TRUE FALSE

touch($filename [, $time [,
$atime]])

touch() $time
$atime. , ,
.
. 13.5

tempnam($dir, $prefix)

$dir ,
$prefix.
, FALSE

204

4.1 ()

tmpfile()


. .
, FALSE

. -
, , . , , :
/var/home/www/htdocs/text.txt
C:\www\htdocs\text.txt


Windows , A B , . UNIX- (root-) /,
. , Windows
, , UNIX-
.
fopen() tmpfile() ,
, . . , .

. UNIX- /, Windows \. , Windows-. ,


20
Microsoft, DOS. PHP /, \. , . 4.1
Windows-, .
4.1.
<?php
$windows = "C:\\www\\htdocs\\text.txt";
$php
= "C:/www/htdocs/text.txt";
?>

4.1, /,
.

205

, ( , ,
).
. 4.1 ,
C:/www/ . . 4.2
:/www/base/1.txt,
C:/www/scr.php.

. 4.1.

4.2. 1.txt
<?php
// 1.txt
$absolute = ":/www/base/1.txt";
// 1.txt
$relative = "base/1.txt";
?>

, ,
/ ,
.
. 4.1, C:/dir/text.txt,
dir.
.., ( 4.3).

206


, ( ..), , .

4.3.
<?php
// text.txt
$absolute = ":/dir/text.txt";
// text.txt
$relative = "../dir/1.txt";
?>

, .., , ../../../result/text.txt.

. Web ,
, , http://www.softtime.ru/index.php.
, ,
.
touch() ( 4.4).
4.4. touch()
<?php
//
$filename = "text.txt";
// $filename
touch($filename);
?>

4.4 , , text.txt. touch() , .



( , ), . ""
fopen(), :
fopen($filename, $mode [, $use_include_path [, $context]])

,
$filename $mode. ,
, $use_include_path (
). , FALSE.

207

. 4.2 $mode,
.
4.2. fopen()

r+

w+

a+

x+

, , r r+.

fopen() FALSE,
. 4.5 text.txt fopen().
4.5. fopen()
<?php
//
$filename = "text.txt";
//
$fd = fopen($filename, "w");
// ,
if (!$fd)
{
echo " <br>";
fclose($fd);
}
?>

fclose() , . .
. - fclose(), : , .
, fflush(),

208

fclose(). , , , .

4.2.

,
. tempnam()
:
tempnam($dir, $prefix)

$dir
$prefix. tempnam() . - , FALSE.
4.6 .
4.6.
<form method='post'>
<input type='submit' value=''>
</form>
<?php
// HTML-
if (isset($_POST))
{
//
$filename = tempnam("./", "fl");
//
$fd = fopen($filename, "w");
//
fclose($fd);
}
?>

tempnam() PHP
tmpfile(), ,
. ,
. tmpfile(), ,
tempnam(), .

209

4.3. ,

,
, . ,
, . 4.3.
4.3.

copy($source, $destination)

$source $destination.
TRUE, FALSE

unlink($filename)

$filename.
TRUE, FALSE

rename($oldname, $newname)

$oldname,
$newname. TRUE, FALSE

4.7 copy(), /etc/my.cnf . my.cnf


, .
4.7. copy()
<?php
if (copy("/etc/my.cnf", "my.cnf")) echo " ";
else echo " ";
?>

,
unlink() ( 4.8).
4.8.
<?php
//
if (!copy("/etc/my.cnf", "my.cnf")) exit " ";
//
if (unlink("/etc/my.cnf")) echo " ";
else echo " ";
?>

, rename(), , -

210


, ( 4.9).
4.9. rename()
<?php
//
if (rename("/etc/my.cnf", "my.cnf")) echo " ";
else echo " ";
?>

copy() rename() ,
. 4.10 http://www.
softtime.ru/index.php.
4.10.
<?php
if (copy("http://www.softtime.ru/index.php", "index.htm"))
echo " ";
else echo " ";
?>

PHP-, HTML ( ).
, Web-, .
copy() .

4.4.
fopen() ; .
fopen() . 4.2.
,
(. 4.2). .
.
r, w x . ,
, . , ,
a,
. , a+ ,
, . . .

211

. 4.2.

, , , , , .
4.11 , text.txt,
( fgetc()) .
4.11.
<?php
//
$fd = fopen("text.txt", "r");
if (!$fd) exit(" text.txt");
// ,
while(($char = fgetc($fd)) !== FALSE)
{
echo $char;
}
//
fclose($fd);
?>

= , while() , fgetc() FALSE. !==, . . != ,


, FALSE (, 0).
, 4.11,
,
. feof(),
TRUE, , TRUE . 4.12 4.11, feof().

212

4.12. feof()
<?php
//
$fd = fopen("text.txt", "r");
if (!$fd) exit(" text.txt");
// ,
while(!feof($fd))
{
$char = fgetc($fd);
echo $char;
}
//
fclose($fd);
?>

fopen()
(. . 4.2). 4.11
4.12 , r, r+, w+, a+ x+, w, a x
. , x+
, , w+ , a+
, .
r r+.
.
PHP , , .
fgets(), :
fgets($handle [, $length])

$handler .
$handle 1 ( $handle
1000), .
, FALSE. 4.13 fgets() text.txt.
4.13. fgets()
<?php
//
$fd = fopen("text.txt", "r");
if (!$fd) exit(" text.txt");
// ,
while(!feof($fd))

213

{
$str = fgets($fd, 1024);
echo "$str<br>";
}
//
fclose($fd);
?>

fgets(),
. , fread(), . :
fread($handle, $length)

fread() $handle $length. 4.14


fread().
4.14. fread()
<?php
//
$fd = fopen("text.txt", "r");
if (!$fd) exit(" text.txt");
// ,
while(!feof($fd))
{
$str = fread($fd, 1024);
echo "$str<br>";
}
//
fclose($fd);
?>

, fread() ( 4.15).
4.15.
<?php
//
$fd = fopen("text.txt", "r");
if (!$fd) exit(" text.txt");
//
$str = fread($fd, filesize($fd));
echo $str;

214

//
fclose($fd);
?>

4.15
filesize().
fread() , .
: , 4 096 ( 4.16).
4.16.
<?php
//
$fd = fopen("http://www.softtime.ru", "r");
if (!$fd) exit(" ");
// ,
$str = "";
while(!feof($fd))
{
$str .= fread($fd, 4096);
}
//
echo $str;
//
fclose($fd);
?>

4.15 4.16
. ,
PHP file_get_contents(),
:
file_get_contents($filename [, $flags [,
$context [, $offset [, $maxlen]]]])

$filename
. ,
, ,
fopen().
$flags . . 4.4. , |.
$context HTTP-,
. , NULL. -

215

$offset $maxlen
, .

FILE_TEXT FILE_BINARY .

4.4. $flags file_get_contents()

FILE_USE_INCLUDE_PATH

, include_path php.ini

FILE_TEXT

UTF-8 (
php.ini)

FILE_BINARY

4.17 ,
4.15.

file_get_contents(), ,
. ,
8 16 memory_limit
php.ini. memory_limit
, "Fatal error: Allowed memory size of 8388608 bytes
exhausted" (" : 8 388 608 ").

4.17. file_get_contents()
<?php
$str = file_get_contents("text.txt");
echo $str;
?>

, file_get_contents() . 4.18 .
4.18. file_get_contents()
<?php
$str = file_get_contents("http://www.softtime.ru");
echo $str;
?>

216

file_get_contents() , explode() ( 4.19).


4.19.
<?php
//
$contents = file_get_contents("text.txt");
//
$arr = explode("\n", $contents);
// $arr
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

4.19 $arr,
.
PHP file(),
:
file($filename [, $flags [, $context]])

$filename , .
$flags . 4.5. $context HTTP-, .

FILE_TEXT FILE_BINARY .

4.5. $flags file()

FILE_USE_INCLUDE_PATH

, include_path php.ini

FILE_IGNORE_NEW_LINES

FILE_SKIP_EMPTY_LINES

FILE_TEXT

UTF-8 (
php.ini)

FILE_BINARY

217

4.20 4.19.
4.20. file()
<?php
//
$arr = file ("text.txt", FILE_IGNORE_NEW_LINES |
FILE_SKIP_EMPTY_LINES |
FILE_BINARY);
// $arr
echo "<pre>";
print_r($arr);
echo "</pre>";
?>

4.5.
( fopen()) , r. , w w+, . fwrite(),
:
fwrite($handle, $str [, $length])

$handle $str. $length ,


( ).
,
FALSE. 4.21 , text.txt
"Hello world!".
4.21.
<?php
//
$fd = fopen("text.txt", "w");
if (!$fd) exit(" ");
// "Hello world!"
fwrite($fd, "Hello world!");
//
fclose($fd);
?>

, . 4.2, b t . -

218

,
. 4.2.
- ,
. UNIX-
\n, Windows \r\n, Mac OS \n\r. t UNIX- \n
. b .

Windows Windows- \r\n, UNIX \n ().

b, . .
.

Windows. "Hello\nworld!", UNIX- \n. ( 4.22) 12 .
4.22.
<?php
//
$fd = fopen("text.txt", "wb");
if (!$fd) exit(" ");
//
fwrite($fd, "Hello\nworld!");
//
fclose($fd);
//
$str = file_get_contents("text.txt");
echo strlen($str); // 12
?>

"Hello\nworld!" 13 , . . UNIX- \n \r\n ( 4.23).


4.23.
<?php
//
$fd = fopen("text.txt", "wt");
if (!$fd) exit(" ");
//
fwrite($fd, "Hello\nworld!");

219

//
fclose($fd);
//
$str = file_get_contents("text.txt");
echo strlen($str); // 13
?>

,
file_put_
contents(), :
file_put_contents($filename, $data [, $flags [, $context]])

$filename $data (
, ). $flags
. 4.6. $context
HTTP-, .

FILE_TEXT FILE_BINARY .

4.6. $flags
file_put_contents ()

FILE_USE_INCLUDE_PATH

, include_path php.ini

FILE_APPEND

LOCK_EX

FILE_TEXT

UTF-8 (
php.ini)

FILE_BINARY

4.24 4.19.
4.24. file_put_contents()
<?php
file_put_contents("text.txt", "Hello world!");
?>

220

,
( 4.25).
4.25.
<?php
//
$arr[] = "Hello ";
$arr[] = "world!";
//
file_put_contents("text.txt", $arr);
?>

4.6.
filesize(), . , , , , 4.26.
4.26.
function getfilesize($filename)
{
// ,
if (!file_exists($filename)) return " ";
//
$filesize = filesize($filename);
// 1024 ,
//
if ($filesize > 1024)
{
$filesize = (float)($filesize/1024);
// 1024 ,
//
if ($filesize > 1024)
{
$filesize = (float)($filesize/1024);
//
$filesize = round($filesize, 1);
return $filesize." ";
}
else
{
//
$filesize = round($filesize, 1);

221

return $filesize." ";


}
}
else
{
return $filesize." ";
}
}
?>

4.26, ,
file_exists() .
TRUE, , FALSE . , , filesize(), 1 , 1 .
.

4.7.
site.rar, 10 000 . , , ( 4.27).
4.27.
<?php
//
$filename = "site.rar";
// 10 000
$piece = 10000;
//
$fp = fopen($filename, "r");
//
$bufer = file_get_contents($filename);
//
fclose($fp);
// ,
$count = (int)filesize($filename)/$piece;
if((float)(filesize($filename)/$piece) $count != 0) $count++;
//
// $bufer
for($i=0; $i<$count; ++$i)
{
$part = substr($bufer,$i*$piece,$piece);
//
file_put_contents("site.tm".$i, $part);
}
?>

222

, tmN, N . , 4.28.
4.28.
<?php
$bufer = "";
for($i = 0; $i < 100000; ++$i)
{
//
$filename = "site.tm".$i;
//
if(file_exists($filename))
// ,
// $bufer
$bufer .= file_get_contents($filename);
else
//
//
break;
// $bufer
//
file_put_contents("site_final.rar", $bufer);
}
?>

4.8.


. ,
. . 4.3
Web-,
.
4.29 .
4.29.
<?php
//
error_reporting(E_ALL & ~E_NOTICE);
// ,
//
if(isset($_POST['content']))

223

{
// ,
if(!file_exists($_POST['filename']))
exit(" ");
// , " "
if(get_magic_quotes_gpc())
{
// " "
$_POST['content'] = stripslashes($_POST['content']);
}
//
file_put_contents($_POST['filename'], $_POST['content']);
// $_GET
//
$_GET['filename'] = $_POST['filename'];
}
echo "<form method='get'>".
" ".
"<input type='text' name='filename' ".
"value='".htmlspecialchars($_GET['filename'])."' />";
echo "<input type='submit' value='' />";
echo "</form>";
//
// ,
if(isset($_GET['filename']))
{
// ,
if(!file_exists($_GET['filename']))
exit(" ");
// $bufer
$bufer = file_get_contents($_GET['filename']);
echo "<form method='post'>".
"<textarea cols='50' rows='5' name='content'>".
htmlspecialchars($bufer)."</textarea>".
"<input type='hidden' name='filename' ".
"value='".htmlspecialchars($_GET['filename'])."' />";
echo "<br /><br />";
echo "<input type='submit' value='' />";
echo "</form>";
}
?>

,
filename , GET , .
file_get_contents() $bufer, -

224

. 4.3.

. content filename,
.
,
POST. , ,
$_POST['content'] , .
$_POST $_GET.
, " " ,
get_magic_quotes_gpc(). " " (. . 2.1.9)
, , ,
. 4.29 , , stripslashes().
$_POST['content'] , , " " , ( 4.30).

, 4.30 get_magic_quotes_gpc()
!, . . if ,
" " , 4.31 , . . , " " .

4.30.
<?php
...
// , " "
if(!get_magic_quotes_gpc())

225

{
// " "
$_POST['content'] = addslashes($_POST['content']);
}
//
file_put_contents($_POST['filename'], "$_POST[content]");
...
?>

4.9.
,
, ,
.
,
, , index.php?down=archive.zip. , down, ,
filecount.txt.
.
HTTP-
Location . , 4.31.
4.31.
<?php
//
error_reporting(E_ALL & ~E_NOTICE);
//
$file_name = array('archive1.zip','archive2.zip','archive3.zip');
// ,
$countname = "filecount.txt";
// ,
//
if(file_exists($countname))
{
//
$content = file_get_contents($countname);
//
$count = unserialize($content);
}
// ,
//

226

else
{
// $count
foreach($file_name as $file)
{
$count[$file] = 0;
}
//
file_put_contents($countname, serialize($count));
}
// , down
// GET
if(isset($_GET['down']))
{
// , $_GET['down']
// $file_name
if(in_array($_GET['down'],$file_name))
{
//
//
// $_GET['down']
$count[$_GET['down']]++;
//
file_put_contents($countname, serialize($count));
//
header("Location: $_GET[down]");
exit();
}
}
//
foreach($file_name as $file)
{
echo " <a href='$_SERVER[PHP_SELF]?down=$file'>$file</a>
".intval($count[$file])." <br />";
}
?>

$file_name, . . -,
down, , ,
. -,
. $count, , ,

227

serialize() ,
unserialize().

, HTTP-
, PHP
"Warning: Cannot modify header information headers already sent by"
(:
). HTTP: ,
, .
, ,
.

4.31, ,
filecount.txt ,
$file_name. 4.31
. 4.4.

. 4.4.

4.10.

HTML
, , ,
. , . ""
, . . HTTP-,
, ,
cookie . . ,
.
, HTTP-,
4.32.

228

4.32. ,
<?php
$filename = basename($_GET['down']);
header("Content-Disposition: attachment; filename=$filename");
header("Content-type: application/octet-stream");
header("Content-length: ".filesize($_GET['down']));
echo file_get_contents($_GET['down']);
?>

4.32 GET- , ,
index.php?down=filetext.txt. basename()
( , GET- down ). HTTP Content-Disposition , filename. filename
, filename
. HTTP- Content-type , , . HTTP- Content-length .
, $_GET['down'],
file_get_contents().
4.32 . 4.5.

, :
echo, . , ?>.

. 4.5.

229

4.11.

, Web-,
. , , ,
.

file(),
,
.
( 4.33).
4.33.
<?php
echo getlinecount($_GET['name']);
function getlinecount($filename)
{
// ,
if(!file_exists($filename)) return " ";
//
// file(), ,
//
$filearr = file($filename);
//
return count($filearr);
}
?>

, 4.33, ,
,
. ( 4.34).
4.34.
<?php
echo getlinecount($_GET['name']);
function getlinecount($filename)
{
// ,
if(!file_exists($filename)) return " ";
//
$fd = fopen($filename, "r");

230

//
if(!$fd) return " ";
$count = 0;
while(($line = fgets($fd)) !== false) $count++;
//
return $count;
}
?>

getlinecount() ,
.
, , .

4.12.
text.txt ( 4.35), .
4.35. text.txt
PHP
++
Java
Ruby
Python
Perl
JavaScript
Visual Basic
Fortran
Pascal
Assembler
Lisp
Haskell
C#

rand(),
:
rand([$min, $max])

$min $max. $min $max ,


0 RAND_MAX ( 32 768).
, , 4.36.

231

4.36.
<?php
//
$filename = "text.txt";
// count.txt
// $lines
$lines = file($filename);
// $lines
$index = rand(0, count($lines) 1);
// $index
echo $lines[$index];
?>

4.13.

. , .
file(), shuffle() ( 4.37).
4.37.
<?php
//
$filename = "text.txt";
//
$lines = file($filename);
//
shuffle($lines);
//
//
array_walk($lines, 'trim_array');
//
file_put_contents($filename, implode("\r\n", $lines));
function trim_array(&$item, $key)
{
$item = trim($item);
}
?>

array_walk() trim_array() $lines trim(),

232

,
.
4.37 text.txt ,
4.38.
4.38. text.txt
C#
Ruby
Assembler
Haskell
Java
Pascal
JavaScript
Python
Visual Basic
Perl
PHP
C++
Lisp
Fortran


file()
sort() rsort(), ( 4.39).
4.39. text.txt
<?php
//
$filename = "text.txt";
//
$lines = file($filename);
//
sort($lines);
//
//
array_walk($lines, 'trim_array');
//
file_put_contents($filename, implode("\r\n", $lines));
function trim_array(&$item, $key)
{
$item = trim($item);
}
?>

233

4.14.
,
. .
, , ,
(. 4.7).
4.7.

mkdir($pathname [, $mode [,
$recursive [, $context]]])

$pathname $mode.
$recursive
TRUE, $pathname . $context , .
TRUE, FALSE

rmdir($dirname [, $context])

$dirname.
TRUE,
FALSE

getcwd()

chdir ($directory)

,
$directory.
TRUE, FALSE

chroot($directory)

$directory.
TRUE,
FALSE

opendir($path [, $context])

"" , $path

readdir($dir_handle)


.
.

$dir_handle , opendir(). , FALSE

closedir($dir_handle)

$dir_handle, closedir()

rewinddir($dir_handle)

$dir_handle

scandir($directory [,
$sorting_order [, $context]])

$directory
FALSE, $directory .
, $sorting_order TRUE,

glob($pattern [, $flags])

,
$pattern.
$flags

234

,
, .
PHP Web- Apache
, .
getcwd() ( 4.40).
4.40. getcwd()
<?php
//
echo getcwd();
?>

chdir() ( 4.41).
cron- ,
, .
4.41. chdir()
<?php
//
chdir("/var/www/html/test/");
?>

4.42 mkdir()
new. mkdir() ,
.
4.42. mkdir()
<?php
if (mkdir("new", 0700)) echo " ";
else echo " ";
?>

4.15.

, , , ( 4.43).

235

4.43.
<?hp
//
$dir = opendir(".");
//
while (($file = readdir($dir)) !== FALSE) echo "$file<br>";
//
closedir($dir);
?>


$file = readdir($dir) FALSE, , , readdir() FALSE, .
opendir() readdir()
scandir(), :
scandir($directory [, $sorting_order [, $context]])

$directory FALSE,
$directory .
, $sorting_order TRUE,
.
4.44 , .
4.44. scandir()
<?php
$dir = 'dir';
//
$files = scandir($dir);
//
$sort_files = scandir($dir, 1);
//
echo "<pre>";
print_r($files);
print_r(sort_files);
echo "</pre>";
?>

4.44 :
Array
(
[0] => array.php

236
[1] => file.txt
[2] => somedir
)
Array
(
[0] => somedir
[1] => file.txt
[2] => array.php
)


glob(), :
glob($pattern [, $flags])

,
$pattern. $flags
. 4.8, .
4.8. $flags glob()

GLOB_MARK

/ UNIX- \ Windows ,

GLOB_NOSORT

GLOB_NOCHECK

GLOB_NOESCAPE

, *,? $.
. GLOB_NOCHECK

GLOB_BRACE

,
{*.html,*.htm,*.php} , html, htm php

GLOB_ONLYDIR

GLOB_ERR

. GLOB_ERR

4.45 glob().
4.45. glob()
<?php
// HTML- PHP-
$arr = glob("{*.html,*.htm,*.php}", GLOB_BRACE | GLOB_MARK);

237

//
if (is_array($arr))
{
foreach ($arr as $filename)
echo "$filename (".filesize($filename)." )<br>";
}
?>

( 4.46). scan_dir(), , . ,
, .
4.46.
<?php
//////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////
function scan_dir($dirname)
{
//
$dir = opendir($dirname);
//
while (($file = readdir($dir)) !== false)
{
// ,
// $file
if($file != "." && $file != "..")
{
echo "$dirname/$file<br>";
// ,
// scan_dir
if(is_dir("$dirname/$file"))
{
scan_dir("$dirname/$file");
}
}
}
//
closedir($dir);
}
//
$dirname = ".";

238
// ,
//
scan_dir($dirname);
?>

, , .

4.16.
,
.
(. 4.6).

. 4.6.

.
,
.
file_count() ( 4.47).
4.47.
<?php
//////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////
function scan_dir($dirname)


{
//
$dir = opendir($dirname);
//
while (($file = readdir($dir)) !== false)
{
// ,
// $file
if($file != "." && $file != "..")
{
// ,
// scan_dir
if(is_dir("$dirname/$file"))
{
echo "$dirname/$file ".
file_count("$dirname/$file")."<br>";
scan_dir("$dirname/$file");
}
}
}
//
closedir($dir);
}
//////////////////////////////////////////////////////////
// ,
//////////////////////////////////////////////////////////
function file_count($dirname)
{
//
$count = 0;
//
$dir = opendir($dirname);
//
while(($file = readdir($dir)))
{
//
if(is_file("$dirname/$file")) ++$count;
}
//
closedir($dir);
return $count;
}
//
$dirname = "scripts";
// ,
//
scan_dir($dirname);
?>

239

240

4.17.


( 4.48).
4.48.
<?php
// home home2
lowering("home","home2");
//////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////
function lowering($dirname,$dirdestination)
{
//
$dir = opendir($dirname);
//
while (($file = readdir($dir)) !== false)
{
echo $file."<br>";
if(is_file("$dirname/$file"))
{
copy("$dirname/$file.", "$dirdestination/$file");
}
//
if(is_dir("$dirname/$file") &&
$file != "." &&
$file != "..")
{
//
if(!mkdir($dirdestination."/".$file))
{
echo " $dirdestination/$file";
}
// lowering
lowering("$dirname/$file", "$dirdestination/$file");
}
}
//
closedir($dir);
}
?>

241

4.18.

, rmdir() ( 4.49).
4.49. rmdir()
<?php
if (rmdir("c:/temp/test")) echo(" ");
else echo(" ");
?>

, FALSE. , . opendir(), readdir().


4.50.
4.50.
<?php
//
//
function full_del_dir($directory)
{
//
$dir = opendir($directory);
//
while(($file = readdir($dir)) !== FALSE)
{
// readdir()
if (is_file("$directory/$file")) unlink("$directory/$file");
// readdir() ,
//
// full_del_dir()
else if (is_dir("$directory/$file") &&
$file != "." &&
$file != "..")
{
full_del_dir("$directory/$file");
}
}
closedir($dir);
rmdir($directory);

242

echo(" ");
}
// temp
full_del_dir("temp");
?>

4.19. ,

,
filesize() ,
.
$size, size_dir() ( 4.51).
4.51. ,
<?php
//
//
function size_dir($directory, $size = 0)
{
$dir = opendir($directory);
while(($file = readdir($dir)))
{
// readdir()
if(is_file("$directory/$file"))
{
$size += filesize("$directory/$file");
}
// readdir()
//
// full_del_dir()
else if (is_dir("$directory/$file") &&
$file != "." &&
$file != "..")
{
size_dir("$directory/$file", $size);
}
}
closedir($dir);
return $size;
}
//
echo size_dir(".");
?>


PHP Web-.
, .
PHP
.

5.1.
PHP ,
, . 5.1
, http://site.dev/
image.jpg image/image.jpg.
5.1. ( 1)
<?php
$content = file_get_contents("http://site.dev/image.jpg");
file_put_contents("image/image.jpg", $contents);
?>

5.1, file_get_
contents() $content,
file_put_contents() .
, copy(),
, ( 5.2).

UNIX-
,
image.

244
5.2. ( 2)
<?php
copy("http://site.dev/image.jpg", "image.jpg");
?>

5.2.
, . . ,
HTTP-. .
(. . ).
, . 5.1,
.

, .
UNIX- , ,
.

fsockopen(),
:
fsockopen($target, $port [, $errno [, $errstr [, $timeout]]])

$target , $port
. ,
FALSE.
$errno $errstr,
. , $timeout
-, . , FALSE.

fsockopen() PHP-,
php.ini php_sockets.dll, ( ;)
extension.

fsockopen() 5.3,
http://www.php.net.
5.3. fsockopen()
<?php
function get_content($hostname, $path)
{
$line = "";

245

// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$headers = "GET $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers);
//
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}
fclose($fp);
}
return $line;
}
$hostname = "www.php.net";
$path = "/";
// .
// ,
set_time_limit(180);
//
echo get_content($hostname, $path);
?>


HTTP-, .
fsockopen() get_content(), : $hostname
, , $path .

, fsockopen() http://, 80.
,
fsockopen(), .

$headers
HTTP- GET.
( 5.4).

246
5.4. , www.php.net
GET / HTTP/1.1\r\n
Host: www.php.net\r\n
Connection: Close\r\n\r\n

fgets()
1 024 , , feof(). .
5.4
(/) GET HTTP/1.1. HTTP- Host
, HTTP- , ( , IP- ). HTTP- Connection .

/ , , /downloads.php,
. HTTP-, GET.

http://www.php.net/. 5.3 . 5.1.

. 5.1. www.php.net

247

HTTP-,
, ,
. HTTP- strstr(),
( ),
( ) ( 5.5).
5.5. HTTP-
<?php
...
$hostname = "www.php.net";
$path = "/";
// .
// ,
set_time_limit(180);
//
$content = get_content($hostname, $path);
echo strstr($content, '<');
?>

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

. 5.2. "" HTTP-

248

5.3. HTTP-
. 5.2 HTTP-,
, : HTTP-. , .

, .

5.3 HTTP- ( 5.6). HTTP-


HTTP- . ,
,
.
5.6. HTTP-
<?php
// HTTP-
function get_content($hostname, $path)
{
$line = "";
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$headers = "GET $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers);
$end = $false;
//
while (!$end)
{
$line = fgets($fp, 1024);
if (trim($line) == "") $end = true;
else $out[] = $line;
}
fclose($fp);
}

249

return $out;
}
$hostname = "www.php.net";
$path = "/";
// .
// ,
set_time_limit(180);
//
$out = get_content($hostname, $path);
//
echo "<pre>";
print_r($out);
echo "</pre>";
?>

:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Date: Sun, 05 Jun 2011 07:19:00 GMT
[2] => Server: Apache/1.3.41 (Unix) PHP/5.2.12RC4-dev
[3] => X-Powered-By: PHP/5.2.12RC4-dev
[4] => Content-language: en
[5] => Set-Cookie: COUNTRY=RUS%2C83.149.47.252; expires=Sun, 12-Jun-2011
07:19:00 GMT; path=/; domain=.php.net
[6] => Last-Modified: Sun, 05 Jun 2011 11:00:27 GMT
[7] => Connection: close
[8] => Transfer-Encoding: chunked
[9] => Content-Type: text/html;charset=utf-8
)

,
( 200). ,
404 (HTTP/1.1 404 Not Found).
Date .
Server Web-. ,
http://www.php.net UNIX,
Web- Apache 1.3.41, PHP 5.2.12.
X-Powered-By , PHP 5.2.12.

HTTP-, X-, , , , ,
, . .

Last-Modified ; , .

250

Content-language ,
.
Set-Cookie cookie COUNTRY
"RUS,83.149.47.252", IP-
.php.net.
downloads http://www.php.net, .
Connection .
Transfer-Encoding ( chuncked) , .
Content-Type (text/html)
(charset=utf-8).
5.6 GET,
HTTP HEAD. ,
5.6 ( 5.7).
5.7. HEAD
<?php
// HTTP-
function get_content($hostname, $path)
{
$line = "";
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$headers = "HEAD $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers);
//
while (!feof($fp))
{
$out[] = fgets($fp, 1024);
}
fclose($fp);
}

251

return $out;
}
$hostname = "www.php.net";
$path = "/";
// .
// ,
set_time_limit(180);
//
$out = get_content($hostname, $path);
//
echo "<pre>";
print_r($out);
echo "</pre>";
?>

, 5.6 5.7 HTTP- Transfer-Encoding, . .


HTTP- .

HEAD HTTP-, GET, .

, PHP get_headers(),
HTTP- ,
HTTP- HEAD.
, true, ,
( 5.8).
5.8. HTTP- get_headers()
<?php
$out = get_headers("http://www.php.net", true);
echo "<pre>";
print_r($out);
echo "</pre>";
?>

5.8 :
Array
(
[0] => HTTP/1.1 200 OK
[Date] => Sun, 05 Jun 2011 08:06:52 GMT
[Server] => Apache/1.3.41 (Unix) PHP/5.2.12RC4-dev
[X-Powered-By] => PHP/5.2.12RC4-dev
[Content-language] => en

252

[Set-Cookie] => COUNTRY=RUS%2C83.149.47.252; expires=Sun, 12-Jun-2011 08:06:52


GMT; path=/; domain=.php.net
[Last-Modified] => Sun, 05 Jun 2011 11:00:27 GMT
[Connection] => close
[Content-Type] => text/html;charset=utf-8
)

5.4.

. get_content(),
HTTP- Content-Length ( 5.9).
5.9.
<?php
// HTTP-
$hostname = "http://www.softtime.ru/files/configs.zip";
$out = get_headers($hostname, true);
foreach($out as $header => $value)
{
if($header === "Content-Length")
{
echo " $value";
}
}
?>

:
26421

5.5. CURL
, , PHP CURL (Client URL Library). 5.10
,
CURL.

CURL PHP-, php.ini php_curl.dll,
( ;) c extension. ssleay32.dll libeay32.dll , PHP, ,
PATH, , C:\Windows\system32.

CURL HTTP-, , . . . CURL


HTTP-, ,

253

curl_setopt() CURLOPT_HEADER
(. . 5.1).
5.10. CURL
<?php
//
$curl = curl_init("http://www.php.net");
//
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//
$content = curl_exec($curl);
// CURL-
curl_close($curl);
//
echo $content;
?>

curl_init() . fsockopen(), , http://, . . CURL (HTTP, HTTPS, FTP).


, curl_init() ,
.
curl_setopt()
:
curl_setopt($curl, $option, $value)

$curl $option
$value. $option , . 5.15.5. ,
TRUE.
curl_exec(). 5.10 $content (
CURLOPT_RETURNTRANSFER,
curl_setopt()).
curl_exec() CURL-.
5.1. CURL-

CURLOPT_AUTOREFERER

HTTP- Location,
HTTP- Referer

254

5.1 ()

CURLOPT_COOKIESESSION

CURL cookie ( )

CURLOPT_CRLF

UNIX- \n
\r\n

CURLOPT_DNS_USE_GLOBAL_CACHE

DNS-

CURLOPT_FAILONERROR

HTTP- 300

CURLOPT_FILETIME

CURL

CURLOPT_FOLLOWLOCATION

URL (
Location)

CURLOPT_FORBID_REUSE

CURL-
curl_exec();

CURLOPT_FRESH_CONNECT

curl_exec() CURL ,

CURLOPT_FTPAPPEND

FTP ,

CURLOPT_FTPASCII

FTP- ,
(ASCII)

CURLOPT_FTPLISTONLY

TRUE
FTP-

CURLOPT_HEADER

HTTP-

CURLOPT_HTTPPROXYTUNNEL

TRUE -

CURLOPT_MUTE

TRUE CURL

CURLOPT_NETRC

TRUE

~/netrc ( ~ )

CURLOPT_NOBODY

.
, HTTP-

CURLOPT_NOPROGRESS

TRUE
( )

CURLOPT_POST

POST- application/x-www-formurlencoded

CURLOPT_PUT

TRUE
PUT HTTP. CURLOPT_INFILE CURLOPT_INFILESIZE.
, PUT

CURLOPT_RETURNTRANSFER

TRUE CURL ,

255
5.1 ()

CURLOPT_SSL_VERIFYPEER

FALSE
.
CURLOPT_CAINFO. CURLOPT_CAPATH.
CURLOPT_SSL_VERIFYPEER 0, , 1 0 CURLOPT_SSL_VERIFYHOST
( 2)

CURLOPT_UNRESTRICTED_AUTH

TRUE
HTTP Location,

CURLOPT_UPLOAD

TRUE

CURLOPT_VERBOSE

TRUE

5.2. CURL-

CURLOPT_BUFFERSIZE

CURLOPT_CONNECTTIMEOUT

.
0

CURLOPT_DNS_CACHE_TIMEOUT

,
DNS-. 120 (2 )

CURLOPT_HTTP_VERSION

HTTP-; :
CURL_HTTP_VERSION_NONE ( ),
CURL_HTTP_VERSION_1_0 ( HTTP 1.0),
CURL_HTTP_VERSION_1_1 ( HTTP 1.1)

CURLOPT_HTTPAUTH

() HTTP-; :
CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE,
CURLAUTH_NTLM, CURLAUTH_ANY CURLAUTH_ANYSAFE

CURLOPT_INFILESIZE

CURLOPT_LOW_SPEED_LIMIT

. ,
CURLOPT_LOW_SPEED_TIME, ,

CURLOPT_LOW_SPEED_TIME

,
CURLOPT_LOW_SPEED_LIMIT,

CURLOPT_MAXCONNECTS

CURLOPT_MAXREDIRS

Location.
CURLOPT_FOLLOWLOCATION

256

5.2 ()

CURLOPT_PORT

CURLOPT_PROXYAUTH

() -;
, CURLOPT_HTTPAUTH

CURLOPT_PROXYPORT

-;
CURLOPT_PROXY

CURLOPT_PROXYTYPE

-:
HTTP- (CURLPROXY_HTTP)
(CURLPROXY_SOCKS5)

CURLOPT_RESUME_FROM

CURLOPT_SSL_VERIFYHOST

,
( SSL-): 1 ; 2 ,

CURLOPT_SSLVERSION

SSL; 2 3.
SSL ,

CURLOPT_TIMECONDITION

CURLOPT_TIMEVALUE.
: TIMECOND_IFMODSINCE
TIMECOND_ISUNMODSINCE.
HTTP

CURLOPT_TIMEOUT

CURLOPT_TIMEVALUE

, 1 1970 .
CURLOPT_TIMECONDITION ( TIMECOND_IFMODSINCE)

5.3. CURL-

CURLOPT_CAINFO

, ,
.
CURLOPT_SSL_VERIFYPEER

CURLOPT_CAPATH

. CURLOPT_SSL_VERIFYPEER

CURLOPT_COOKIE

HTTP- Cookie.
cookie
curl_setopt()

CURLOPT_COOKIEFILE

, cookie.
Netscape, HTTP-

CURLOPT_COOKIEJAR

, cookie,

257
5.3 ()

CURLOPT_CUSTOMREQUEST

, HTTP- GET
HEAD. DELETE , . GET,
POST . .

CURLOPT_ENCODING

HTTP- Accept-Encoding,
HTTP-. : identity, deflate,
gzip

CURLOPT_FTPPORT

IP- PORT FTP. : IP-, , (


UNIX), IP-

CURLOPT_INTERFACE

.
, IP-

CURLOPT_KRB4LEVEL

KRB4 (Kerberos 4) FTP. ( ): clear, safe, confidential, private. , private.


NULL KRB4

CURLOPT_POSTFIELDS

POST-

CURLOPT_PROXY

-,

CURLOPT_PROXYUSERPWD

- HTTP
[username]:[password]

CURLOPT_RANDOM_FILE

,
SSL

CURLOPT_RANGE

"X-Y"
( X Y ). , : "X-". HTTP ,
"X-Y,N-M"

CURLOPT_REFERER

HTTP- Referer

CURLOPT_SSL_CIPHER_LIST

, SSL, : RC4-SHA, TLSv1

CURLOPT_SSLCERT

SSL- PEM

CURLOPT_SSLCERTPASSWD

SSL-,
CURLOPT_SSLCERT

CURLOPT_SSLCERTTYPE

. : PEM
( ), DER ENG

CURLOPT_SSLKEY

, SSL-

CURLOPT_SSLKEYPASSWD

,
SSL-

CURLOPT_SSLKEYTYPE

SSL-. :
PEM ( ), DER ENG

CURLOPT_URL

URL, .

curl_init()

258

5.3 ()

CURLOPT_USERAGENT

HTTP- User-Agent.

CURLOPT_USERPWD


[username]:[password]

5.4. CURL-,

CURLOPT_HTTP200ALIASES

HTTP- 200 (
)

CURLOPT_HTTPHEADER

HTTP-

CURLOPT_POSTQUOTE

FTP-,

CURLOPT_QUOTE

FTP-,

5.5. CURL-,
, fopen()

CURLOPT_FILE

CURLOPT_INFILE

CURLOPT_WRITEHEADER

HTTP-

CURLOPT_STDERR

CURLOPT_RETURNTRANSFER, CURLOPT_FILE
CURLOPT_WRITEHEADER, curl_exec() . , 5.10 , ( 5.11).
5.11.
<?php
//
$curl = curl_init("http://www.php.net");
//
echo curl_exec($curl);
// CURL-
curl_close($curl);
?>

259

HTTP- CURL
, 5.12.
5.12. CURL
<?php
function get_content($hostname)
{
//
$curl = curl_init($hostname);
//
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// HTTP-
curl_setopt($curl, CURLOPT_HEADER, 1);
// HTTP-
curl_setopt($curl, CURLOPT_NOBODY, 1);
// HTTP-
$content = curl_exec($curl);
// CURL-
curl_close($curl);
// $content
return explode("\r\n", $content);
}
$hostname = "http://www.php.net";
$out = get_content($hostname);
echo "<pre>";
print_r($out);
echo "</pre>";
?>

curl_setopt()
CURLOPT_HEADER CURLOPT_NOBODY,
HTTP-, HTTP-.

5.6.
: , , (
). ,
, ,

260

13 ( ). 5.13
wwv.nist.gov.
5.13.
<?php
$fp = fsockopen("wwv.nist.gov",
13,
$errno,
$errstr,
5);
if (!$fp) exit("ERROR: $errno $errstr");
else echo fread($fp, 26);
fclose($fp);
?>

5.13 :
55717 11-06-05 10:17:45 5

5.7. Yandex
Yandex, GET- text http://www.yandex.ru/
yandsearch. , " PHP" (
urlendode()):
http://www.yandex.ru/yandsearch?text=%D4%EE%F0%F3%EC+PHP

5.14 , Yandex .
,
: url name .
5.14. (Yandex)
<?php
// Yandex
function yandex($url)
{
//
$result = array();
//
$contents = file_get_contents($url);
//
$pattern =
"|<a.*?tabindex=\"[\d]+\"(.*?)href=\"([^\"]+)\"[^>]+>(.*?)</a>|is";

261

//
preg_match_all($pattern, $contents, $out, PREG_PATTERN_ORDER);
//
for($i = 0; $i < count($out[2]); $i++)
{
$result[$i]['url'] = $out[2][$i];
$result[$i]['name'] = $out[3][$i];
}
return $result;
}
//
$url = "http://www.yandex.ru/yandsearch?text=%D4%EE%F0%F3%EC+PHP";
//
$arr = yandex($url);
echo "<pre>";
print_r($arr);
echo "<pre>";
?>

,
, tabindex.

5.8. Google
Yandex, GET- q http://www.google.ru/
search. " PHP" :
http://www.google.ru/search?q=%D4%EE%F0%F3%EC+PHP&complete=1&hl=ru&sa=N

5.15 , Google :
(url name ).
5.15. (Google)
<?php
// Google
function google($url)
{
//
$result = array();
//
$contents = file_get_contents($url);
//
$pattern =
'|<h3 class="r"><a href=\"([^\"]+)\"[^>]*>(.+)</a>|isU';

262
//
preg_match_all($pattern, $contents, $out, PREG_PATTERN_ORDER);
//
for($i = 0; $i < count($out[1]); $i++)
{
$result[$i]['url'] = $out[1][$i];
$result[$i]['name'] = $out[2][$i];
}
return $result;
}
//
$url = "http://www.google.ru/search?q=".urlencode(" PHP").
"&complete=1&hl=ru&sa=N";
//
$arr = google($url);
echo "<pre>";
print_r($arr);
echo "<pre>";
?>

5.9.

HTML-, RSS-. , , XML-, , . .
XML- , HTML-. XML-,
,
HTML-.

. http://
www.cbr.ru/currency_base/D_print.asp?date_req=$date, $date //, : http://www.cbr.ru/
currency_base/D_print.asp?date_req=01/06/2011.

,
http://www.cbr.ru/scripts/Root.asp?Prtid=SXML.

HTML-, XML-
http://www.cbr.ru/scripts/XML_daily.asp?date_req=$date.
XML-, (. 5.3),
, 5.16.

263

. 5.3. 1 2011 .

5.16. XML-
<Valute ID="R01010">
<NumCode>036</NumCode>
<CharCode>AUD</CharCode>
<Nominal>1</Nominal>
<Name> </Name>
<Value>21,4176</Value>
</Valute>

<NumCode> <CharCode> .
<Name> . <Nominal>
<Value> .

<Nominal>, , , 10.

XML- ( 5.17).
5.17. XML-
<?php
// XML-
$url = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=".
date("d/m/Y");
//
$content = file_get_contents($url);

264

//
$pattern = "|<valute
id=\"([^\"]+)\">[\s]*<NumCode>([^<]+)</NumCode>[\s]*<CharCode>([^<]+)</CharCode
>[\s]*<Nominal>([^<]+)</Nominal>[\s]*<Name>([^<]+)</Name>[\s]*<Value>([^<]+)</V
alue>[\s]*</Valute>|is";
preg_match_all($pattern, $content, $out);
echo "<table border=1>";
echo "<tr>
<td>ID</td>
<td> </td>
<td> </td>
<td></td>
<td></td>
<td></td>
</tr>";
for($i = 0; $i < count($out[1]); $i++)
{
echo "<tr>
<td>".$out[1][$i]."</td>
<td>".$out[2][$i]."</td>
<td>".$out[3][$i]."</td>
<td>".$out[4][$i]."</td>
<td>".$out[5][$i]."</td>
<td>".$out[6][$i]."</td>
</tr>";
}
echo "</table>";
?>

XML-, $out.
, . 5.4.
5.18 , , .
5.18.
<?php
// XML-
$url = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=".
date("d/m/Y");
//
$content = file_get_contents($url);
//
$pattern = "|<valute
id=\"([^\"]+)\">[\s]*<NumCode>([^<]+)</NumCode>[\s]*<CharCode>
([^<]+)</CharCode>[\s]*<Nominal>([^<]+)</Nominal>[\s]*<Name>([^<]+)</Name>[\s]*
<Value>([^<]+)</Value>[\s]*</Valute>|is";

265

preg_match_all($pattern, $content, $out);


for($i = 0; $i < count($out[1]); $i++)
{
$out[6][$i] = str_replace(",",".",$out[6][$i]);
if($out[3][$i] == "USD")
echo sprintf(" %3.2f<br>", $out[6][$i]/$out[4][$i]);
if($out[3][$i] == "EUR")
echo sprintf(" %3.2f<br>", $out[6][$i]/$out[4][$i]);
}
?>


str_replace(), , .

. 5.4. 5.17

XML-
, XML-.
XML-
simplexml_load_file(), ,
XML-. 5.19 ,
.
5.19.
<?php
// XML-
$url = "http://www.cbr.ru/scripts/XML_daily.asp?date_req=".
date("d/m/Y");

266

//
$xml = simplexml_load_file($url);
foreach($xml as $index => $value)
{
if($value->CharCode == "USD")
echo sprintf(" %3.2f<br>", $value->Value);
if($value->CharCode == "EUR")
echo sprintf(" %3.2f<br>", $value->Value);
}
?>

5.10. POST
, name
( 5.20).
5.20. HTML-
<form action='handler.php' method='post'>
: <input type='text' name='name'><br>
: <input type='text' name='pass'><br>
<input type='submit' value=''>
</form>

POST handler.php, 5.21.


5.21. handler.php
<?php
echo " $_POST[name] <br>";
echo " $_POST[pass] <br>";
?>

, name pass
HTML-. HTML- POST-,
.
.
POST HTTP-
POST /path HTTP/1.1 Content-Length,
.
POST, GET, ,
, .
GET: = -

267

(&). , HTML- name=, pass=,


:
name=&pass=

, , ,
urlencode().
, POST , 5.22.
5.22. POST
<?php
$hostname = "localhost";
$path = "/puzzles/handler.php";
$line = "";
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$data =
"name=".urlencode("")."&pass=".urlencode("")."\r\n\r\n";
// HTTP-
$headers = "POST $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Content-type: application/x-www-form-urlencoded\r\n";
$headers .= "Content-Length: ".strlen($data)."\r\n\r\n";
// HTTP-
fwrite($fp, $headers.$data);
//
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}
fclose($fp);
}
echo $line;
?>

:
HTTP/1.1 200 OK
Date: Wed, 16 Nov 2005 18:00:44 GMT

268
Server: Apache/1.3.33 (Win32)
X-Powered-By: PHP/5.0.4
Transfer-Encoding: chunked
Content-Type: text/html
22

HTTP-,
HTML-.

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

5.23
CURL.
5.23. POST- CURL
<?php
//
$curl = curl_init("http://localhost/puzzles/5/handler.php");
// POST
curl_setopt($curl, CURLOPT_POST, 1);
// POST-
$data = "name=".urlencode("").
"&pass=".urlencode("")."\r\n\r\n";
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//
curl_exec($curl);
// CURL-
curl_close($curl);
?>

CURL ,
POST, CURLOPT_POST. POST- CURLOPT_POSTFIELDS.

269

5.11.
,

$_SERVER['HTTP_REFERER']. , 1.php
2.php (<a href='2.php'></a>), 2.php
5.24, , . 5.5.
5.24.
<?php
echo " ".$_SERVER['HTTP_REFERER'];
?>

. 5.5.

HTML- ( HTML- ). . HTML- index.php, 5.25.


5.25. HTML-
<table>
<form action='handler.php' method='post'>
<tr>
<td>:</td>
<td><input type='text' name='name'></td>
</tr>
<tr>
<td>:</td>
<td><input type='password' name='pass'></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type='submit' value=''></td>

270

</tr>
</form>
</table>

HTML- HTML handler.php ,


( 5.26).
5.26. HTML-
<?php
// HTML-
$html = "http://".$_SERVER['SERVER_NAME'];
// ,
if (substr($_SERVER['HTTP_REFERER'], 0, strlen($html)) == $html)
{
if ($_POST['name'] == 'admin' && $_POST['pass'] == 'admin')
{
// HTML-
}
}
else
{
echo " ";
}
?>

.
,
Web- .
, :
HTTP- Referer ( 5.27) CURL,
curl_setopt() CURLOPT_REFERER ( 5.28).
5.27.
<?php
$hostname = "localhost";
$path = "/test/handler.php";
$line = "";
// POST (admin),
// (admin), session_id ($SID)
// cookie PHPSESSID
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);


//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// POST-
$data = "name=admin&pass=admin&\r\n\r\n";
// HTTP-
$headers = "POST $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
$headers .= "Content-type: application/x-www-form-urlencoded\r\n";
$headers .= "Content-Length: ".strlen($data)."\r\n";
//
$headers .= "Referer: http://localhost/test/index.php\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers.$data);
//
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}
fclose($fp);
}
echo $line;
?>
5.28. CURL
<?php
//
$curl = curl_init("http://localhost/test/handler.php");
// POST
curl_setopt($curl, CURLOPT_POST, 1);
// POST-
$data = "name=admin&pass=admin&\r\n\r\n";
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//
curl_setopt($curl, CURLOPT_REFERER,
"http://localhost/test/index.php");
//
curl_exec($curl);
// CURL-
curl_close($curl);
?>

271

272

5.12.
PHP-
USER_AGENT : PHP 5.3.
php.ini user_agent
(. . 2.1.11).
$_SERVER['USER_AGENT']. , . . HTTP- User-Agent. HTTP, , . 5.29 , , ,
Windows XP,
Internet Explorer 6.0. HTTP- User-Agent :
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
5.29.
<?php
$hostname = "localhost";
$path = "/test/index.php";
$line = "";
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$headers = "GET $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
// ,
// Windows XP
$headers .= "User-Agent: Mozilla/4.0 ".
"(compatible; MSIE 6.0; Windows NT 5.1)\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers);
//
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}

273

fclose($fp);
}
echo $line;
?>

5.30 CURL. curl_setopt() CURLOPT_USERAGENT HTTP User-Agent.


5.30. CURL
<?php
//
$curl = curl_init("http://localhost/test/handler.php");
//
$useragent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1";
curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
//
curl_exec($curl);
// CURL-
curl_close($curl);
?>

5.13. cookie
cookie , , ,
( cookie)
.
HTTP- Cookie cookie.
HTTP- , cookie
, HTTP- :
Cookie: name1=value1; name2=value2; ...

name1, name2, ... cookie, value1, value2, ... .


, cookie, . cookie name ,
cookie admin, editor user
, ( 5.31).
5.31. cookie
<?php
if (isset($_COOKIE['name']))
{

274
if (isset($_COOKIE['admin']))
{
echo ", $_COOKIE[name] !<br>";
}
if (isset($_COOKIE['editor']))
{
echo ", $_COOKIE[name] !<br>";
}
if (isset($_COOKIE['user']))
{
echo ", $_COOKIE[name] !<br>";
}
}
?>

, ,
5.32.

, . .
.
SID, , , cookie.
, , , (, XSS-),
.

5.32. cookie
<?php
$hostname = "localhost";
$path = "/1.php";
// ,
// $hostname
$fp = fsockopen($hostname, 80, $errno, $errstr, 30);
//
if (!$fp) echo "$errstr ($errno)<br />\n";
else
{
// HTTP-
$headers = "GET $path HTTP/1.1\r\n";
$headers .= "Host: $hostname\r\n";
// cookie
$headers .= "Cookie: name=cheops; admin=1;\r\n";
$headers .= "Connection: Close\r\n\r\n";
// HTTP-
fwrite($fp, $headers);

275

//
$line = "";
while (!feof($fp))
{
$line .= fgets($fp, 1024);
}
fclose($fp);
}
echo $line;
?>

cookie, HTTP-:
Cookie: name=cheops; admin=1;\r\n

cheops cookie admin 1.


. 5.6. HTTP- , , , .

. 5.6.

. 5.7.

276

:
cookie admin editor user. ,
5.32
. HTTP- :
Cookie: name=cheops; admin=1; editor=1; user=1;\r\n

. 5.7.

5.14. IP-

IP-, , DNS- IP-. HTTP 1.1
IP- .
fsockopen(), , PHP
, IP-
(. 5.6). , Whois-,
IP-.
5.6. IP-

heckdnsrr($hostname [, $type])

DNS- $type
$hostname

gethostbyname($hostname)

$hostname IP-

gethostbynamel($hostname)

$hostname IP-

gethostbyaddr($ip_address)

IP- $ip_address

ip2long($ip_address)

IP- $ip_address

long2ip($proper_address)

IP- $proper_address

gethostbyname() , , IP-.
:
gethostbyname($hostname)

5.33
http://www.yandex.ru.

IP-

277

5.33. gethostbyname()
<?php
$hostname = "www.yandex.ru";
$ip_address = gethostbyname($hostname);
echo "IP- $hostname: $ip_address";
?>

, 5.33 :
IP- www.yandex.ru: 93.158.134.203

IP-; . IP-,
, gethostbynamel(),
gethostbyname(). :
gethostbynamel($hostname)

,
DNS . DNS, ,
DNS- .
IP- gethostbynamel()
( 5.34).
5.34. gethostbynamel()
<?php
$hostname = "www.yandex.ru";
$ip_address = gethostbynamel($hostname);
for($i = 0; $i < count($ip_address); $i++)
{
echo "IP- $hostname: {$ip_address[$i]}<br>";
}
?>

, 5.34 :
IP-
IP-
IP-
IP-
IP-
IP-
IP-

www.yandex.ru:
www.yandex.ru:
www.yandex.ru:
www.yandex.ru:
www.yandex.ru:
www.yandex.ru:
www.yandex.ru:

93.158.134.203
213.180.204.3
77.88.21.3
87.250.250.3
87.250.250.203
87.250.251.3
93.158.134.3

278

5.15.
IP-
gethostbyaddr() IP- $ip_address
. :
gethostbyaddr($ip_address)

5.35 gethostbyaddr() .
5.35. gethostbyaddr()
<?php
$ip_address = "127.0.0.1";
$hostname = gethostbyaddr($ip_address);
echo " IP- $ip_address: $hostname";
?>

5.35 :
IP- 127.0.0.1: localhost

5.16. IP-
Whois ,
IP-. IP- 43
Whois-. Whois- IP . whois.arin.net.
Whois- IP-,
ReferralServer,
Whois-, IP-. Whois- whois(),
: Whois- IP-.
,
( 5.36).
5.36.
<center>
<form method='post'>
<input type='text' name='ip' size='35'
value='<?php
if (!empty($_POST['ip'])) echo htmlspecialchars($_POST['ip']);
?>'>
<input type='submit' value=' IP-'>

279

</form>
</center>
<?php
if (!empty($_POST['ip'])) echo whois("whois.arin.net",$_POST['ip']);
function whois($url,$ip)
{
// TCP,
// "whois.arin.net" 43.
// $sock.
$sock = fsockopen($url, 43, $errno, $errstr);
if (!$sock) exit("$errno($errstr)");
else
{
echo $url."<br>";
// $_POST["ip"]
// .
fputs ($sock, $ip."\r\n");
//
$text = "";
while (!feof($sock))
{
$text .= fgets ($sock, 128)."<br>";
}
//
fclose ($sock);
//
$pattern = "|ReferralServer: whois://([^\n<:]+)|i";
preg_match($pattern, $text, $out);
if (!empty($out[1])) return whois($out[1], $ip);
else return $text;
}
}
?>

whois.arin.net,
.
Whois-, . 213.115.162.82,
AB MySQL, ,
. 5.8.
. 5.8, Whois-: whois.arin.net
whois.ripe.net.
IP- 192.131.90.161, http://
www.w3c.org, , . 5.9. , IP- Whois-
whois.apnic.net.

280

. 5.8. IP- 213.115.162.82

. 5.9. IP- 192.131.90.161

281

5.17.
PHP mail(), :
mail($to, $subject, $body [, $headers] [, $parameters])

:
$to ;
$subject ;
$message ;
$headers , ;
$parameters , .

$headers,
.
(text/plain) HTML- (text/html)
.
Content-Type charset .
Content-Type: text/html; charset=UTF-8\r\n


cp1251 UTF-8
windows-1251.

, , , , 5.37.
5.37. mail()
<?php
$theme = " ";
$message = "<html>
<head></head>
<body>
".date("d.m.Y H:i:s")."<br>
".filesize($_SERVER['PHP_SELF'])."
</body>
</html>";
$headers = "Content-Type: text/html; charset=UTF-8\r\n";
if(mail($to, $subject, $message, $headers))
{
echo " ";
}

282

else
{
echo " ";
}
?>

.

From:
From: name <e-mail>

name ,
, e-mail .
$headers
( 5.38).
5.38.
<?php
$headers = "Content-Type: text/html; charset=KOI8-R\r\n";
$headers .= "From: server <someone@somewhere.ru>\r\n\r\n";
?>

, ,
server someone@somewhere.ru.

5.18.
,
.
HTML-, mail_to,
mail_subject, mail_msg
, file , HTML- ( 5.39).
5.39. HTML-
<?php
if(!empty($_POST))
{
// HTML-
include "handler.php";
}
?>

283

<table>
<form enctype='multipart/form-data' method='post'>
<tr>
<td width=50%>To:</td>
<td align='right'>
<input type='text' name='mail_to' maxlength='32'>
</td>
</tr>
<tr>
<td width=50%>Subject:</td>
<td align='right'>
<input type='text' name='mail_subject' maxlength='64'>
</td>
</tr>
<tr>
<td colspan='2'>
:<br><textarea cols='50' rows='8' name='mail_msg'></textarea>
</td>
</tr>
<tr>
<td width='50%'>Photo:</td>
<td align='right'>
<input type='file' name='mail_file' maxlength='64'>
</td>
</tr>
<tr><td colspan='2'><input type='submit' value=''></td></tr>
</form>
</table>

HTML- . 5.10.
handler.php, ( 5.40).
5.40. HTML-
<?php
if(empty($_POST['mail_to'])) exit(" ");
//
$pattern = "/^[0-9a-z_]+@[0-9a-z_^\.]+\.[a-z]{2,6}$/i";
if (!preg_match($pattern, $_POST['mail_to']))
{
exit(" somebody@server.com");
}
$_POST['mail_to'] = htmlspecialchars(stripslashes($_POST['mail_to']));
$_POST['mail_subject'] =
htmlspecialchars(stripslashes($_POST['mail_subject']));

284

$_POST['mail_msg'] =
htmlspecialchars(stripslashes($_POST['mail_msg']));
$picture = "";
//
if (!empty($_FILES['mail_file']['tmp_name']))
{
//
$path = $_FILES['mail_file']['name'];
if (copy($_FILES['mail_file']['tmp_name'], $path)) $picture = $path;
}
$thm = $_POST['mail_subject'];
$msg = $_POST['mail_msg'];
$mail_to = $_POST['mail_to'];
//
if(empty($picture)) mail($mail_to, $thm, $msg);
else send_mail($mail_to, $thm, $msg, $picture);
//
function send_mail($to, $thm, $html, $path)
{
$fp = fopen($path,"r");
if (!$fp)
{
print " $path ";
exit();
}
$file = fread($fp, filesize($path));
fclose($fp);
$boundary = "--".md5(uniqid(time())); //
$headers .= "MIME-Version: 1.0\n";
$headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
$multipart .= "--$boundary\n";
$kod = 'utf-8'; // $kod = 'windows-1251';
$multipart .= "Content-Type: text/html; charset=$kod\n";
$multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
$multipart .= "$html\n\n";
$message_part = "--$boundary\n";
$message_part .= "Content-Type: application/octet-stream\n";
$message_part .= "Content-Transfer-Encoding: base64\n";
$message_part .= "Content-Disposition: attachment; filename =
\"".$path."\"\n\n";
$message_part .= chunk_split(base64_encode($file))."\n";
$multipart .= $message_part."--$boundary--\n";
if(!mail($to, $thm, $multipart, $headers))
{

285

exit(" , ");
}
}
//
@header("Location: ".$_SERVER['PHP_SELF']);
?>

. 5.10. HTML-

,
. , mail().
,
send_mail(). send_mail()
mail(). ,
.

.

5.19.

, HTML, , 5.41.

286
5.41.
<?php
function htmlimgmail($mail_to, $thema, $html, $path)
{
$EOL = "\n";
$boundary
= "--".md5(uniqid(time()));
$headers
= "MIME-Version: 1.0;$EOL";
$headers .= "From: somebody@somewhere.ru$EOL";
$headers
.= "Content-Type: multipart/related; ".
"boundary=\"$boundary\"$EOL";
$multipart
$multipart
$multipart
$multipart
if($EOL ==
$multipart

= "--{$boundary}$EOL";
.= "Content-Type: text/html; charset=koi8-r$EOL";
.= "Content-Transfer-Encoding: 8bit$EOL";
.= $EOL;
"\n") $multipart .= str_replace("\r\n", $EOL, $html);
.= $EOL;

if (!empty($path))
{
for($i = 0; $i < count($path); $i++)
{
$file = file_get_contents($path[$i]);
$name = basename($path[$i]);
$multipart .= "$EOL--$boundary$EOL";
$multipart .= "Content-Type: image/jpeg; name=\"$name\"$EOL";
$multipart .= "Content-Transfer-Encoding: base64$EOL";
$multipart .= "Content-ID: <".md5($name).">$EOL";
$multipart .= $EOL;
$multipart .= chunk_split(base64_encode($file), 76, $EOL);
}
}
$multipart .= "$EOL--$boundary--$EOL";
if(!is_array($mail_to))
{
//
if(!mail($mail_to, $thema, $multipart, $headers))
return False;
else
return True;
exit;
}
else
{
//
foreach($mail_to as $mail)

287

{
mail($mail, $thema, $multipart, $headers);
}
}
}
?>

5.42 htmlimgmail(). $mail_to , ( , ), $thema , HTML-.


. ,
, . . htmlimgmail() . HTML- cid, , Content-ID.
md5().
5.42. htmlimgmail()
<?php
//
$picture[0] = "s_20040815135808.jpg";
$picture[1] = "s_20040815135939.jpg";
$mail_to = "sombody@somewhere.ru";
$thm
= convert_cyr_string(" ", "w", "k");
$html = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML ".
"4.01 Transitional//EN\">
<html>
<head><title> </title></head>
<body><img src='cid:".md5($picture[0])."' border='0'>
<br><br><img src='cid:".md5($picture[1])."' border='0'></body>
</html>";
$html = convert_cyr_string($html, "w", "k");
if(send_mail($mail_to, $thm, $html, $picture))
echo " ".date("d.m.Y H:i");
else
echo " ";
?>

MySQL


.
, , ,
. . , (SQL). ,
. PHP MySQL.
PHP ,
, Oracle, MS SQL, Sybase . .

6.1. SQL
() . , , . , ().
, ,
.

. http://softtime.ru/forum/
index.php?id_forum=3.

,
, SQL (Structured Query Language,
).
, SQL " ",
, -

MySQL

289

. SQL ,
, :
( );
( -

);
(//);
(

, );
( );
.

SQL , (PHP, C++, Pascal . .) . , .


, SQL , : ,
,
. , SQL
, - ,
. ,
,
, .

6.2. ,

MySQL data.
, . ,
, ,
, .
. 6.1 .
6.1.

CREATE DATABASE db;

db

DROP DATABASE db;

db

290

6.1 ()

SHOW DATABASES;

USE db;

db

RENAME DATABASE db TO new;

db new

ALTER DATABASE db;

db


USE SQL,
mysql. PHP- MySQL mysql_select_db().

CREATE DATABASE
DEFAULT CHARACTER SET.

, . 6.1
wet Windows-1251.

, MySQL,
SHOW CHARACTER SET.

6.1. Windows-1251
CREATE DATABASE wet DEFAULT CHARACTER SET cp1251;


,
ALTER DATABASE ( 6.2).
6.2. UTF-8
ALTER DATABASE wet DEFAULT CHARACTER SET utf8;

RENAME DATABASE. 6.3 wet db.


6.3.
RENAME DATABASE wet TO db;

DROP DATABASE.
, , IF EXISTS,

MySQL

291

, ( 6.4).
IF EXISTS , .
6.4.
DROP DATABASE IF EXISTS db;

, CREATE DATABASE
,
IF NOT EXISTS, ,
( 6.5).
6.5.
CREATE DATABASE IF NOT EXISTS wet;

6.3. ,

, .
: ,
db.tbl, tbl.
, USE
mysql_select_db(). , .
. 6.2 .
6.2.

CREATE TABLE tbl;

tbl

DROP TABLE tbl;

tbl

ALTER TABLE tbl;

tbl

RENAME TABLE tbl TO new;

tbl new

DESCRIBE TABLE tbl;

tbl

TRUNCATE TABLE tbl;

tbl

SHOW TABLES;

6.6 tbl,
: id name.

292
6.6.
CREATE TABLE tbl (
id INT,
name TEXT
);

, , . . 6.3 .

.
UNSIGNED.
, , , .

6.3.

TINYINT

128 127, 0 255

SMALLINT

32 768 32 767, 0 65535

MEDIUMINT

8 388 608 8 388 608, 0 16 777 215

INT, INTEGER

2 147 683 648 2 147 683 648, 0 4 294 967 295

BIGINT

263 2631, 0 264

BIT

1 64

BOOL, BOOLEAN

0, 1

DECIMAL, DEC, NUMERIC

, :
, DECIMAL(5,2) 5
, ,
99,99 999,99

FLOAT

1,175494351 1039,
3,402823466 1038

DOUBLE, REAL,

2,2250738585072014 10308,
1,797693134862315 10308

DOUBLE PRECISION

MySQL : TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT.


,
. ,
.
DECIMAL NUMERIC DEC , , . , (FLOAT DOUBLE), DECIMAL , FLOAT DOUBLE.

MySQL

293


MySQL , , INT(11).

, , mysql.

. 6.4 , BLOB-, .
6.4.

CHAR

,
, , CHAR(255)
255 ( 65 535). ,
VARCHAR

VARCHAR

, CHAR,
, ,

TINYBLOB, TINYTEXT

, 255

BLOB, TEXT

, 65 535

MEDIUMBLOB, MEDIUMTEXT

, 2241

LONGBLOB, LONGTEXT

, 2321

ENUM('value1','value2',...)

SET('value1','value2',...)


(. 6.5).
6.5.

DATE

, '1000-01-01'
'9999-12-31'

TIME

, '828:59:59'
'828:59:59'

DATATIME

,
'1000-01-01 00:00:00' '9999-12-31 00:00:00'

TIMESTAMP

,
'1970-01-01 00:00:00' '2038-12-31 59:59:59'. INSERT UPDATE

YEAR

1901 2155 YEAR(4),


1970 2069 YEAR(2)

CREATE TABLE, . ,

294

ENGINE. 6.7 MyISAM-


comments, DEFAULT CHARSET UTF-8.

MySQL ,
InnoDB. , CREATE TABLE , ( defaultstorage-engine my.ini).

6.7.
CREATE TABLE comments (
id_position INT,
name TINYTEXT,
comment TEXT,
putdate DATETIME,
hide ENUM('show','hide')
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

DROP TABLE,
6.8. DROP DATABASE IF EXISTS
.
6.8.
DROP TABLE IF EXISTS comments;

ALTER TABLE, , . 6.9 author


id_position comments.

AFTER id_position ,
.
FIRST.

6.9. comments
ALTER TABLE comments ADD COLUMN author TEXT AFTER id_position;

DESCRIBE,
( 6.10).

MySQL

295

6.10.
DESCRIBE comments;
+-------------+---------------------+------+-----+---------+-------+
| Field
| Type
| Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+-------+
| id_position | int(11)
| NO
|
| NULL
|
|
| author
| text
| NO
|
| NULL
|
|
| name
| tinytext
| NO
|
| NULL
|
|
| comment
| text
| NO
|
| NULL
|
|
| putdate
| datetime
| NO
|
| NULL
|
|
| hide
| enum('show','hide') | NO
|
| NULL
|
|
+-------------+---------------------+------+-----+---------+-------+

DROP COLUMN ( 6.11).


6.11. comments
ALTER TABLE comments DROP COLUMN author;

MODIFY.
6.12 id_position INT BIGING.
6.12.
ALTER TABLE comments MODIFY id_position BIGINT;

CHANGE, . 6.13 id_position


id_comment.
6.13.
ALTER TABLE comments CHANGE id_position id_comment INT;

6.4. .
INSERT
INSERT INTO tbl VALUES().
. CREATE TABLE
.
tbl, , id
5, id_cat NULL ( 6.14).

296
6.14. tbl
CREATE TABLE tbl (
id INT(11) NOT NULL DEFAULT '5',
id_cat INT(11) DEFAULT NULL
);

INSERT, ( 6.15).
6.15. INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO

tbl
tbl
tbl
tbl

VALUES (10, 20);


(id_cat, id) VALUES (10, 20);
(id) VALUES (30);
() VALUES ();

, INSERT
.
SELECT ( 6.16),
. 6.6.
6.16.
SELECT * FROM tbl;
+----+--------+
| id | id_cat |
+----+--------+
| 10 |
20 |
| 20 |
10 |
| 30 |
NULL |
| 5 |
NULL |
+----+--------+

. INSERT comments, 6.7, ( 6.17).


6.17.
INSERT INTO comments
VALUES(1, '', ' ', NOW(), 'show');

MySQL- NOW(),
.

MySQL

297

INSERT ,
VALUES ,
( 6.18).
6.18.
INSERT INTO comments VALUES
(1, '', ' ', NOW(), 'show'),
(2, '', ' ', NOW(), 'show');

6.5.
, ,
. .
MySQL . PRIMARY KEY AUTO_INCREMENT.
NULL
0 ,
, . 6.19 tbl, id name. id
AUTO_INCREMENT.
6.19. AUTO_INCREMENT
CREATE TABLE tbl (
id INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT,
PRIMARY KEY (id)
) DEFAULT CHARSET=cp1251;
INSERT INTO tbl VALUES (NULL, '');
INSERT INTO tbl VALUES (NULL, ' ');
INSERT INTO tbl VALUES (NULL, '');
SELECT * FROM tbl;
+----+-------------------+
| id | name
|
+----+-------------------+
| 1 |
|
| 2 | |
| 3 |
|
+----+-------------------+

,
AUTO_INCREMENT ( -

298


).
MySQL LAST_INSERT_ID(), 6.20.

PHP mysql_insert_id().

6.20.
SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
|
3 |
+------------------+

6.6. . SELECT
SELECT.
6.19. SELECT
*,
, FROM . * . tbl,
6.19, SELECT, ( 6.21).
6.21. SELECT
SELECT id, name FROM tbl;
+----+-------------------+
| id | name
|
+----+-------------------+
| 1 |
|
| 2 | |
| 3 |
|
+----+-------------------+

6.6.1. .
AS
SELECT (
). 6.22 SELECT- id

MySQL

299

100, NOW(),
.
6.22.
SELECT id + 100, name, NOW() FROM tbl;
+----------+-------------------+---------------------+
| id + 100 | name
| NOW()
|
+----------+-------------------+---------------------+
|
101 |
| 2011-06-18 13:26:46 |
|
102 | | 2011-06-18 13:26:46 |
|
103 |
| 2011-06-18 13:26:46 |
+----------+-------------------+---------------------+

SELECT-.
,
. MySQL , AS ( 6.23).
6.23.
SELECT
id + 100 AS id,
name AS catalog,
NOW() AS time
FROM tbl;
+-----+-------------------+---------------------+
| id | catalog
| time
|
+-----+-------------------+---------------------+
| 101 |
| 2011-06-18 13:35:16 |
| 102 | | 2011-06-18 13:35:16 |
| 103 |
| 2011-06-18 13:35:16 |
+-----+-------------------+---------------------+

6.6.2. .
WHERE
, , , ,
. SQL- SELECT
WHERE, . ,
, .
6.24 tbl ,
id 1.

300


SQL PHP,
, " " != SQL <>. () SQL AND (OR).

6.24.
SELECT * FROM tbl
WHERE id > 1;
+----+-------------------+
| id | name
|
+----+-------------------+
| 2 | |
| 3 |
|
+----+-------------------+

,
OR AND. 6.25 id 1 name 15.

name MySQL- LENGTH().

6.25.
SELECT * FROM tbl
WHERE
id > 1 AND
LENGTH(name) < 15;
+----+---------------+
| id | name
|
+----+---------------+
| 3 | |
+----+---------------+

6.6.3. .
ORDER BY
, . ,
, , , .
, , , , ,
, . ,
, -

MySQL

301

. ,
. , ORDER BY. 6.26
tbl name.

ALTER TABLE , ALTER TABLE tbl ORDER BY id.

6.26. ORDER BY
SELECT * FROM tbl
ORDER BY name;
+----+-------------------+
| id | name
|
+----+-------------------+
| 3 |
|
| 2 | |
| 1 |
|
+----+-------------------+

DESC, .

6.6.4.
. ORDER BY
RAND() ( 6.27).
6.27.
SELECT * FROM tbl
ORDER BY RAND();
+----+-------------------+
| id | name
|
+----+-------------------+
| 2 | |
| 3 |
|
| 1 |
|
+----+-------------------+

6.6.5. . LIMIT
.
,

302

. ,
,
. SELECT
LIMIT. 6.28 tbl
.
6.28. LIMIT
SELECT * FROM tbl
ORDER BY id
LIMIT 2;
+----+-------------------+
| id | name
|
+----+-------------------+
| 1 |
|
| 2 | |
+----+-------------------+

LIMIT , ,
. ,
, ( 6.28).
6.29. LIMIT
SELECT * FROM tbl
ORDER BY id
LIMIT 2, 2;
+----+---------------+
| id | name
|
+----+---------------+
| 3 | |
+----+---------------+

6.7. .
UPDATE
. 6.30 name tbl
, id 1.

6.30 WHERE-,
name tbl.

MySQL

303

6.30. UPDATE
UPDATE tbl SET name = '1'
WHERE id = 1;
SELECT * FROM tbl;
+----+-------------------+
| id | name
|
+----+-------------------+
| 1 | 1
|
| 2 | |
| 3 |
|
+----+-------------------+

UPDATE .
SET ( 6.31).

UPDATE c ORDER BY LIMIT .

6.31. UPDATE
UPDATE tbl
SET
name = '',
id = 100
WHERE id = 1;
SELECT * FROM tbl;
+-----+-------------------+
| id | name
|
+-----+-------------------+
| 100 |
|
|
2 | |
|
3 |
|
+-----+-------------------+

6.8. .
DELETE
DELETE. 6.32
3 id .

DELETE c ORDER BY LIMIT .

304
6.32. DELETE
DELETE FROM tbl
WHERE id = 3;
SELECT * FROM tbl;
+-----+-------------------+
| id | name
|
+-----+-------------------+
| 100 |
|
|
2 | |
+-----+-------------------+

MySQL
MySQL , PHP.

7.1.

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

;
TEXT,

.
, . ,
, ENUM SET. .
, ,
, /. id_position,
id_catalog, number :

306
SELECT * FROM tbl
WHERE id_position = 3 AND id_catalog = 2 AND number > 15;
SELECT * FROM tbl
WHERE id_position = 3 AND id_catalog = 2;
SELECT * FROM tbl
WHERE id_position = 3;

, :
SELECT * FROM tbl
WHERE id_catalog = 2 AND number > 15;

, , SELECT-,
INSERT, DELETE UPDATE (
).

PRIMARY KEY, .

. , , PRIMARY KEY, NULL.
PRIMARY KEY .
7.1 tbl,
id.

, ,
.

7.1.
CREATE TABLE tbl (
id INT(11) NOT NULL PRIMARY KEY,
name TINYTEXT NOT NULL
)

, 7.2.
7.2.
CREATE TABLE tbl (
id INT(11) NOT NULL,
name TINYTEXT NOT NULL,
PRIMARY KEY(id)
)

MySQL

307


. , . ,
, . INDEX KEY. , , UNIQUE, . . UNIQUE INDEX UNIQUE KEY.
7.3 CREATE TABLE, tbl, id id_tbl id_cat.
7.3. ,
CREATE TABLE tbl (
id INT(11) NOT NULL AUTO_INCREMENT,
id_tbl INT(11) NOT NULL DEFAULT '0',
id_cat INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (id),
KEY id_tbl (id_tbl),
KEY id_cat (id_cat)
);

, , :
KEY first (id),
KEY second (id_cat)


, .
INDEX KEY.

7.2.
MySQL , . , .
SHOW
CHARACTER SET ( 7.4).

308

7.4.
SHOW CHARACTER SET;
+----------+-----------------------------+---------------------+--------+
| Charset | Description
| Default collation
| Maxlen |
+----------+-----------------------------+---------------------+--------+
| big5
| Big5 Traditional Chinese
| big5_chinese_ci
|
2 |
...
| koi8r
| KOI8-R Relcom Russian
| koi8r_general_ci
|
1 |
...
| utf8
| UTF-8 Unicode
| utf8_general_ci
|
3 |
| cp866
| DOS Russian
| cp866_general_ci
|
1 |
| cp1251
| Windows Cyrillic
| cp1251_general_ci
|
1 |
...
| eucjpms | UJIS for Windows Japanese
| eucjpms_japanese_ci |
3 |
+----------+-----------------------------+---------------------+--------+

,
, , , ,
.
SHOW COLLATION . , LIKE,
cp1251, Windows- ( 7.5).
7.5. , Windows-1251
mysql> SHOW COLLATION LIKE 'cp1251%';
+---------------------+---------+----+---------+----------+---------+
| Collation
| Charset | Id | Default | Compiled | Sortlen |
+---------------------+---------+----+---------+----------+---------+
| cp1251_bulgarian_ci | cp1251 | 14 |
|
|
0 |
| cp1251_ukrainian_ci | cp1251 | 23 |
|
|
0 |
| cp1251_bin
| cp1251 | 50 |
|
|
0 |
| cp1251_general_ci
| cp1251 | 51 | Yes
|
|
0 |
| cp1251_general_cs
| cp1251 | 52 |
|
|
0 |
+---------------------+---------+----+---------+----------+---------+

7.5, cp1251 , :
cp1251_bulgarian_ci ();
cp1251_ukrainian_ci ();
cp1251_bin , ASCII- ;

MySQL

309

cp1251_general_ci ();
cp1251_general_cs ( ).

.
SHOW COLLATION Yes , , (. 7.5). cp1251, ,
cp1251_general_ci. , ( , ) cp1251,
CREATE TABLE, 7.6.
7.6. , cp1251
CREATE TABLE catalogs (
id_catalog INT(11) NOT NULL,
name TINYTEXT NOT NULL
) ENGINE=MyISAM CHARACTER SET cp1251;

,
, 7.7, . . .
7.7. cp1251
CREATE TABLE catalogs (
id_catalog INT(11) NOT NULL,
name TINYTEXT NOT NULL
) ENGINE=MyISAM CHARACTER SET cp1251 COLLATION cp1251_ukrainian_ci;

, ,
latin1
latin1_swedish_ci. , ,
CHARACTER SET
COLLATION, latin1 . , --default-character-set . --default-collation
. 7.8
cp1251 ( ) cp1251_ukrainian_ci ( ).
7.8. MySQL- cp1251
mysqld --default-character-set=cp1251
mysqld --default-character-set=cp1251
--default-collation=cp1251_ukrainian_ci

310

.
my.cnf (my.ini) [mysqld]
( 7.9).
7.9. my.ini
[mysqld]
default-character-set=cp1251
default-collation=cp1251_general_ci

, .
, .

( ).
character_set_client. , , character_set_connection. collation_connection.
character_set_results ,
. ( ) , , 7.10.
7.10.
SET character_set_client='cp1251';
SET character_set_results='cp1251';
SET character_set_connection='cp1251';

, 7.10,
SET NAMES '_' ( 7.11).
7.11. SET NAMES
SET NAMES 'cp1251';

7.3. MySQL
MySQL.

7.3.1. MySQL
MySQL-
VERSION() ( 7.12).

MySQL

311

7.12.
SELECT VERSION();
+------------------+
| VERSION()
|
+------------------+
| 5.1.56-community |
+------------------+

7.3.2.

COUNT() :
COUNT(expr)
COUNT(*)
COUNT(DISTINCT expr1, expr2, ...)

, expr NULL. 7.13 tbl.


7.13. tbl
CREATE TABLE tbl (
id int(11) NOT NULL,
value int(11) default NULL
);
INSERT INTO tbl VALUES (1, 230);
INSERT INTO tbl VALUES (2, NULL);
INSERT INTO tbl VALUES (3, 405);
INSERT INTO tbl VALUES (4, NULL);

7.14 ,
tbl.
7.14. COUNT()
SELECT * FROM tbl;
+----+-------+
| id | value |
+----+-------+
| 1 |
230 |
| 2 | NULL |
| 3 |
405 |
| 4 | NULL |
+----+-------+
SELECT COUNT(id), COUNT(value) FROM tbl;

312
+-----------+--------------+
| COUNT(id) | COUNT(value) |
+-----------+--------------+
|
4 |
2 |
+-----------+--------------+

7.14, id value . , NULL- .


COUNT(*) , , - NULL ( 7.15). , NULL.
7.15. COUNT(*)
SELECT COUNT(*) FROM tbl;
+----------+
| COUNT(*) |
+----------+
|
4 |
+----------+

COUNT(*) , SELECT ,
WHERE.

7.3.3.


MIN() MAX()( 7.16).

7.16 , 7.13.

7.16. MIN() MAX()


SELECT
MIN(id) AS min,
MAX(id) AS max
FROM tbl;
+------+------+
| min | max |
+------+------+
|
1 |
4 |
+------+------+

MySQL

313

MIN() MAX() WHERE . 7.17 tbl id.


7.17. MIN() MAX() WHERE
SELECT * FROM tbl WHERE id = MAX(id);
ERROR 1111: Invalid use of group function


ORDER BY. 7.18
id, .
7.18. MIN() MAX() ORDER BY
SELECT * FROM tbl ORDER BY id LIMIT 1;
+----+-------+
| id | value |
+----+-------+
| 1 | 230
|
+----+-------+
SELECT * FROM tbl ORDER BY id DESC LIMIT 1;
+----+-------+
| id | value |
+----+-------+
| 5 | NULL |
+----+-------+

7.3.4.
SUM() ( 7.19).
7.19.
SELECT SUM(id) FROM tbl;
+---------+
| SUM(id) |
+---------+
|
102 |
+---------+

7.3.5.
DATE_FORMAT(date, format) date
format. format , . 7.1.

314

7.1. DATE_FORMAT()

%a

(SunSat)

%b

(JanDec)

%c

(112)

%D

(1st, 2nd, 3rd . .)

%d

(0131)

%e

(131)

%f

(000000999999)

%H

(0023)

%h

(0112)

%I

(0112)

%i

(0059)

%j

(001366)

%k

(023)

%l

(112)

%M

(JanuaryDecember)

%m

(0112)

%p

AM PM ( 12- )

%r

, 12- (hh:mm:ss AM hh:mm:ss PM)

%S

(0059)

%s

(0059)

%T

, 24- (hh:mm:ss)

%U

(0052),

%u

(0052),

%V

(0153), .
%X

%v

(0153), .
%x

%W

(SundaySaturday)

%w

(06), 0

%X

, ,
, 4 , %V

%x

, ,
, , 4 , %v

%Y

, 4 (YYYY)

%y

, 2 (YY)

%%

, . 7.1, .

MySQL

315


MySQL- '2011-01-12 11:55:17'
'12.01.2011 11:55'. , 7.20.
7.20. DATE_FORMAT()
SELECT DATE_FORMAT(putdatetime,'%d.%m.%Y %H:%i') AS putdatetime FROM tbl;
+------------------+
| putdatetime
|
+------------------+
| 12.01.2011 11:55 |
+------------------+

7.3.6.
tbl,
:
id ;
fio , , ;
putdate .

7.21 CREATE TABLE, tbl.


7.21. tbl
CREATE TABLE tbl (
id INT(11) NOT NULL,
fio TINYTEXT NOT NULL,
putdate DATE NOT NULL
);
INSERT INTO tbl VALUES (1,
INSERT INTO tbl VALUES (2,
INSERT INTO tbl VALUES (3,
INSERT INTO tbl VALUES (4,

' ..', '1972-12-02');


' ..', '1976-06-24');
' ..', '1968-10-24');
' ..', '1986-12-07');

.
TO_DAYS() 365,25 ( 7.22): 365 ;
0,25 ,
.
7.22.
SELECT
fio,
(TO_DAYS(NOW()) TO_DAYS(putdate))/365.25 AS putdate

316
FROM tbl;
+----------------+---------+
| fio
| putdate |
+----------------+---------+
| .. | 38.5462 |
| .. | 34.9870 |
| .. | 42.6530 |
| .. | 24.5339 |
+----------------+---------+

,
FLOOR() ( 7.23).
7.23.
SELECT
fio,
FLOOR((TO_DAYS(NOW()) TO_DAYS(putdate))/365.25) AS putdate
FROM tbl;
+----------------+---------+
| fio
| putdate |
+----------------+---------+
| .. |
38 |
| ..
|
34 |
| ..
|
42 |
| .. |
24 |
+----------------+---------+

7.3.7. IP-
INET_ATON(address) IP- address
( 7.24). XXX.YYY.ZZZ.WWW :
XXX

2563 + YYY

2562 + ZZZ

256 + WWW.


IP-,
BIGINT.

7.24. IP- INET_ATON()


SELECT INET_ATON('62.145.69.10'), INET_ATON('127.0.0.1');
+---------------------------+------------------------+
| INET_ATON('62.145.69.10') | INET_ATON('127.0.0.1') |
+---------------------------+------------------------+
|
1049707786 |
2130706433 |
+---------------------------+------------------------+

MySQL

317

INET_ATON() IP- , 7.25.


7.25. IP-
SELECT INET_ATON('127.0.01'), INET_ATON('127.1');
+-----------------------+--------------------+
| INET_ATON('127.0.01') | INET_ATON('127.1') |
+-----------------------+--------------------+
|
2130706433 |
2130706433 |
+-----------------------+--------------------+

INET_NTOA(address) IP- ( INET_ATON()) ,


, ( 7.26).
7.26. IP- INET_NTOA()
SELECT INET_NTOA(1049707786), INET_NTOA(2130706433);
+-----------------------+-----------------------+
| INET_NTOA(1049707786) | INET_NTOA(2130706433) |
+-----------------------+-----------------------+
| 62.145.69.10
| 127.0.0.1
|
+-----------------------+-----------------------+

7.4.
.
products id_catalog,
catalogs. id_catalog;
, 7.27.
7.27. id_catalog products
SELECT id_catalog FROM products ORDER BY id_catalog;
+------------+
| id_catalog |
+------------+
|
1 |
|
1 |
|
1 |
|
2 |
|
2 |
|
3 |
|
4 |
|
5 |
|
5 |
+------------+

318

7.27, .
, id_catalog.
DISTINCT ( 7.28).
7.28.
SELECT DISTINCT id_catalog FROM products ORDER BY id_catalog;
+------------+
| id_catalog |
+------------+
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
+------------+

7.28, .
GROUP BY, , ( 7.29).

GROUP BY SELECT- ORDER BY
LIMIT.

7.29. GROUP BY
SELECT id_catalog
FROM products
GROUP BY id_catalog
ORDER BY id_catalog;
+------------+
| id_catalog |
+------------+
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
+------------+

7.5.
, . 7.30 catalogs products,
products id_catalog, , . 7.1.

MySQL

319

products

catalogs

id_product

...

id_catalog

id_catalog

name

...

...

...

...

...

...

...

...

...

. 7.1.

7.30. catalogs products


CREATE TABLE catalogs (
id_catalog int(11) NOT NULL auto_increment,
name tinytext NOT NULL,
PRIMARY KEY (id_catalog)
);
INSERT INTO catalogs VALUES (1, ''), (2, ' '),
(3, ''), (4, ' '), (5, ' ');
CREATE TABLE products (
id_product int(11) NOT NULL auto_increment,
name tinytext NOT NULL,
id_catalog int(11) NOT NULL,
PRIMARY KEY (id_product),
KEY id_catalog (id_catalog)
);
INSERT INTO products VALUES (1, ' N 1', 2),
(2, ' N 1', 5), (3, ' N 1', 1),
(4, ' N 2', 1), (5, ' N 3', 1),
(6, ' N 2', 5), (7, ' N 2', 2),
(8, ' N 1', 4), (9, ' N 1', 3);

products, "". , 7.31.

320

7.31.
SELECT * FROM products
WHERE id_catalog = (SELECT id_catalog FROM catalogs
WHERE name = '');
+------------+---------------+------------+
| id_product | name
| id_catalog |
+------------+---------------+------------+
|
3 | N 1 |
1 |
|
4 | N 2 |
1 |
|
5 | N 3 |
1 |
+------------+---------------+------------+

7.31, :
SELECT * FROM products

:
SELECT id_catalog FROM catalogs WHERE name = ''

, (id_catalog),
MySQL ,
. .
,
. 7.32
catalogs,
products.
7.32. ,
SELECT name FROM catalogs
WHERE id_catalog = (SELECT id_catalog FROM products
WHERE id_product = (SELECT MAX(id_product)
FROM products));
+---------------+
| name
|
+---------------+
| |
+---------------+

id_product products:
SELECT MAX(id_product) FROM products

id_catalog,
id_product :
SELECT id_catalog FROM products
WHERE id_product = (SELECT MAX(id_product)
FROM products)

MySQL

321

id_catalog (. 7.32).

,
. . .

, ,
( 7.33).
7.33.
SELECT id_catalog, (SELECT MAX(id_product) FROM products)
FROM catalogs;
+------------+----------------------------------------+
| id_catalog | (SELECT MAX(id_product) FROM products) |
+------------+----------------------------------------+
|
1 |
9 |
|
2 |
9 |
|
3 |
9 |
|
4 |
9 |
|
5 |
9 |
+------------+----------------------------------------+

7.33 SELECT MAX(id_product) FROM products id_product (9) products .


, WHERE, HAVING ON. (=, <>, <, <=, >, >=). , , . 7.34 ,
, , ,
id_product, .
7.34.
SELECT name FROM catalogs
WHERE id_catalog > (SELECT id_catalog FROM products
WHERE id_product = 5);
+--------------------+
| name
|
+--------------------+
| |
|
|
|
|
| |
+--------------------+

322

SELECT name FROM catalogs


WHERE (SELECT id_catalog FROM products
WHERE id_product = 5) < id_catalog;
+--------------------+
| name
|
+--------------------+
|
|
|
|
| |
+--------------------+

7.6. ,

,
. ,
MySQL 1242: " " ( 7.35).
7.35.
SELECT name FROM catalogs
WHERE id_catalog = (SELECT id_catalog FROM products);
ERROR 1242: Subquery returns more than 1 row

, , , LIMIT 1 ( 7.36).
7.36. LIMIT
SELECT name FROM catalogs
WHERE id_catalog = (SELECT id_catalog FROM products LIMIT 1);
+------------+
| name
|
+------------+
| |
+------------+

7.6.1. IN
catalogs,
id_catalog , ,
IN ( 7.36).

MySQL

323

7.36. IN
SELECT name FROM catalogs
WHERE id_catalog IN (SELECT id_catalog FROM products
GROUP BY id_catalog)
ORDER BY name;
+--------------------+
| name
|
+--------------------+
|
|
|
|
| |
| |
|
|
+--------------------+

, 7.36, , 7.37.
7.37. IN

SELECT name FROM catalogs
WHERE id_catalog IN (1,2,3,4,5)
ORDER BY name;
+--------------------+
| name
|
+--------------------+
|
|
|
|
| |
| |
|
|
+--------------------+

, , ,
NOT IN, 7.38.
7.38. NOT IN
SELECT name FROM catalogs
WHERE id_catalog NOT IN (SELECT DISTINCT id_catalog
FROM products WHERE id_catalog < 3)
ORDER BY name;

324

+--------------------+
| name
|
+--------------------+
|
|
|
|
| |
+--------------------+

7.6.2. ANY
IN "" (=). =
( 7.39).
7.39.
SELECT name FROM catalogs
WHERE id_catalog > (SELECT id_catalog FROM products);
ERROR 1242: Subquery returns more than 1 row

, IN . , SQL
. ANY
( 7.40).
7.40. ANY
SELECT id_catalog, name FROM catalogs
WHERE id_catalog > ANY (SELECT id_catalog FROM products);
+------------+--------------------+
| id_catalog | name
|
+------------+--------------------+
|
2 | |
|
3 |
|
|
4 |
|
|
5 | |
+------------+--------------------+

ANY
(=, <>, <, <=, >, >=). id_catalog
,
. 1 (),
. 7.40
id_catalog (1, 2, 3, 4, 5), catalogs,
id_catalog (1, 2, 3, 4, 5) products. id_catalog = 1 :

MySQL
1
1
1
1
1

>
>
>
>
>

1
2
3
4
5

------

0
0
0
0
0

325

()
()
()
()
()

,
:
3
3
3
3
3

>
>
>
>
>

1
2
3
4
5

------

1
1
0
0
0

()
()
()
()
()


"WHERE X > ANY (SELECT Y...)"

" X Y",

"WHERE X < ANY (SELECT Y...)"

" X Y...".

7.6.3. ALL
ANY ALL,
(=, <>,
<, <=, >, >=).
, , , 1 ().

ANY , . . ,
, ALL
.

7.41 , products shop,


.
7.41. ALL
SELECT * FROM catalogs
WHERE id_catalog >= ALL (SELECT id_catalog FROM products
GROUP BY id_catalog);
+------------+--------------------+
| id_catalog | name
|
+------------+--------------------+
|
5 | |
+------------+--------------------+

326

, 7.41,
( 7.42).
7.42.
SELECT id_catalog FROM products GROUP BY id_catalog;
+------------+
| id_catalog |
+------------+
|
1 |
|
2 |
|
3 |
|
4 |
|
5 |
+------------+

ALL 7.41 ,

, 7.42.

7.7. .
HAVING
SQL- HAVING GROUP BY.
( COUNT(), SUM(), MIN(), MAX() .)
, , . 7.43 id_catalog, COUNT() , products
.
7.43. GROUP BY COUNT()
SELECT id_catalog, COUNT(id_catalog)
FROM products
GROUP BY id_catalog
ORDER BY id_catalog;
+------------+-------------------+
| id_catalog | COUNT(id_catalog) |
+------------+-------------------+
|
1 |
3 |
|
2 |
2 |
|
3 |
1 |
|
4 |
1 |
|
5 |
2 |
+------------+-------------------+

MySQL

327

WHERE ( 7.44).
7.44. WHERE GROUP BY
SELECT id_catalog, COUNT(id_catalog)
FROM products
WHERE id_catalog > 2
GROUP BY id_catalog
ORDER BY id_catalog;
+------------+-------------------+
| id_catalog | COUNT(id_catalog) |
+------------+-------------------+
|

3 |

1 |

4 |

1 |

5 |

2 |

+------------+-------------------+


, , ,
. WHERE
.
WHERE HAVING, GROUP BY ( 7.45).
7.45. GROUP BY
SELECT id_catalog, COUNT(id_catalog) AS total
FROM products
GROUP BY id_catalog
HAVING total > 1
ORDER BY id_catalog;
+------------+-------+
| id_catalog | total |
+------------+-------+
|
1 |
3 |
|
2 |
2 |
|
5 |
2 |
+------------+-------+

HAVING ,
.

328

7.8. SELECT
. catalogs products.

FROM JOIN. USING , ,
, ( 7.46).
7.46.
SELECT * FROM catalogs;
+------------+--------------------+
| id_catalog | name
|
+------------+--------------------+
|
1 |
|
|
2 | |
|
3 |
|
|
4 |
|
|
5 | |
+------------+--------------------+
SELECT * FROM products;
+------------+------------------------+------------+
| id_product | name
| id_catalog |
+------------+------------------------+------------+
|
1 | N 1 |
2 |
|
2 | N 1 |
5 |
|
3 | N 1
|
1 |
|
4 | N 2
|
1 |
|
5 | N 3
|
1 |
|
6 | N 2 |
5 |
|
7 | N 2 |
2 |
|
8 | N 1
|
4 |
|
9 | N 1
|
3 |
+------------+------------------------+------------+
SELECT
products.id_product AS id_product,
products.name AS product,
catalogs.name AS catalog
FROM
catalogs JOIN products
USING(id_catalog);

MySQL

329

+------------+------------------------+--------------------+
| id_product | product
| catalog
|
+------------+------------------------+--------------------+
|
1 | N 1 | |
|
2 | N 1 | |
|
3 | N 1
|
|
|
4 | N 2
|
|
|
5 | N 3
|
|
|
6 | N 2 | |
|
7 | N 2 | |
|
8 | N 1
|
|
|
9 | N 1
|
|
+------------+------------------------+--------------------+

, , , USING
ON ( 7.47).
7.47. ON
SELECT
products.id_product AS id_product,
products.name AS product,
catalogs.name AS catalog
FROM
catalogs JOIN products
ON catalogs.id_catalog = products.id_catalog;

. ,
catalogs
products GROUP BY id_catalog catalogs ( 7.48).
7.48.
SELECT
catalogs.id_catalog AS id_catalog,
catalogs.name AS catalog,
COUNT(products.id_product) AS total
FROM
catalogs JOIN products
USING(id_catalog)
GROUP BY catalogs.id_catalog;
+------------+--------------------+-------+
| id_catalog | catalog
| total |
+------------+--------------------+-------+
|
1 |
|
3 |
|
2 | |
2 |

330

|
3 |
|
1 |
|
4 |
|
1 |
|
5 | |
2 |
+------------+--------------------+-------+

, GROUP_CONCAT(). 7.49
catalogs, id_product products,
.
7.49. GROUP_CONCAT()
SELECT
catalogs.id_catalog AS id_catalog,
catalogs.name AS catalog,
GROUP_CONCAT(id_product ORDER BY id_product SEPARATOR ', ') AS list
FROM
catalogs JOIN products
USING(id_catalog)
GROUP BY catalogs.id_catalog;
+------------+--------------------+---------+
| id_catalog | catalog
| list
|
+------------+--------------------+---------+
|
1 |
| 3, 4, 5 |
|
2 | | 1, 7
|
|
3 |
| 9
|
|
4 |
| 8
|
|
5 | | 2, 6
|
+------------+--------------------+---------+

7.9.
points, value x y axis ( 7.50). x y .
7.50. points
CREATE TABLE points (
value INT(11) NOT NULL,
axis ENUM('x','y') NOT NULL
);
INSERT INTO points VALUES(3, 'x');
INSERT INTO points VALUES(5, 'x');

MySQL
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO

points
points
points
points
points
points
points
points

331

VALUES(4, 'x');
VALUES(1, 'x');
VALUES(10, 'x');
VALUES(8, 'y');
VALUES(1, 'y');
VALUES(4, 'y');
VALUES(9, 'y');
VALUES(2, 'y');

points ,
( 7.51).
7.51.
SELECT a.axis, a.value, b.axis, b.value
FROM
points AS a,
points AS b
WHERE
a.axis = 'x' AND
b.axis = 'y'
ORDER BY RAND()
LIMIT 1;
+------+-------+------+-------+
| axis | value | axis | value |
+------+-------+------+-------+
| x
|
3 | y
|
4 |
+------+-------+------+-------+

7.10. DELETE
DELETE .
FROM .
catalogs , id_catalog
3. , 7.52.

SQL- DELETE ORDER BY LIMIT.

7.52. catalogs
DELETE FROM catalogs WHERE id_catalog > 3;
SELECT * FROM catalogs;

332

+------------+-------------------+
| id_catalog | name
|
+------------+-------------------+
|
1 |
|
|
2 | |
|
3 |
|
+------------+-------------------+

7.52 catalogs " " " " id_catalog,


4 5, . products .
, SQL-, 7.53.
7.53. products
SELECT id_catalog, COUNT(*) FROM products GROUP BY id_catalog;
+------------+----------+
| id_catalog | COUNT(*) |
+------------+----------+
|
1 |
9 |
|
2 |
6 |
|
3 |
4 |
|
4 |
5 |
|
5 |
6 |
+------------+----------+

7.54 products ,
catalogs.
7.54. products
DELETE FROM products USING products, catalogs
WHERE products.id_catalog = catalogs.id_catalog;

, products , FROM. ,
7.55, .
7.55. products catalogs
DELETE FROM products, catalogs USING products, catalogs
WHERE products.id_catalog = catalogs.id_catalog;

,
3, SQL-,
catalogs, products ( 7.56).

MySQL

333

7.56. 3
DELETE products, catalogs FROM products, catalogs
WHERE products.id_catalog = catalogs.id_catalog AND
catalogs.id_catalog > 3;
SELECT * FROM catalogs;
+------------+-------------------+
| id_catalog | name
|
+------------+-------------------+
|
1 |
|
|
2 | |
|
3 |
|
+------------+-------------------+
SELECT id_catalog, COUNT(*) FROM products GROUP BY id_catalog;
+------------+----------+
| id_catalog | COUNT(*) |
+------------+----------+
|
1 |
9 |
|
2 |
6 |
|
3 |
4 |
+------------+----------+

7.56,
.

7.11.
, , ,
.
users,
( 7.57).
7.57. users
CREATE TABLE users (
id_position INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
pass TINYTEXT NOT NULL,
email TINYTEXT NOT NULL,
PRIMARY KEY (id_position)
);
INSERT INTO users VALUES(1, 'cheops', 'pass', 'igor@softtime.ru');
INSERT INTO users VALUES(2, 'makkuz', 'pass', 'kuznetsov@softtime.ru');
INSERT INTO users VALUES(3, 'cheops', 'pass', 'igor@softtime.ru');

334


MAX(), , MySQL, ( 7.58).
7.58.
DELETE FROM users
WHERE users.id_position < (SELECT MAX(snd.id_position)
FROM `users` AS snd
WHERE users.name = snd.name);
ERROR 1093 (HY000): You can't specify target table 'users' for update in FROM
clause


users, ( 7.59).
7.59. users
DELETE fst
FROM
users fst
JOIN
(SELECT name, MAX(id_position) AS id_max
FROM users
GROUP BY name
HAVING COUNT(*) > 1) AS snd
ON
fst.name = snd.name AND
fst.id_position < snd.id_max;
SELECT * FROM users;
+-------------+--------+-------+-----------------------+
| id_position | name
| pass | email
|
+-------------+--------+-------+-----------------------+
|
2 | makkuz | pass | kuznetsov@softtime.ru |
|
3 | cheops | passw | igor@softtime.ru
|
+-------------+--------+-------+-----------------------+

PHP MySQL
PHP MySQL php_mysql,
MySQL, .

8.1.
. 8.1 ,
.
mysql_close(),
.
8.1.

mysql_connect()

mysql_close()

mysql_ping()

MySQL
mysql_connect(), :
mysql_connect ([$server [,
$username [,
$password [,
$new_link [,
$client_flags]]]]])

MySQL,
$server. $username $password, .

336

mysql_connect()
,
. $new_link
TRUE, .
$client_flags :
MYSQL_CLIENT_COMPRESS

;
MYSQL_CLIENT_IGNORE_SPACE SQL-

;
MYSQL_CLIENT_INTERACTIVE interactive_timeout -

, .

. , ,
: server = 'localhost:3306',
username , password .

, FALSE.
8.1 mysql_connect().
8.1. mysql_connect()
<?php
// MySQL
$dblocation = "localhost";
//
$dbuser = "root";
//
$dbpasswd = "";
$dbcnx = @mysql_connect($dblocation, $dbuser, $dbpasswd);
if (!$dbcnx) // 0,
{
exit ("<P> ,
.</P>");
}
else
{
echo "<P> .</P>";
}
?>


, PHP, ,
8.1 mysql_connect() @.

PHP MySQL

337

$dblocation, $dbuser $dbpasswd ,


, , ( , config.php),
PHP-. MySQL.

SET NAMES, 8.2.
.

mysql_query() . 8.3.

8.2. Windows-1251
<?php
mysql_query ("SET NAMES 'cp1251'");
?>

mysql_close(),
:
mysql_close([$link_identifier])


$link_identifier. ,
. TRUE FALSE .
8.3 .
8.3. mysql_close()
<?php
//
$dbcnx = @mysql_connect($dblocation, $dbuser, $dbpasswd);
if (!$dbcnx)
{
//
exit ("<P> ,
.</P>");
}
if (mysql_close($dbcnx)) //
{
echo " ";
}
else
{
echo " ";
}
?>

338

,
mysql_close() , . . .
, -
, , , , PHP-.
, .

8.2.
,
, ( mysql
USE). . mysql_select_db(),
USE SQL-. :
mysql_select_db($database_name [, $link_identifier])


$database_name $link_identifier.
TRUE FALSE . 8.4 $dbname.
8.4. mysql_select_db()
<?php
...
//
if (!@mysql_select_db($dbname, $dbcnx))
{
echo "<P> ,
.</P>";
exit();
}
?>


(config.php), ,
( 8.5),
include_once() require_once(),
MySQL.
8.5. config.php
<?php
// MySQL
$dblocation = "localhost";

PHP MySQL

339

//
$dbname = "test";
//
$dbuser = "root";
//
$dbpasswd = "";
//
$dbcnx = @mysql_connect($dblocation, $dbuser, $dbpasswd);
if (!$dbcnx) {
exit( "<P> ,
.</P>" );
}
//
if (! @mysql_select_db($dbname, $dbcnx) ) {
exit( "<P> ,
.</P>" );
}
@mysql_query("SET NAMES 'cp1251'");
?>

8.3. SQL-
SQL- mysql_query(),
:
mysql_query($query [, $link_identifier])

$query, , $link_identifier ,
mysql_connect().

, , mysql_connect() .


mysql_query() , mysql, . , ,
mysql_query() ,
SQL-.

FALSE
. , . 8.6 , catalogs.

340

8.6. mysql_query()
<?php
//
include "config.php";
// SQL-
$query = "CREATE TABLE catalogs (
id_catalog INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
PRIMARY KEY (id_catalog))";
if (mysql_query($query))
{
echo " ";
}
else
{
exit(" ".mysql_error());
}
?>

8.6 mysql_query() exit(),


, , mysql_erorr().
, mysql_query(), . : mysql_result(), mysql_fetch_
row(), mysql_fetch_assoc(), mysql_fetch_array() mysql_fetch_object().
catalogs, 8.7.
8.7. catalogs
CREATE TABLE catalogs (
id_catalog int(11) NOT NULL auto_increment,
name tinytext NOT NULL,
PRIMARY KEY (id_catalog),
FULLTEXT KEY name (name)
) ENGINE=MyISAM DEFAULT CHARSET=cp1251;
INSERT INTO catalogs VALUES (1,'');
INSERT INTO catalogs VALUES (2,' ');
INSERT INTO catalogs VALUES (3,'');
INSERT INTO catalogs VALUES (4,' ');
INSERT INTO catalogs VALUES (5,' ');

PHP MySQL

341

8.4.
mysql_query() ,
, , . 8.2.
8.2.

mysql_result()

mysql_fetch_row()

mysql_fetch_assoc()

mysql_fetch_array()

mysql_fetch_object()

mysql_result() ,
mysql_query(). . :
mysql_result($result, $row [, $field])

$result , mysql_query(). $row


, . $field . 8.8
catalogs.
8.8. mysql_result()
<?php
//
include "config.php";
// SQL-
$query = "SELECT COUNT(*) FROM catalogs";
// SQL-
$cat = mysql_query($query);
//
if ($cat) echo " ".mysql_result($cat, 0);
else exit(" ".mysql_error());
?>

8.8 . 8.1.

342

. 8.1. 8.8

mysql_fetch_row()
.
.
FALSE. mysql_fetch_row() :
mysql_fetch_row($result)

$result , mysql_query(). , ,
FALSE, .
, FALSE. , mysql_fetch_row(), list(), .
8.9 HTML-, catalogs.
8.9. mysql_fetch_row()
<?php
//
include "config.php";
// SQL-
$query = "SELECT * FROM catalogs";
// SQL-
$cat = mysql_query($query);
// SQL-
if (!$cat) exit(" ".mysql_error());
// ,
echo "<table border='1'>";

PHP MySQL

343

while(list($id_author, $name) = mysql_fetch_row($cat))


{
echo "<tr>
<td>$id_author</td>
<td>$name</td>
</tr>";
}
echo "</table>";
?>

8.9 . 8.2.

. 8.2. 8.9

mysql_fetch_assoc() .
. mysql_fetch_assoc()
:
mysql_fetch_assoc($result)

$result , mysql_query(). , ,
FALSE, . . 8.10
HTML-, catalogs.
8.10. mysql_fetch_assoc()
<?php
//
include "config.php";

344

// SQL-
$query = "SELECT * FROM catalogs";
// SQL-
$cat = mysql_query($query);
// SQL-
if (!$cat) exit(" ".mysql_error());
//
echo "<table border='1'>";
while($catalogs = mysql_fetch_assoc($cat))
{
echo "<tr>
<td>".$catalogs['id_catalog']."</td>
<td>".$catalogs['name']."</td>
</tr>";
}
echo "</table>";
?>

8.10 ,
8.9 (. . 8.2). ,
while $catalogs,
catalogs.
, , , . 8.11 MySQL
VERSION() MySQL.
'VERSION()'.
8.11. mysql_fetch_assoc()
<?php
//
include "config.php";
// SQL-
$query = "SELECT VERSION()";
// SQL-
$ver = mysql_query($query);
// SQL-
if (!$ver) exit(" ".mysql_error());
//
$version = mysql_fetch_assoc($ver);
echo $version['VERSION()'];
?>

, . . .

PHP MySQL

345


AS. 8.11 , 8.12.
8.12. , AS
<?php
//
include "config.php";
// SQL-
$query = "SELECT VERSION() AS ver";
// SQL-
$ver = mysql_query($query);
// SQL-
if (!$ver) exit(" ".mysql_error());
//
$version = mysql_fetch_assoc($ver);
echo $version['ver'];
?>

mysql_fetch_array() . ( )
. . mysql_fetch_array() :
mysql_fetch_array($result [, $result_type])

$result , mysql_query().
:
MYSQL_ASSOC ;
MYSQL_NUM ;
MYSQL_BOTH , , .

MYSQL_BOTH.


mysql_fetch_array(), MYSQL_ASSOC MYSQL_NUM, mysql_fetch_
assoc() mysql_fetch_row() .


, .
MYSQL_BOTH. 8.13
catalogs , mysql_fetch_array().

346


print_r(). <pre> </pre>, , . . .

8.13. mysql_fetch_array()
<?php
//
include "config.php";
// SQL-
$query = "SELECT * FROM catalogs";
// SQL-
$prd = mysql_query($query);
// SQL-
if (!$prd) exit(" ".mysql_error());
//
$product = mysql_fetch_array($prd);
echo "<pre>";
print_r($product);
echo "</pre>";
?>

mysql_fetch_array() mysql_fetch_assoc()
mysql_fetch_row() ( 8.14).
8.14. catalogs
<?php
//
include "config.php";
// SQL-
$query = "SELECT * FROM catalogs";
// SQL-
$cat = mysql_query($query);
// SQL-
if (!$cat) exit(" ".mysql_error());
//
echo "<table border='1'>";
while($catalog = mysql_fetch_array($cat))
{
echo "<tr>
<td>".$catalogs['id_catalog']."</td>

PHP MySQL

347

<td>".$catalogs['name']."</td>
</tr>";
}
echo "</table>";
?>

mysql_fetch_object() ,
.
. mysql_fetch_object() :
mysql_fetch_object($result)

$result , mysql_query(). , , FALSE,


.

, , .

8.15 ,
catalogs id_catalog
name.
8.15. mysql_fetch_object()
<?php
//
include "config.php";
// SQL-
$query = "SELECT * FROM catalogs";
// SQL-
$cat = mysql_query($query);
// SQL-
if (!$cat) exit(" ".mysql_error());
while($catalog = mysql_fetch_object($cat))
{
echo "id_catalog: ".$catalog->id_catalog."<br />";
echo "name: ".$catalog->name."<br />";
}
?>

8.15 . 8.3.

348

. 8.3. 8.15

8.5.
, mysql_query(). mysql_num_rows(), :
mysql_num_rows($result)

$result
, mysql_query().

SELECT. , INSERT, UPDATE, DELETE, mysql_
affected_rows().


mysql_num_fields() .

test, : id_test name ( 8.16).


8.16. test
CREATE TABLE test (
id_test int(11) NOT NULL auto_increment,
name tinytext NOT NULL,
PRIMARY KEY (id_test)
);

PHP MySQL

349

, ( 8.17).
8.17.
<?php
//
include "config.php";
// SQL-
$query = "SELECT name FROM test LIMIT 1";
// SQL-
$tst = mysql_query($query);
// SQL-
if (!$tst) exit(" ".mysql_error());
//
echo mysql_result($tst,0);
?>

8.17 (. 8.4).

. 8.4.

mysql_num_rows() ( 8.18).
8.18. mysql_num_rows()
<?php
//
include "config.php";

350

// SQL-
$query = "SELECT name FROM test LIMIT 1";
// SQL-
$tst = mysql_query($query);
// SQL-
if (!$tst) exit(" ".mysql_error());
// ,
//
if (mysql_num_rows($tst) > 0)
{
echo mysql_result($tst,0);
}
?>

8.6. . SQL-
, . userslist ( 8.19).
8.19. userslist
CREATE TABLE userslist (
id_user INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
pass TINYTEXT NOT NULL,
email TINYTEXT NOT NULL,
url TINYTEXT NOT NULL,
PRIMARY KEY (id_user)
);
INSERT INTO userslist VALUES
(1, 'cheops', '', 'igor@softtime.ru', 'http://www.softtime.ru'),
(2, 'barton', '', 'barton@mail.ru', '');

userslist :
id_user , AUTO_INCREMENT;
name ;
pass ;
email ;
url .

8.20.
:
<a href='user.php?id_user=1'>name</a>

1 userslist, name .

PHP MySQL

351

8.20. (index.php)
<?php
//
require_once("config.php");
//
$query = "SELECT * FROM userslist ORDER BY name";
$usr = mysql_query($query);
if (!$usr) exit(" ".mysql_error());
while($user = mysql_fetch_array($usr))
{
echo "<a href='user.php?id_user=$user[id_user]'>$user[name]</a><br>";
}
?>

user.php . user.php 8.21.


8.21. (user.php)
<?php
//
require_once("config.php");
//
$query = "SELECT * FROM userslist WHERE id_user = $_GET[id_user]";
$usr = mysql_query($query);
if (!$usr) exit(" ".mysql_error());
$user = mysql_fetch_array($usr);
echo " $user[name]<br>";
if (!empty($user['email'])) echo "e-mail $user[email]<br>";
if (!empty($user['url'])) echo "URL $user[url]<br>";
?>

8.21, GET- id_user SQL-


. ,
, ,
, SQL-, SQL-.
SQL-
SELECT * FROM userslist WHERE id_user = 1

. ,
'-%20', (. 8.5),
. . :
SELECT * FROM userslist WHERE id_user = '- '

352

. 8.5.


%20 . ,
URL ,
urlencode().

UNION, , MySQL 4.0,


, ( 8.22).
8.22. UNION
SELECT * FROM userslist WHERE id_user = 1
UNION
SELECT * FROM userslist WHERE id_user = 2

SQL- .
, . URL- :
user.php?id_user=1%20UNION%20SELECT%20*%20FROM%20userslist%20WHERE%20id_
user%20=%202

, -
1 (. 8.6).
8.23 , 1 2.
8.23. , 8.22
1, 'cheops', ******, 'cheops@mail.ru', 'http://www.softtime.ru'
2, 'barton', ******, 'barton@mail.ru', ''

, . . mysql_fetch_array() , ,

PHP MySQL

353

.
UNION, . . . . , ( 8.24). id_user .
, , .

. 8.6. 1

8.24.
SELECT * FROM userslist WHERE id_user = -1
UNION
SELECT * FROM userslist WHERE id_user = 2

URL- SQL- 28.24 ,


:
user.php?id_user=-1%20UNION%20SELECT%20*%20FROM%20userslist%20WHERE%20
id_user%20=%202

SELECT- UNION, 2 (. 8.7).


SELECT- ,
ORDER BY, , .
id_user.
ORDER
BY id_user DESC, UNION ( 8.25).

354

. 8.7. SELECT- UNION

8.25.
SELECT * FROM userslist WHERE id_user = 1
UNION
SELECT * FROM userslist WHERE id_user = 2
ORDER BY id_user DESC

SELECT-,
. *
( 8.26).
8.26. *
SELECT * FROM userslist WHERE id_user = 1
UNION
SELECT id_user, name, pass, email, url FROM userslist WHERE id_user = 2
ORDER BY id_user DESC

SELECT, . name pass


, ( 8.27).
8.27. name pass
SELECT * FROM userslist WHERE id_user = 1
UNION
SELECT id_user, pass, name, email, url FROM userslist WHERE id_user = 2
ORDER BY id_user DESC

, (name) (pass) (. 8.8).

PHP MySQL

355

. 8.8.


UNION SELECT-, SQL- , , .

SQL-, ( 8.28) intval() ( 8.29).


8.28. SQL-

<?php
//
require_once("config.php");
// GET- id_user,
//
if (!preg_match("|^[\d]+$|",$_GET['id_user']))
{
exit(" URL-");
}
//
$query = "SELECT * FROM userslist WHERE id_user = $_GET[id_user]";
$usr = mysql_query($query);
if (!$usr) exit(" ".mysql_error());
$user = mysql_fetch_array($usr);
echo " $user[name]<br>";
if (!empty($user['email'])) echo "e-mail $user[email]<br>";
if (!empty($user['url'])) echo "URL $user[url]<br>";
?>

356
8.29. GET-
<?php
//
require_once("config.php");
// GET- id_user,
//
$_GET['id_user'] = intval($_GET['id_user']);
//
$query = "SELECT * FROM userslist WHERE id_user = $_GET[id_user]";
$usr = mysql_query($query);
if (!$usr) exit(" ".mysql_error());
$user = mysql_fetch_array($usr);
echo " $user[name]<br>";
if (!empty($user['email'])) echo "e-mail $user[email]<br>";
if (!empty($user['url'])) echo "URL $user[url]<br>";
?>

, , SQL-. ,
" ", . 8.30
, ,
SQL-.

mysql_escape_string().

8.30.
<?php
...
if (!get_magic_quotes_gpc())
{
// " "
$_POST['name'] = mysql_escape_string($_POST['name']);
$_POST['pass'] = mysql_escape_string($_POST['pass']);
}
...
?>

PHP AJAX
, -. , . , ,
. (CSS, JavaScript,
Flash) .
PHP JavaScript/
jQuery, AJAX-, .

9.1. AJAX

Web-.
, ,
, . - ,
, , .
JavaScript,
HTML-.
DOM- HTML-, JavaScript
.
DHTML. JavaScript ,
DOM , ,
. ,
( , ).

, .

358

. , ,
JavaScript , Web-
AJAX (Asynchronous JavaScript and XML). ,
JavaScript, DHTML,
. XML
: ,
JavaScript XML-,
.

9.2. jQuery
, . , ,
, , .
, .

. ,
JavaScript, , , (, CSS 3).
.
, , . , - .
JavaScript . , . .
. JavaScript- . ,
, , PHP.
JavaScript-,
, jQuery, - . http://
docs.jquery.com/Downloading_jQuery.

PHP AJAX

359

jQuery HTML- , , . 9.1 ,


<p>, green ,
id .

jQuery JavaScript- ,
http://softtime.ru/forum/index.php?id_forum=4.

9.1. jQuery
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("p").css("color", "blue");
$(".green").css("color", "green");
$("#id").css("color", "red");
});
</script>
</head>
<body>
<p> .</p>
<p class='green'> .</p>
<div class='green'> .</div>
<p id='id'> .</p>
<p> .</p>
</body>
</html>

jQuery,
jquery.js <script>. 9.1,
$,
, CSS-:
, CSS- ,
#. ready() , ,
, . css()
CSS- ( )
( ).

http://docs.jquery.com/.

360

, CSS-, jQuery . ,
div- green, :
$("div .green").

9.3.
JavaScript-
, , . 9.2
click (
) <p> id_text.
( , ). CSS cursor pointer,
.
9.2. jQuery
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
//
$("#id_text").css("cursor", "pointer");
// click
$("#id_text").bind("click", function(){
if($("#id_text").css("color") == "#0000ff")
//
$("#id_text").css("color", "#ff0000");
else
//
$("#id_text").css("color", "#0000ff");
});
});
</script>
</head>
<body>
<p id="id_text"> .</p>
</body>
</html>

9.2,
id_text bind(), -

PHP AJAX

361

, -. 9.3
,
handler().
9.3.
...
$(document).ready(function() {
//
$("#id_text").css("cursor", "pointer");
// click
$("#id_text").bind("click", handler);
});
function handler(){
if($("#id_text").css("color") == "#0000ff")
// ,
$("#id_text").css("color", "#ff0000");
else
//
$("#id_text").css("color", "#0000ff");
}

, jQuery, JavaScript, on. . 9.1


.
9.1. JavaScript

blur

change

<select>.
( , <input> <textarea>)
, ,

click

dblclick

error

,
<img>

focus

keydown

keypress

keyup

load

mousedown

362

9.1 ()

mousemove

mouseout

mouseover

mouseup

resize

scroll

select

submit

HTML-

unload

9.4.
jQuery CSS-,
, , . 9.4 <p> "
".
html().
9.4. html()
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(document).ready(change_text);
function change_text()
{
$("p").html(" ");
}
</script>
</head>
<body>
<p> .</p>
<div> .</div>
<p> .</p>
</body>
</html>

PHP AJAX

363

9.4 ,
ready() change_text().
, , ,
.

. file : +
, (. 9.1).

. 9.1.

9.5 jQuery.
9.5.
<?php
if(!empty($_FILES))
{
echo "<pre>";
print_r($_FILES);
echo "</pre>";
exit();
}
?>
<html>
<head>
<title>jQuery</title>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
// click
//
$(document).ready(handlers);

364

// + function handlers()
{
// click
$("input[type=button]").
not("[value=+]").
bind("click", remove_field);
$("input[type=button]").
not("[value=-]").
bind("click", add_field);
}
// +
function add_field(){
//
$("p:last").clone().appendTo("p:last");
//
handlers();
}
// function remove_field(){
//
$("p:last").remove();
}
</script>
</head>
<body>
<form enctype='multipart/form-data' method="post">
<p><input type="file" name="filename[]" />
<input type="button" value="+">
<input type="button" value="-"></p>
<div><input type="submit" value=""></div>
</form>
</body>
</html>

9.5, HTML- . file filename[], ,


( PHP $_FILES ). button +
. submit
PHP-,
( , ).
, ,
:

PHP AJAX

365

handlers() + , -

, + ;
add_field() +,

+ ;
remove_field() ,

.
handlers(), , , input, type
button, value, +
, , . remove_field(), + add_field().
add_field() p:last p, clone().
appendTo(). +
,
handlers().
remove_field() p (p:last) .
$_FILES.
Array
(
[filename] => Array
(
[name] => Array
(
[0] => 1.gif
[1] => 2.jpg
[2] => 3.jpg
)
[type] => Array
(
[0] => image/gif
[1] => image/jpeg
[2] => image/jpeg
)
[tmp_name] => Array
(
[0] => C:\WINDOWS\Temp\php38CB.tmp
[1] => C:\WINDOWS\Temp\php38CC.tmp
[2] => C:\WINDOWS\Temp\php38CD.tmp
)
[error] => Array

366
(
[0] => 0
[1] => 0
[2] => 0
)
[size] => Array
(
[0] => 112425
[1] => 6264
[2] => 5055
)
)
)
)

9.5.
AJAX-
load(). , ,
,
JavaScript- , ,
.
,
( 9.6). ,
load().
.

, UTF-8.
AJAX
Internet Explorer 6,
, - , UTF-8 , HTML-.
.

9.6. load() (index.php)


<html><head>
<title> load()</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
// click
//

PHP AJAX

367

$(document).ready(function(){
$("#id").bind("click", function(){
$('#info').load("time.php");
})
});
</script>
</head>
<body>
<div><a href='#' id='id'> </a></div>
<div id='info'></div>
</body>
</html>

9.6, id
click,
time.php ( 9.7). div- info.
9.7. time.php
<?php
echo date("d.m.Y H:i:s");
?>

9.6. AJAX-
AJAX- . ,
,
.
9.8 SQL- users,
.
9.8. SQL- users
CREATE TABLE users (
id_position INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
pass TINYTEXT NOT NULL,
email TINYTEXT NOT NULL,
fname TINYTEXT NOT NULL,
ffamily TINYTEXT NOT NULL,
fpatronymic TINYTEXT NOT NULL,
registerdate DATETIME NOT NULL,
block ENUM('block','unblock') NOT NULL DEFAULT 'unblock',
PRIMARY KEY (id_position)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

368

INSERT INTO users VALUES


(1, 'cheops', 'pass', 'igor@softtime.ru',
'', '', '',
'2011-05-10 19:40:01', 'unblock'),
(2, 'makkuz', 'pass', 'kuznetsov@softtime.ru',
'', '', '',
'2011-05-27 19:22:41', 'unblock');

9.8, users ,
:
id_position

, AUTO_

;
INCREMENT,

name ;
pass ;
email ;
fname ;
ffamily ;
fpatronymic ;
registerdate ;
block , unblock block.

, id usr1, usr2
. ., id_position users
( 9.9).
9.9. (index.php)
<html><head>
<title> </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="index.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
// click
//
$(document).ready(function(){
$("#list>div>a").bind("click", function(){
// AJAX-
var url = "user.php?id_position=" + this.id.substr(3,1);
//
url = encodeURI(url);

PHP AJAX

369

// AJAX-
$('#info').load(url, null, $('#info').removeClass("hidden"));
})
});
</script>
</head>
<body>
<?php
//
require_once("config.php");
//
$query = "SELECT * FROM users
ORDER BY name";
$usr = mysql_query($query);
if(!$usr) exit(" ".mysql_error());
if(mysql_num_rows($usr))
{
echo "<div id='list'>";
while($users = mysql_fetch_array($usr))
{
echo "<div><a href='#' ".
"id='usr".$users['id_position']."'>".
htmlspecialchars($users['name'])."</a></div>";
}
echo "</div>";
}
?>
<div id='info' class='hidden'></div>
</body>
</html>

: div- list , div-


info , .
div- info CSS- hidden:
.hidden {
display: none;
}

click,
AJAX- user.php?id_position=N, N users.
div- info, CSS- hidden, ,
removeClass(). 9.10
user.php.

370
9.10. (user.php)
<?php
//
require_once("config.php");
// GET-
$_GET['id_position'] = intval($_GET['id_position']);
//
$query = "SELECT * FROM users
WHERE id_position = {$_GET['id_position']}";
$usr = mysql_query($query);
if(!$usr) exit(" ".mysql_error());
if(mysql_num_rows($usr))
{
//
$user = mysql_fetch_array($usr);
//
$user['name']
= htmlspecialchars($user['name']);
$user['email']
= htmlspecialchars($user['email']);
$user['fname']
= htmlspecialchars($user['fname']);
$user['ffamily']
= htmlspecialchars($user['ffamily']);
$user['fpatronymic'] = htmlspecialchars($user['fpatronymic']);
//
echo "<p>".
"<span class='p'>:</span>".
"<span class='r'>{$user['name']}</span>".
"</p>";
echo "<p>".
"<span class='p'>Email:</span>".
"<span class='r'>{$user['email']}</span>".
"</p>";
echo "<p>".
"<span class='p'>:</span>".
"<span class='r'>{$user['fname']}</span>".
"</p>";
echo "<p>".
"<span class='p'>:</span>".
"<span class='r'>{$user['ffamily']}</span>".
"</p>";
echo "<p>".
"<span class='p'>:</span>".
"<span class='r'>{$user['fpatronymic']}</span>".
"</p>";
}
?>

PHP AJAX

371

user.php GET- id_position


user. / :
<p><span></span><span></span></p>

, CSS-, (. 9.2).

. 9.2. AJAX-

CSS- index.css, 9.11.


9.11. CSS- (index.css)
body {
font-family: Arial, sans-serif;
font-size: 14px;
}
#list {
float: left;
padding: 10px;
background: #ddd;
border-radius: 8px;
box-shadow: 2px 2px 4px #bdbcb0;
margin-right: 10px;
}
#list div {
margin-bottom: 5px;
}
#list div a {
color: #333;

372

text-decoration: none;
}
#list div a:hover {
text-decoration: underline;
}
#info {
float: left;
padding: 10px;
background: #ddd;
border-radius: 8px;
box-shadow: 2px 2px 4px #bdbcb0;
}
#info p span.p {
display: block;
float: left;
width: 70px;
text-align: right;
padding-bottom: 5px;
}
#info p span.r {
display: block;
float: left;
text-align: left;
padding: 0px 0px 5px 5px;
}
#info p {
clear: both;
}
.hidden {
display: none;
}

9.7. POST
load() jQuery POST- .
POST HTML , comments ( 9.12).
9.12. comments
CREATE TABLE comments (
id_position INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
comment TEXT NOT NULL,
putdate DATETIME NOT NULL,

PHP AJAX

373

hide ENUM('show','hide') NOT NULL,


PRIMARY KEY (id_position)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

9.12, comments :
id_position , AUTO_I
NCREMENT,


;
name ;
comment ;
putdate ;
hide , 'hide' ( -

) 'show' ( ).
. 9.3 Web-.

. 9.3. AJAX

374

comments.php, HTML-
(div- form), (div- info) ( 9.13).
9.13. (comments.php)
<html><head>
<title>AJAX- POST</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="comments.css" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
// click
//
$(document).ready(function(){
$("#id_submit").bind("click", function(){
//
if($.trim($("#id_name").val()) === "")
{
alert(', ""');
return false;
}
if($.trim($("#id_comment").val()) === "")
{
alert(', ""');
return false;
}
//
$("#id_submit").attr("disabled", "disabled");
// AJAX-
$("#info").load("addcom.php",
{name: $("#id_name").val(),
comment: $("#id_comment").val()},
$("#id_submit").attr("disabled", ""));
})
});
</script>
</head>
<body>
<div id='info'>
<?php
require_once("addcom.php");
?>
</div>
<div id='form'>
<p>
<span class='ttl'>:</span>

PHP AJAX

375

<span class='fld'>
<input id='id_name' type='text' />
</span>
</p>
<p>
<span class='ttl'>:</span>
<span class='fld'>
<textarea rows='5' id='id_comment' type='text'></textarea>
</span>
</p>
<p>
<span class='ttl'>&nbsp;</span>
<span class='fld'>
<input id='id_submit' type='submit' value='' />
</span>
</p>
</div>
</body>
</html>

HTML- id_name, id_comment id_submit.


click, ,
POST addcom.php ( 9.14).
POST- ,
load() jQuery, ,
POST- (name comment), POST-,
id_name id_comment val().
( ) div- info. ,
, disabled.
9.14. (addcom.php)
<?php
//
require_once("config.php");
// 1. , POST-,
// ,
//
if(!empty($_POST))
{
$error = array();

376
if(empty($_POST['name']))
{
$error[] = " ";
}
if(empty($_POST['comment']))
{
$error[] = " ";
}
// ,
//
if(empty($error))
{
// " ",
//
if (!get_magic_quotes_gpc())
{
$_POST['name'] = mysql_escape_string($_POST['name']);
$_POST['comment'] = mysql_escape_string($_POST['comment']);
}
$query = "INSERT INTO comments
VALUES (NULL,
'{$_POST['name']}',
'{$_POST['comment']}',
NOW(),
'show')";
if(!mysql_query($query))
{
$error[] = " ";
}
}
}
// 2.
//
$query = "SELECT * FROM comments
WHERE hide = 'show'
ORDER BY putdate DESC";
$com = mysql_query($query);
if(!$com) exit(" ".mysql_error());
// ,
//
if(mysql_num_rows($com))
{
while($comments = mysql_fetch_array($com))
{
// ,
// JavaScript-
$comments['name'] = htmlspecialchars($comments['name']);

PHP AJAX

377

$comments['comment'] = nl2br(htmlspecialchars($comments['comment']));
//
echo "<div>".
"<span class='author'>{$comments['name']}</span>".
"<span class='date'>{$comments['putdate']}</span>".
"<span class='comment'>{$comments['comment']}</span>".
"</div>";
}
}
?>

addcom.php :
. addcom.php - POST, , .
,
.

9.8.
.
catalogs, ( 9.15).
9.15. SQL- catalogs
CREATE TABLE catalogs (
id_catalog INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
pos INT(11) NOT NULL,
hide ENUM('show','hide') NOT NULL,
id_parent INT(11) NOT NULL,
PRIMARY KEY (id_catalog)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO catalogs VALUES(1, ' ', 1, 'show', 0);
INSERT INTO catalogs VALUES(2, ' ', 2, 'show', 0);
INSERT INTO catalogs VALUES(3, '', 3, 'show', 0);
INSERT INTO catalogs VALUES(4, '', 4, 'show', 0);
INSERT INTO catalogs VALUES(5, 'ASUS', 1, 'show', 1);
INSERT INTO catalogs VALUES(6, 'Biostar', 2, 'show', 1);
INSERT INTO catalogs VALUES(7, 'Foxconn', 3, 'show', 1);
INSERT INTO catalogs VALUES(8, 'GIGABYTE', 4, 'show', 1);
INSERT INTO catalogs VALUES(9, 'Intel', 5, 'show', 1);
INSERT INTO catalogs VALUES(10, 'MSI', 6, 'show', 1);
INSERT INTO catalogs VALUES(11, 'Supermicro', 7, 'show', 1);

378
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT
INSERT

INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO
INTO

catalogs
catalogs
catalogs
catalogs
catalogs
catalogs
catalogs
catalogs
catalogs
catalogs

VALUES(12,
VALUES(13,
VALUES(14,
VALUES(15,
VALUES(16,
VALUES(17,
VALUES(18,
VALUES(19,
VALUES(20,
VALUES(21,

'Hitachi', 1, 'show', 2);


'Samsung', 2, 'show', 2);
'Seagate', 3, 'show', 2);
'Western Digital', 4, 'show', 2);
'ASUS', 1, 'show', 3);
'GIGABYTE', 2, 'show', 3);
'MSI', 3, 'show', 3);
'Sapphire', 4, 'show', 3);
'AMD', 1, 'show', 4);
'Intel', 2, 'show', 4);

catalogs
:
id_catalog , AUTO_INCREMENT,


;
name ;
pos ;
hide ;
id_parent , -

0,
id_catalog .
: " ", " ", ""
"". AJAX- (. 9.4).

. 9.4.

PHP AJAX

379

id_fst ,
id_snd disabled.
change
( 9.16).
9.16. (catalog.php)
<html><head>
<title> </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
$("#id_fst").bind("change", function(){
// AJAX-
$("#id_snd").load("select.php?id_catalog=" + $('#id_fst').val(),
null,
$("#id_snd").attr("disabled", ""));
})
});
</script>
</head>
<body>
<?php
//
require_once("config.php");
//
$query = "SELECT * FROM catalogs
WHERE id_parent = 0 AND hide = 'show'
ORDER BY pos";
$cat = mysql_query($query);
if(!$cat) exit(" ".mysql_error());
if(mysql_num_rows($cat))
{
echo "<select id='id_fst'>";
echo "<option value='0'> </option>";
while($catalog = mysql_fetch_array($cat))
{
echo "<option value='{$catalog[id_catalog]}'>".
"{$catalog[name]}</option>";
}
echo "</select>";
}
?>
<select id='id_snd' disabled='disabled'>
<option value='0'> </option>

380

</select>
</body>
</html>

select.php, GET- id_catalog ( 9.17).


9.17. (select.php)
<?php
//
require_once("config.php");
// GET-
//
$_GET['id_catalog'] = intval($_GET['id_catalog']);
//
$query = "SELECT * FROM catalogs
WHERE id_parent = {$_GET['id_catalog']} AND
hide = 'show'
ORDER BY pos";
$cat = mysql_query($query);
if(!$cat) exit(" ".mysql_error());
if(mysql_num_rows($cat))
{
echo "<option value='0'> </option>";
while($catalog = mysql_fetch_array($cat))
{
echo "<option value='{$catalog['id_catalog']}'>".
"{$catalog['name']}</option>";
}
}
?>

9.9.
AJAX-
, . , .
( $_SESSION). HTML- ,
. 9.5.
index.php, HTML-
AJAX-, 9.18.

PHP AJAX

381

. 9.5. AJAX-

9.18. (index.php)
<?php
//
session_start();
?>
<html>
<head>
<title>jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[type=checkbox]").bind("click", function(){
$.post("check.php", {id: $(this).attr("id"),
status: $(this).attr("checked")});
});
});
</script>
</head>
<body>
<p><input id="id1" type="checkbox"
<?php echo checkbox("id1"); ?> /> </p>
<p><input id="id2" type="checkbox"
<?php echo checkbox("id2"); ?> /> </p>
<p><input id="id3" type="checkbox"
<?php echo checkbox("id3"); ?> /> </p>
<p><input id="id4" type="checkbox"
<?php echo checkbox("id4"); ?> /> </p>
</body>
</html>

382

<?php
function checkbox($key)
{
if(empty($_SESSION[$key])) return "";
else return "checked='checked'";
}
?>

post()
check.php ( 9.19). ,
JavaScript-, POST-. POST-: id status
( ).
9.19. AJAX- (check.php)
<?php
//
session_start();
//
if($_POST['status'] == "true")
{
$_SESSION[$_POST['id']] = 1;
}
else
{
$_SESSION[$_POST['id']] = 0;
}
?>

check.php $_SESSION .
checkbox() index.php checked, HTML-.

10

PHP
Web- PHP,
. .
, .

10.1.
, , .
, . , Windows UNIX- , , .

. PHP
setlocale(), :
setlocale($category, $locale [, ...])

FALSE,
. $category . 10.1.
NULL,
.
10.1. ,

LC_COLLATE

LC_CTYPE


. : , , ,

LC_MONETARY

10

384

10.1 ()

LC_NUMERIC

LC_TIME

.
, ,

LC_MESSAGES

LC_ALL

10.1 setlocale() .
10.1.
<?php
//
echo setlocale(LC_ALL, NULL);
?>

,
, Windows
:
Russian_Russia.1251

UNIX- , , :
ru_RU.UTF-8
ru_RU.KOI8-R
ru_RU.CP1251

, . 10.2
.
10.2.
<?php
//
echo setlocale(LC_MONETARY, "ru_RU.CP1251");
?>

setlocale() . 10.3 ,
.

PHP

385

10.3.
<?php
$loc = setlocale(LC_ALL, 'ru', 'ru_RU', "rus", "russian");
echo " '$loc'";
?>

10.2.
(, )
, ,
.
PHP serialize(),
unserialize().
serialize() :
serialize($value)

,
. unserialize() , .
unserialize($str)

10.4 serialize() unserialize().


10.4. serialize() unserialize()
<?php
$poll[0] = 23;
$poll[1] = 45;
$poll[2] = 34;
$poll[3] = 2;
$poll[4] = 12;
//
$str = serialize($poll);
echo $str."<br>";
//
$arr = unserialize($str);
print_r($arr);
?>

10.4 :
a:5:{i:0;i:23;i:1;i:45;i:2;i:34;i:3;i:2;i:4;i:12;}
Array
(
[0] => 23

10

386
[1]
[2]
[3]
[4]

=>
=>
=>
=>

45
34
2
12

, PHP $_SESSION serialize(). , . .


serialize().

10.3.
PHP GDLib,
, , . resizeimg(),
:
$filename ;
$smallimage ;
$w ;
$h .
resizeimg($filename, $smallimage, $w, $h)

10.5 .
10.5.
<?php
function resizeimg($filename, $smallimage, $w, $h)
{
// 1. $w $h
//
$ratio = $w / $h;
//
list($width, $height) = getimagesize($filename);
// ,
if (($width < $w) && ($height < $h))
{
copy($filename, $smallimage);
return true;
}
//
$src_ratio = $width/ $height;

PHP

387

// ,
//
if ($ratio < $src_ratio) $h = $w/$src_ratio;
else $w = $h*$src_ratio;
// 2.
// $w x $h
$dest_img = imagecreatetruecolor($w, $h);
// ,
$src_img = imagecreatefromjpeg($filename);
//
imagecopyresampled($dest_img,
$src_img,
0,
0,
0,
0,
$w,
$h,
$width,
$height);
//
imagejpeg($dest_img, $smallimage);
//
imagedestroy($dest_img);
imagedestroy($src_img);
return true;
}
?>

$w $h, ,
( ).
$smallimage $filename.
imagecreatetruecolor(), $dest_img. $src_img
imagecreatefromjpeg(). imagecopyresampled().

10.4.
, GDLib. PNG-, -

10

388

. . 10.1 -
.

. 10.1.

(, Adobe
Photoshop), , 50%.

imagecopy(), :
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h)

$src_im $dst_im.
$src_x,
$src_y. $src_w $src_h . $dst_im
$dst_x, $dst_y.
10.6 ,
softtime.png img.jpg.
10.6.
<?php
//
$filename = "img.jpg";
//
$img = imagecreatefromjpeg($filename);
//
$filename = "softtime.png";
$msk = imagecreatefrompng($filename);
//
list($width, $height) = getimagesize($filename);
//
// Y 50
imagecopy($img, $msk, 0, 50, 0, 0, $width, $height);
//
header('Content-type: image/jpeg');
imagejpeg($img);
?>

10.6 water_marks.php. ( 10.7).

PHP

389

10.7.
<table>
<tr align='center'>
<td></td>
<td></td>
</tr>
<tr>
<td><img width='200' src='img.jpg' /></td>
<td><img width='200' src='water_mark.php' /></td>
</tr>
</table>

. 10.2 10.7.

. 10.2.

10.5.
, ,
, PHP . 10.8
dir ( ls UNIX), .
10.8.
<?php
// echo `ls -l`; // UNIX
echo `dir`;
// Windows
?>

10

390

:
E MEDIUM
: EC68-EF90
E:\main
25.03.2004
25.03.2004
23.10.2004
24.07.2004
03.07.2004
18.09.2003
25.03.2004
11.04.2004
25.03.2004
30.03.2004
04.04.2004
25.04.2004
12.06.2004
26.09.2004

20:41
<DIR>
.
20:41
<DIR>
..
00:19
411 config.php
12:43
54 index.php
12:55
1 815 main.php
19:43
2 789 top.php
20:42
<DIR>
images
16:30
<DIR>
Projects
20:43
<DIR>
admin
22:17
<DIR>
scripts
12:27
<DIR>
Books
12:52
<DIR>
tools
09:46
<DIR>
test
12:53
<DIR>
Site
4
5 069
10 18 157 846 528


,
. , ,
, .
,
http://www.softtime.ru/from/.
, , , , .

A
Apache
13
105
22
93
.htaccess 82, 92
php.ini 55
mod_rewrite 105
22
14
.htpasswd 103

C
chcp 53
cookies 188
cron 89

D
dir 62

F
for 142
foreach 143

H
HTTP 98
HTTP-
Accept 196
Accept-Language 197
Connection 246, 250

Content-Language 250
Content-Length 252
Content-Type 250
Cookie 273
Date 249
Host 246
Last-Modified 249
Referer 270
Server 249
Set-Cookie 250
Transfer-Encoding 250
User-Agent 199, 272
X-Powered-By 249

J
jQuery
appendTo 365
bind() 360
clone() 365
css() 359
load() 366
ready() 359, 363
removeClass() 369
val() 375
361

M
MySQL
ALTER DATABASE 290
ALTER TABLE 291, 294, 301
ANY 324
ALL 325
AS 299
AUTO_INCREMENT 297

BIGINT 292, 316


BOOLEAN 292
BLOB 293
CHAR 293
COLLATION 308
Command Line Client 42
COUNT() 326
CREATE DATABASE 289
CREATE TABLE 123, 291,307
CREATE USER 117, 122, 123
DATE 293
DATE_FORMAT() 313
DATETIME 293
DEC 292
DECIMAL 292
DEFAULT CHARATER SET 290
DEFAULT CHARSET 294
DELETE 123, 348
DELIMITER 119
DESCRIBE 294
DESCRIBE TABLE 291
DISTINCT 318DELETE 127, 303
DOUBLE 292
DOUBLE PRECISION 292
DROP COLUMN 295
DROP DATABASE 289
DROP TABLE 123, 291, 294
DROP USER 122,127
ENGINE 294
FLOAT 292
FLOOR() 316
FROM 328
GRANT 122
GRANT ALL, IDENTIFIED BY 126
GRANT, LIKE 126
GRANT, ON 125
GROUP BY 318, 326
GROUP_CONCAT() 330
HAVING 321, 327
IN 322, 324
INDEX 307
INET_ATON() 316
INET_NTOA() 317
INSERT 123, 295, 348
INT 292
IF EXISTS 291
IF NOT EXISTS 291
JOIN 328
KEY 307

393

LAST_INSERT_ID() 298
LIMIT 331, 302
LONGBLOB 293
LONGTEXT 293
MAX() 312
MEDIUMBLOB 293
MEDIUMINT 292
MEDIUMTEXT 293
MIN() 312, 326
MODIFY 295
NOT IN 323
NOW() 299
NUMERIC 292
ON 321, 329
ORDER BY 301, 313
PRIMARY KEY 297, 306
RAND() 301
RENAME DATABASE 290
RENAME USER 123
RENAME TABLE 291
REAL 292
REVOKE 122, 127
SELECT 124, 318, 348
SELECT ... INTO 123
Server Instance Configuration Wizard 36
SET 293
SET NAMES 310, 337
SET PASSWORD 121
SMALLINT 292
SHOW CHARATER SET 307
SHOW DATABASES 124, 290
SHOW GRANTS 127
SHOW TABLE 291
SQL- 130
SUM() 313
TEXT 293
TIME 293
TIMESTAMP 293
TINYBLOB 293
TINYINT 292
TINYTEXT 293
TO_DAYS() 315
TRUNCATE TABLE 291
UNIQUE 307
UNIQUE INDEX 307
UNIQUE KEY 307
UNLOCK TABLES 129
UNSIGNED 292
UPDATE 124, 303

394

MySQL (.)
USE 290, 291
USING 328
VARCHAR 293
VERSION() 42, 310
WHERE 299, 321, 327
WITH GRANT OPTION 126
YEAR 293
SUM() 326
338
14
337
43
39, 53, 307
116
my.ini 44
43
125
333

, 288

387

AllowOverride 99
Apache
AccessFileName 92
AddDefaultCharset 94
AddType 28
AllowOverride 92
CustomLog 21
DirectoryIndex 28, 95
DocumentRoot 21
ErrorDocument 99
ErrorLog 21
HeaderName 95
Include 20
IndexIgnore 96

127
318
a 30
335
c 117

P
PHP
59
13
86
php.ini 28, 30
a 24
phpMyAdmin 131

S
Structured Query Language 288

LoadModule 28
NameVirtualHost 21
Options 95, 106
PHPIniDir 28, 56
ReadmeName 95
Redirect 100
RedirectPermanent 101
RedirectTemp 101
RemoveHandler 98
RewriteBase 107
RewriteCond 114, 115, 116
RewriteEngine 106
RewriteRule 111, 116
ServerAlias 21
SeverAdmin 21
MySQL
character_set_client 310
character_set_connection 310
character_set_results 310
collation_connection 310
default-charater-set 42
default-storage-engine 294
skip-grant-tables 121

PHP
allow_url_fopen 79
allow_url_include 79
arg_separator.input 74
arg_separator.output 74
asp_tags 56
auto_append_file 75, 77
auto_globals_jit 74
auto_prepend_file 75, 77, 83
date.default_latitude 81
date.default_longitude 81
date.sunrise_zenith 81
date.sunset_zenith 81
date.timezone 81
default_charset 75
default_mimetype 75
default_socket_timeout 79
disable_classes 63
disable_functions 63, 64
display_errors 68
display_startup_errors 68
engine 56
error_log 69
error_reporting 68, 71, 73
expose_php 67
extension 79
extension_dir 79
file_uploads 78
from 79
highlight.bg 66
highlight.comment 66
highlight.default 66
highlight.html 66
highlight.keyword 66
highlight.string 66
ignore_repeated_errors 69
ignore_user_abort 67
log_errors 68
log_errors_max_len 68
magic_quotes_gpc 75, 76, 77
magic_quotes_runtime 75
magic_quotes_sybase 75
max_execution_time 67
max_input_time 67
memory_limit 67, 85
open_basedir 63, 64, 82
output_buffering 56, 57, 58
post_max_size 75
precision 56, 57

395

realpath_cache_size 66
realpath_cache_ttl 66
register_argc_argv 74
register_globals 74, 75
register_long_arrays 74, 83
request_order 74
safe_mode 61
safe_mode_allowed_env_vars 61, 62
safe_mode_exec_dir 60, 62
safe_mode_gid 60, 61
safe_mode_include_dir 60, 61
safe_mode_protected_env_vars 62
session.auto_start 80
session.cookie_domain 80
session.cookie_lifetime 80, 192
session.cookie_path 80
session.cookie_secure 80
session.gc_divisor 81
session.gc_maxlifetime 81
session.gc_probability 81
session.name 80
session.save_handler 80
session.save_path 80, 193
session.serialize_handler 80
session.use_cookies 80
session.use_only_cookies 80
short_open_tag 56
track_errors 69
upload_max_filesize 78, 185
upload_tmp_dir 78, 182
user_agent 79, 272
variables_order 74
121

240
203
234
241

array() 137
include 60
include_once 60
isset() 147
list() 161
require 60
require_once 60
unset() 195

396

383

$_COOKIE 174
$_ENV 174
$_FILES 173, 182, 183
$_GET 60, 173, 174
$_POST 173, 181
$_REQUEST 174
$_SERVER 60, 174, 195
$_SESSION 174, 192, 193
$GLOBALS 174
133
133, 148
133
133
145
141
154
152
134
136
162
152
147
159
133

100
51, 114
79, 272

281
UNIX 59, 90

220
107

385
192

244
SQL 289
288
225

InnoDB 36
MyISAM 36

204
218
208
182
217
209
203
205
209
218
206
203
209
211

array_count_values() 145, 146


array_fill() 138
array_key_exists() 151
array_keys() 148
array_map() 158
array_merge() 155
array_merge_recursive() 155, 156
array_multisort() 162, 167
array_rand() 153
array_search() 151
array_sum() 152
array_unique() 159
array_walk() 157, 231
arsort() 162, 165
asort() 162, 164
basename() 228
chdir() 233, 234
checkdnsrr() 276
chroot() 233
closedir() 233
convert_cyr_string() 62

copy() 188, 209


count() 145
curl_exec() 253
curl_init() 253
curl_setopt() 253, 259
date_sun_info() 81
date_sunrise() 81
date_sunset() 81
error_reporting() 73
exec() 60
exit() 340
explode() 138
fclose() 203
fgets() 212, 246
file() 216, 229, 231
file_count() 238
file_exists() 221
file_get_contents() 60, 214, 228
file_put_contents() 219, 243
filesize() 214, 220, 242
fopen() 60, 203, 206
fread() 60, 213
fsockopen() 244
fwrite() 60, 217
get_magic_quotes_gpc() 76, 77, 224
getcwd() 233, 234
gethostbyaddr() 276, 278
gethostbyname() 276
gethostbynamel() 276, 277
glob() 233, 236
highlight_file() 64
highlight_string() 64
htmlspecialchars() 62
http_build_query() 176
imagecopy() 388
imagecopyresampled() 387
imagecreatefromjpeg() 387
in_array() 150
ini_get() 84
ini_get_all() 84
ini_restore() 84
ini_set() 84
ip2long() 276
is_array() 147
is_uploaded_file() 183
krsort() 162, 166
ksort() 162, 165
long2ip() 276
mail() 281

397

memory_get_usage() 84
mkdir() 233, 234
mktime() 189
move_uploaded_file() 184, 188
mysql_close() 335, 337
mysql_connect() 335
mysql_erorr() 340
mysql_escape_string() 76
mysql_fetch_array() 340, 341, 345, 352
mysql_fetch_assoc() 340, 341, 343, 345
mysql_fetch_object() 340, 341, 347
mysql_fetch_row() 340, 341, 342, 345
mysql_insert_id() 298
mysql_num_fields() 348
mysql_num_rows() 348, 349
mysql_ping() 335
mysql_query() 339, 340, 341
mysql_result() 340, 341
mysql_select_db() 290, 291, 338
natcasesort() 162
natsort() 162, 166
opendir() 233, 241
parse_url() 176, 177
php_sapi_name() 84
php_uname() 85
phpinfo() 29, 85, 86
phpversion() 85
print_r() 134, 142, 346
put_get_contents() 60
rand() 152, 230
range() 138
rawurldecode() 176
rawurlencode() 176
readdir() 233, 241
rename() 209
rewinddir() 233
rmdir() 233, 241
rsort() 162, 164, 232
scan_dir() 237
scandir() 233, 235
serialize() 385
session_destroy() 194
session_id() 195
session_start() 193
setcookie() 188
setlocale() 384
shell_exec() 60, 62
shuffle() 153, 231
sizeof() 145

398

(.)
sort() 162, 232
strstr() 247
system() 60
tempnam() 203, 208
time() 189
tmpfile() 204
touch() 203, 206
trim() 231
trim_array() 231
uasort() 162
uksort() 162
unlink() 209
unserialize() 385
urldecode() 176

urlencode() 176, 352


usort() 162

121

76

SQL 288

Оценить