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

PHP Hypertext Preprocessor

., . . ..-

:
1. -
2.
3.
4.
5.
6.
7.
8.
9.

., . . ..-

1
3

- WEB-
Web-

Apache

()

HTML

WEB-
web-
:
Apache Apache
IIS (Internet Information Server ) Microsoft
SunOne Sun Microsystems
WebLogic BEA Systems
IAS (Inprise Application Server) Borland
WebSphere IBM
OAS (Oracle Application Server)


HTTP (HyperText Transfer Protocol,
) ,
Internet.
:
;
URI;
;
, ,
, , , () .
:
, (
);
, ,
.

< > := <> < >


<-URI> < >
GET http://phpbook.info/
,
( ,
) , , .
:
< > := < >
(< >|< >|
< >) < >
[< >]
POST http://phpbook.info/cgi-bin/test HTTP/1.0
7

HTTP
HTTP ,
: POST, GET HEAD.
GET ,
URI . URI ,
( ). ,
, (
).
HEAD GET,
.
POST
, , ,
, ..
.

HTML-
<form method="get" action=result.php">
:
<input type="text" name="fio"><br>
:
<select name="age">
<option value="1"> 20</option>
<option value="2">20-40</option>
<option value="3"> 40</option>
</select><br>
<input type="checkbox" name="human"> ""!<br>
<input type="submit" name="submit" value="ok">
</form>

HTML-
( result.php)
<?php
if (!$_REQUEST["human"]) {
echo " !!!\n";
exit();
}
echo ", $_REQUEST[fio]!\n";
if ($_REQUEST["age"]==1) {
echo ...\n";
}
elseif ($_REQUEST["age"]==2) {
echo " ?\n";
}
elseif ($_REQUEST["age"]==3) {
echo " !\n";
}
10

HTML-
( result.php )
<?php
if (!$_REQUEST["human"]) {
echo " !!!\n";
die; // exit()
}
echo ", $_REQUEST[fio]!\n";
$message = array(
1=> ...\n,
2=>" ?\n,
3=>" !\n"
);
echo $message[$_REQUEST["age"]];

11



, , ,
, ,
, ..
:
REMOTE_ADDR IP- (), ;
REMOTE_HOST , ;
HTTP_REFERER , ;
REQUEST_METHOD , ;
QUERY_STRING , URL ;
SCRIPT_NAME , ;
HTTP_USER_AGENT ,

12


4.1.0

4.1.0
first_name= -
$first_name - .

$HTTP_POST_VARS $HTTP_GET_VARS,
,
.

:
first_name= GET,
$HTTP_GET_VARS["first_name"]=".
first_name= POST,
$HTTP_POST_VARS["first_name"]=".

13


4.1.0

PHP 4.1.0
, HTTP, $_REQUEST.
, POST GET,
HTTP cookies.
, ..
,
( ).
<?php
$str = ",
".$_REQUEST["first_name"].
".$_REQUEST["last_name"]."! <br>";
$str .="
".$_REQUEST["kurs"];
echo $str;
?>
14


$_REQUEST
$HTTP_POST_VARS $_POST
$HTTP_GET_VARS
$_GET
$_POST $_GET , ..
.
<?php
$str = ",
".$_POST ["first_name"]."
".$_POST ["last_name"] ."! <br>";
$str .= " ".$_POST["kurs"];
echo $str;
?>
, !
PHP

15

getenv()
,
.
<?
getenv("REQUEST_METHOD");
//
echo getenv ("REMOTE_ADDR");
// IP- ,
getenv("QUERY_STRING");
// , URL
getenv("HTTP_REFERER");
// ,
?>

16

2
17


<?php echo "Hello, world!" ; ?>
:
$var_name = $value;

$var1 = 1;
$var2 = 1.0;
$var3 = str;
$var4 = true;
$var5 = $object;

:
define($name, $value, $case_sen);

define(pi, 3.14, true);


define(str, string, false);

18


PHP .
:
boolean ();
integer ();
float ( );
string ().

:
array ();
object ().
:
resource ();
NULL.
19

integer
<?PHP
$a = 1234; //
$b = -123; //
$c = 0123; //
$d = 0x1A; //
?>

20

string
PHP :
;
;
c heredoc-.
:
<?PHP
echo ';
echo ': \n - ';
echo ' $expand ';
?>

21

string
:
<?PHP
echo ": \n - ";
echo " $expand - ";
?>

Heredoc :

<?PHP
$name = '';
echo <<< HEREDOC
"$name".
HEREDOC;
?>

// "

22

string
:

\n (LF),
\r (CR),
\t ,
\\ - ,
\$ - ,
\" ,
\000 - \377: ASCII- 0 3778,
\x00 - \xFF: ASCII- 0 FF16

23

array
<?PHP
$array = Array(25, -7 , 93, -567, 90);
?>
<?PHP
$food = Array('','','); //

echo $food[0]; // - .
$food[1] = ''; // -

echo $food[1]; // .
?>

24


<?PHP
$arr = Array('key'=>'val' , 'key2'=>'val2'); //

echo $arr['key']; // key. val


echo $arr[0]; // . .

$arr['key2'] = ''; // key2


.
echo $arr['key2']; // .

?>
25


<?PHP
$ARRAY = Array
(
Array('','') ,
Array('key'=>'val' , 'key2'=>'val2') ,
Array('key3'=>'val3', '')
);
echo $ARRAY[2]['key3'];

// . 0,1 2
// . 0 1
// . key key2
// . key3 0
// val3

$arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));


echo $arr["somearray"][6];
// 5
echo $arr["somearray"][13];
// 9
echo $arr["somearray"]["a"];
// 42
?>
26

object
<?php
//
class Person
{
// ()
var $eye_color;
var $weight;
// , PHP
function know_php()
{
echo " PHP";
}
}
$bob = new Person;
// bob
$bob->eye_color = blue; // eye_color
$bob->weight = 86.5;
// weight
$bob -> know_php();
// PHP
?>
27

resource
,
(,
).

(, mysql_connect(),
pdf_new() ..)

28

NULL
NULL ,
.
NULL, :
NULL ($var = NULL);
- ;
unset().
NULL
NULL.

29

gettype()

is_float(), is_int(), is_string(), is_object(), is_array()


intval() - integer

floatval() - float

strval() - string

settype() -

30

3
31

-$a
$a + $b
$a - $b
$a * $b
$a / $b
$a % $b

- $a.
- $a $b.
- $a $b.
- $a $b.
- $a $b.
-
$a $b.

32

++ -

++$a - $a
$a.
$a++ -
$a, $a 1.
--$a - $a 1
$a.
$a-- -
$a, $a 1

33


<?PHP
$a = "Hello ";
$b = $a . "World!"; // $b "Hello World!"

$a = "Hello ";
$a .= "World!";

// $a "Hello World!"

?>

34

$a + $b
$a == $b

$a $b.
TRUE , $a $b
.
$a === $b TRUE , $a $b

.
$a != $b TRUE $a
$b.
$a <> $b TRUE $a
$b.
$a !== $b TRUE $a
$b.

35

==

$a == $b

===

$a === $b

!=

$a != $b

<>

$a <> $b

!==

$a !== $b

<

$a < $b

>

$a > $b

<=

$a <= $b

>=

$a >= $b
36

and

$a and $b

&&

$a && $b

or

$a or $b

||

$a || $b

xor
!


(NOT)

$a xor $b
! $a
37

4
38

if elseIf-else
if( )
1;
elseIf( )
2;
else
3;

39

if
if($name == "sasha") echo ", !";
else echo " ?";
<?php
if($s == "yes") :
?>
<h1>!</h1>
<?php
endif;
?>
40

switch-case

switch()
{
case 1: ; [break;]

case N: ; [break;]
}

41


switch-case
switch($what) {
case 33:
case "sun":
default:

echo "what is 33"; break;


echo "what is sun"; break;
echo "what is unknown"; }

switch ($var) {
case $a: echo " var a"; break;
case $b: echo " var b"; break; }

42

switch-case if elseIf
switch ($a) {
case "run":
func1();
break;
case "stop":
func2();
break;
case "pause":
func3();
break;
}

if ($a=="run") {
func1();
}
elseif ($a=="stop") {
func2();
}
elseif ($a=="pause") {
func3();
}

43

while, do-while for


while( )
;
do ;
while() ;
for(; ; )
;
44

while

$a=0;
while($a <100) {
$a++;
echo $a; }

$a=0;
while($a <100):
$a++;
echo $a;
endwhile;

45

for
for($i = 0; $i < 10; $i++)
{ echo ($i); }

for($i = 10; $i > 0; $i--):


echo ($i);
endfor;

46

foreach
<?php
$names[""] = "";
$names[""] = "";
$names[""] = "";
$names[""] = "";
foreach ($names as $key => $value) {
echo "<b>$value $key</b><br>";
}
?>

47

5
48

fopen()
$fp = fopen('counter.txt', 'r');
r .
r+ - .
w .
, .
w+ - r+,
, .
a ,
(
).
a+ -
(
). .

49

fwrite()
<?php
$fp = fopen("counter.txt", "a"); //
$mytext = " \r\n"; //

$test = fwrite($fp, $mytext); //


if ($test) echo ' .';
else echo ' .';
fclose($fp); //
?>

50

fgets()
<?php
$fp = fopen("counter.txt", "r"); //
if ($fp)
{
while (!feof($fp))
{
$mytext = fgets($fp, 999);
//
echo $mytext."<br />";
//
}
}
else echo " ";
fclose($fp);
?>

51

fread()
<?php
//
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

52

file()
<?php
$file_array = file("counter.txt");
// $file_array

?>
$lines = file('http://www.example.com/');
//
foreach ($lines as $line_num => $line) {
echo " #{$line_num}: " .$line . "\n";

53

fgetc()
<?php
$fp = fopen("counter.txt", "r"); //
if ($fp)
{
while(!feof($fp))
{
$char = fgetc($fp);
if ($char == '') $i = $i + 1;//
}
echo ' "c" : '. $i;
}
else echo " ";
?>

54

fclose()
<?php
$fp = fopen("counter.txt", "r");
if ($fp)
{
echo ' ';
fclose($fp); //
}
?>
55

file_get_contents()
#1
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
#2
<?php
// 14 , 21
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

56

var_damp()
<?php
$a = array (1, 2, array ("a", "b", 3.14));
var_dump ($a);
?>
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> array(3) {
[0]=> string(1) "a"
[1]=> string(1) "b"
[2]=> float(1) (3.14)
}}

57


mkdir("mydir"); - (bool)
rmdir("mydir"); - (bool)
chmod("myfile.txt", 0666); - (bool)
copy("myfile1.txt", "myfile2.txt"); - (bool)
rename("myfile1.txt", "myfile2.txt"); - (bool)
unlink("myfile.txt"); - (bool)
if (file_exists("myfile.txt")) { } (bool)
file_put_contents("myfile.txt", $data); -
PHP 5 (int)

58

6
59

Regular expressions (reges)


-
, :
.
UNIX
Perl.

(regular expression)
,
(pattern) .
(pattern) ,
, .

.
.
,
.

60


$arr = explode(".", "28.01.2008"); -
(array)
$str = implode("-", array(2008,1,28)); -
(string)
$str = ltrim(" "); - (string)
$str = rtrim(" "); - (string)
$str = trim(" "); - (string)
$str = sprintf("%02d.%02d.%04d", $d, $m, $y); -
(string)
$a = strlen("qwerty"); - (int)
if (strpos($str, "q")===FALSE) {} (int)
$s = strstr($str, "q"); - (string)
$s = substr("qwerty", 2, 3); - (string)
$str = str_replace("banana", "a", "@"); - (string)
if (strcasecmp($str1, $str2)==0) {} (int)
if (strcmp($str1, $str2)==0) {}
unset($str)

61


<?php
$stroka = 'php';
$file = file("php_text.txt");
$i = 0;
while ($i < sizeof($file)) {
if (strstr($file[$i], $stroka) <> FALSE){
unset($file[$i]);
}
$i++; }
// php_text_out
$f = fopen("php_text_out.txt", 'w+');
foreach($file as $string) {
fwrite($f, $string); }
fclose($f);
?>

62


-
,
.

, .
/(.*?)\s/i

/ (.*?)\ /i
~(.*?)\s~i
#(.*?)\s#i

/(.*?)\s/

(.*?)\s

\s -
.* -
? -

i -
.
63

'a.c'
abc, aWc, a+c
ac, a..c, cba
'F.*d'
FddFd, Freud, F.*d feed, Sigmund, dF
'u..[p-t]'
user, u##s, uppp undo, uncut, u=t
'wuff(-wuff)*'
wuff, wuff-wuff-wuff wuffwuff, wuff'[+-]?[0-9]+'
+1, -0932, 333
+-7, -, 0+0
'[fit|plug](in|out)+' fitin, pluginoutin
infit, plug, outin

-
-
64

\d
\D
\s
\S
\w
\W
\n
\r
\t
\xhh
^
$
|
.
*
+
?
{}
\A
\Z
\z
\b
\B
\G

(0-9)
( 0-9).
( ).
(, , \s).
, (_).
, , \w.
.
.

0xhh
.
.
().
. .
.
.
.
. {4,6} - 4 6 .
.
.
.
.
.
.

65


- , ,
.
"{}".
: .
\d{4} - .
\d{2,4} - .
\w{3,} - .
\d{,5} - , , .
[ -- ]{1,3} - , .

66


: "*" (), "+" () "?" ().
,
. ,
,
( @), - ( @).
\w* - , 0.
\d+ - , .
\d? - , .
"*" "+":

?"

" "

\.+

" "

" "

\.+?

""

67


.
i

case-insensitive, ..
.
, , ,
.

, .
'^' '$'
. ,
.

'.'
. .. /.+/
, , .
.

" "
("g" - "greedy", "").

68

foo
^foo
foo$
^foo$
[abc]
[a-z]
[^A-Z]
(gif | jpg)
[a-z]+
[0-9.-]
^[a-zA-Z0-9_]{1,}$
([wx])([yz])
(^A-Za-z0-9)
([A-Z]{3}|[0-9]{4})

foo
foo
foo
foo
a, b, c

,
gif jpeg

,
, , _
wy, wz, xy, xz
( )
4

69



e-mail


[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+?[\ .A-Za-z0-9]{2,}
^\d{1,2}([-. /])\d{1,2}\1\d{2,4}$
[\d]{4}\.[\d]{2}
(?:8|\+7)? ?\(?(\d{3})\)? ?(\d{3})[ -]?(\d{2})[ -]?(\d{2})
/<tag>(.*)</tag>/is

70


PHP
:

preg_match()
preg_match_all()

preg_match() , true,
false,
preg_match_all() ,

preg_replace()

preg_replace(), , ereg_replace(),
,
, , ,
.

preg_split()

preg_split(), split(), ,

.
preg_grep() ,
, .

preg_grep()

preg_quote()


http://on-line-teaching.com/php/regexp.htm


function checkmail($mail) {
//
$mail=trim($mail);
if (strlen($mail)==0) return 1;

if (!preg_match("[\.\-_A-Za-z0-9]+?@[\.\-A-Za-z0-9]+
?[\.A-Za-z0-9]{2,}",$mail))
return -1;
return $mail;
}

72

/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i

/A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zAZ0-9]{6,}z/

/<title>(.*)</title>/
^\d{1,2}([-. /])\d{1,2}\1\d{2,4}$
/.*?\./
/\.(?:exe|msi|dmg|bin|xpi|iso)$/i
/<a [^<>]*href=[\'"]([^\'"]+)[\'"][^<>]*>(((?!/si
/^[0-9]{1,55}$/
/([a-zA-Z--]+)/
/^.{1,10}$/
/<b>(.*)</b>/

.
.
, , ,
,
.
.
.
.
.
.
55 .
.
, 1 10 .
,
.


.
73

7
74


<?php

function myFunction($parameter1, $parameter2)


{
// ( )
// return _
}
?>
1. ,
.
2. -
, ..
"&": function func($p1, &$p2) { }
3. PHP
, PHP 4.3
.
75


$arr = array("a"=>"lemon", "b"=>"apple", "c"=>"orange");
$i = count($arr); -
$k = array_keys($arr); - (array)
$v = array_values($arr); - (array)
list($a1, $a2, $a3) = $v; - ,

if (in_array("lemon", $arr)) {}
$idx = array_search("lemon", $arr); - ,
( )
$s = array_sum(array(0,1,2,3,4,5)); - (int)
$a = array_merge($k, $v, ); - (array)
$a = array_unique($a); -
( ) (array)
$a = asort($arr); - (array)
$a = ksort($arr); - (array)
$a = sort($arr); - (array)

76

/
$stamp = time(); - (. UNIX) (int)
$str = date("d.m.Y"); - (string): D
(Mon-Sun), H (00-23), i (00-59), M
(Jan-Dec), O GMT (+0400), r
RFC822, s (00-59), W (1-53), z
(1-366)
$stamp = mktime($hr, $min, $sec, $mon, $day, $y); -
UNIX (int)
if (checkdate($mon, $day, $y)) {}
(bool)

77


acos($x), asin($x), atan($x),
pi(), cos($x), sin($x), tan($x),
exp($x), log($x), log10($x), pow($x, $y), sqrt($x),
abs($x), ceil($x), floor($x), round($x),
max($v1, $v2, ), min($v1, $v2, ),
rand($min, $max), srand(time())
$val2 = base_convert($val10, 10, 2); -
(str)

78


if (empty($var)) {} TRUE, $var 0, "0", "", NULL,
FALSE, array() (bool)
if (isset($var)) {} TRUE,
$str = gettype($var); - (string)
if (is_array($arr)) {} $arr (bool)
$str = print_r($arr, TRUE); - $arr (string)

settype($a, "integer"); - (bool)


unset($a, $b, ); -
$str = serialize($obj); - // (string)
$obj = unserialize($str); - / /

79

, URL
$url = parse_url("http://mp3:qwerty@mp3.int.ru/search.php?query=1");
// URL (array):
Array (
[scheme] => http
[host] => mp3.int.ru
[user] => mp3
[pass] => qwerty
[path] => /search.php
[query] => query=1
)

$str = urlencode(any_string"); - URL- (string)

<?php
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>
$str = urldecode("%41%46+%34%33"); - URL- (string)
!! $_GET $_REQUEST .

80


$info = gd_info(); - GD (array)
Array (
[GD Version] => bundled (2.0.28 compatible)
[FreeType Support] => 1
[FreeType Linkage] => with freetype
[T1Lib Support] =>
[GIF Read Support] => 1
[GIF Create Support] => 1
[JPG Support] => 1
[PNG Support] => 1
[WBMP Support] => 1
[XBM Support] => 1
[JIS-mapped Japanese Font Support] =>
)

$types = imagetypes(); - (int)


if ($types) {}
: IMG_GIF, IMG_JPG, IMG_PNG, IMG_WBMP.

81


$img = imagecreate(200, 100); - 200100
$img = imagecreatetruecolor(300, 200); -
(16) 300x200 (resource)
$img = imagecreatefromjpeg("my.jpg"); -
JPEG- (resource)
$img = imagecreatefrompng("my.png"); -
PNG- (resource)
imagedestroy($img); -
imagejpeg($img); - JPEG
imagepng($img); - PNG
$info = getimagesize("my.jpg"); -
Array (
[0] => 593
[1] => 639
[2] => 3
[3] => width="593" height="639"
[bits] => 8
[mime] => image/png
)

// ( imagesx($img))
// ( imagesy($img))
// image_type_to_mime_type()
// <IMG>
//
// MIME-

82


$white = imagecolorallocate($img, 255, 255, 255); -
RGB- (int).
.
imagesetpixel($img, $x, $y, $clr); -
imageline($img, $x1, $y1, $x2, $y2, $clr); -
imagearc($img, $cx, $cy, $w, $h, $s, $e, $clr);
imagefilledarc($img, $cx, $cy, $w, $h, $s, $e, $clr, IMG_ARC_PIE);
imageellipse($img, $cx, $cy, $w, $h, $clr); -
imagefilledellipse($img, $cx, $cy, $w, $h, $clr); -
imagerectangle($img, $x1, $y1, $x2, $y2, $clr); -
imagefilledrectangle($img, $x1, $y1, $x2, $y2, $clr); -

imagestring($img, $font, $x, $y, "qwerty", $clr); -
(: 1-5)
imagettftext($img, $sz, $angle, $x, $y, $clr, "arial.ttf", "qwerty"); (UTF8) (TTF)

83

MySQL
$link = mysql_connect("localhost", "user", "pass"); -
MySQL- (resource);
mysql_close($link); - (bool)
mysql_select_db("test"); - test (bool)
$req = mysql_query("select * from users where uid=1000"); -
SQL- (resource)
$n = mysql_num_rows($req); - - SELECT (int)
$n = mysql_affected_rows($link); - -
DELETE/INSERT/REPLACE/UPDATE (int)
mysql_free_result($req); - - (bool)
$arr = mysql_fetch_assoc($req); -
$arr = mysql_fetch_row($req); -
$str = mysql_escape_string("Alex's PC"); -
SQL-

84

8
85


,
.
,
.
class Articles { // c
var $title;
var $author;
var $description;
//
function make_article($t, $a, $d){
$this->title = $t;
$this->author = $a;
$this->description = $d;
}
//
function show_article(){
$art = $this->title . "<br>" .
$this->description .
"<br>: " . $this->author;
echo $art;
}
}
86


,
, ,
.


.
,

. ,
, .
, .

87

9
88

$GLOBALS
$GLOBALS
#1 $GLOBALS
<?php
function test() {
$foo = Local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
?>
:
$foo in global scope: Example content
$foo in current scope: Local variable

89

$_GET
$_POST
$_COOKIE
90

$_GET
<?php
echo ' ' . htmlspecialchars($_GET["name"]) . '!';
?>

, !

91

GET
GET
1. ().
2. POST,
.
3. , , (
).
GET
1. , , (
).
2. , , .

92

$_POST
<?php
echo ' ' . htmlspecialchars($_POST["name"]) . '!';
?>

, !

93

POST
POST
1. ,
.
2.
. , URL.
. POST
!
POST
1. , GET,
.
2. , POST,
(-).

94

$_COOKIE
<?php
echo ', ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>

, !

95

www

http://www.w3schools.com/php/

96

http://www.w3schools.com/
97

http://www.w3schools.com/

98

? ? ?
99

Оценить