PHÁT TRIỂN ỨNG DỤNG WEB
Bài 2: PHP Nâng cao
Nguyễn Hữu Thể
1
Nội dung
▪ PHP Date() Function
▪ PHP Include File
▪ PHP File Handling
▪ PHP File Upload
▪ PHP Cookies
▪ PHP Sessions
▪ PHP Sending E-mails
▪ PHP Error Handling
▪ PHP Exception Handling
2
PHP Date() Function
− Hàm date() định dạng một timestamp để có thể đọc ngày/ giờ. − Timestamp là một chuỗi ký tự, biểu thị ngày tháng và/ hoặc thời
gian. ❖ Syntax
3
PHP Date() - Format the Date
− Tham số format trong hàm date() để định dạng ngày/ giờ.
▪ d - Đại diện các ngày của tháng (01-31)
▪ m - Đại diện một tháng (01-12)
▪ Y - Đại diện một năm (bốn chữ số)
− Các ký tự: "/", ".", hoặc "-" cũng có thể được chèn vào
4
PHP Date() - Adding a Timestamp
− Tham số tùy chọn timestamp trong hàm date() xác định một dấu
thời gian.
− Nếu không chỉ định timestamp, ngày/giờ hiện tại sẽ được sử
dụng.
− Hàm mktime() trả về Unix timestamp cho một ngày.
❖ Syntax for mktime()
5
PHP Date() - Adding a Timestamp
− Để đến một ngày trong tương lai, thêm đối số ngày của mktime()
6
PHP Include File
− Chèn nội dung của file PHP vào một file PHP, sử dụng hàm:
▪ include(“filename”) hoặc require(“filename”)
▪ Cách khác: include 'filename’ hoặc require 'filename'
− Hai hàm này giống nhau, trừ cách xử lý lỗi:
▪ include() tạo ra một cảnh báo, kịch bản sẽ tiếp tục thực hiện
▪ require() tạo ra một lỗi, và kịch bản sẽ ngừng
− Tạo các hàm, các thành phần tái sử dụng trên nhiều trang. − Tạo các file header, footer, menu chuẩn cho tất cả các trang.
▪ Khi header cần cập nhật, chỉ cần cập nhật các file,
▪ Khi thêm một trang mới vào trang web, chỉ thay đổi file menu (thay vì cập nhật các liên kết trên tất cả các trang web).
7
PHP include() Function
− Hàm include() lấy nội dung trong một file chỉ định vào file
hiện tại.
− Nếu lỗi xảy ra, hàm include() tạo ra một cảnh báo, nhưng kịch
bản sẽ tiếp tục thực hiện.
❖ Example − include file "header.php" vào một trang, sử dụng hàm include()
8
PHP include() Function
− file "menu.php", nên sử dụng trên tất cả các trang
− Các trang trong Web site nên include file menu này.
9
PHP include() Function
− Nếu lỗi xảy ra, hàm include() tạo ra một cảnh báo, nhưng kịch
bản sẽ tiếp tục thực hiện.
10
PHP require() Function
− Nếu lỗi xảy ra, hàm require() sẽ thông báo lỗi, và kịch bản sẽ
dừng lại.
11
PHP require() Function
− Lưu ý: nên sử dụng hàm require(), vì kịch bản không nên tiếp tục
thực hiện sau khi xuất hiện lỗi.
12
PHP File Handling
❖ Opening a File − Hàm fopen(): mở file trong PHP. − Tham số đầu tiên chứa tên file được mở và tham số thứ hai quy
định mode của file được mở ra
13
PHP File Handling
− File có thể được mở theo một trong các mode:
14
PHP File Handling
− Tạo ra một thông báo nếu hàm fopen() không thể mở file
15
Closing a File
− Hàm fclose(): đóng một file đã mở.
16
Check End-of-file
− Hàm feof() kiểm tra nếu kết thúc file (“end-of-file” - EOF). − Dùng kiểm tra các dữ liệu không rõ chiều dài.
❖ Lưu ý: Không thể đọc từ file đã mở trong mode w, a, x.
17
Reading a File Line by Line
− Hàm fgets(): đọc một dòng từ một file. − Sau khi gọi hàm này, con trỏ file đã di chuyển đến dòng kế tiếp.
18
Reading a File Character by Character
− Hàm fgetc(): đọc một ký tự đơn từ một file. − Sau khi gọi hàm này, con trỏ file di chuyển đến ký tự tiếp theo.
19
PHP File Upload
− Upload files to the server
❖ Configure The "php.ini" File − First, ensure that PHP is configured to allow file uploads. − In your "php.ini" file, search for the file_uploads directive, and
set it to On:
file_uploads = On
20
PHP File Upload - Create The HTML Form
− Create an HTML form that allow users to choose the image file
they want to upload
21
PHP File Upload - Create The Upload File PHP
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) {
echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1;
} else {
echo "File is not an image."; $uploadOk = 0;
}
} ?>
22
File Upload - Check if File Already Exists
− Now we can add some restrictions. − First, we will check if the file already exists in the "uploads"
folder. If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists if (file_exists($target_file)) {
echo "Sorry, file already exists."; $uploadOk = 0;
}
23
File Upload - Limit File Size
− The file input field in our HTML form above is named
"fileToUpload".
− Check the size of the file. If the file is larger than 500KB, an
error message is displayed, and $uploadOk is set to 0
// Check file size if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large."; $uploadOk = 0;
}
24
File Upload - Limit File Type
− The code below only allows users to upload JPG, JPEG, PNG,
and GIF files.
− All other file types gives an error message before setting
$uploadOk to 0
// Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0;
}
25
The complete "upload.php"
File Upload - Limit File Type
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) {
echo "File is not an image."; $uploadOk = 0;
echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else {
}
} if (file_exists($target_file)) {
echo "Sorry, file already exists."; $uploadOk = 0;
} if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large."; $uploadOk = 0;
} if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0;
} if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; 26 }
} ?>
PHP Cookies
− Cookie thường được sử dụng để xác định một người sử dụng.
▪ Một cookie là một file nhỏ mà server nhúng trên máy tính của
người dùng.
▪ Mỗi lần máy tính yêu cầu một trang với một trình duyệt, nó sẽ
gửi kèm theo các cookie. − How to Create a Cookie?
▪ Hàm setcookie() được sử dụng để thiết lập một cookie.
− Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
✓ Hàm setcookie() cần đặt trước thẻ .
27
Lập trình ứng dụng mạng
PHP Cookies – Tạo cookie
− Tạo ra một cookie có tên là "user" và gán giá trị "Alex Porter".
Thiết lập cho cookie này sẽ hết hạn sau một giờ:
− Lưu ý: giá trị của cookie được tự động mã hoá URLencoded khi
gửi cookie, và tự động giải mã khi nhận được.
28
PHP Cookies – Ví dụ
− Thiết lập thời gian hết hạn của cookie bằng cách sử dụng giây.
− Trong ví dụ trên, thời gian hết hạn của cookie là một tháng
(60 sec * 60 min * 24 hours * 30 days)
29
How to Retrieve a Cookie Value?
− Biến $_COOKIE: lấy một giá trị cookie.
30
How to Retrieve a Cookie Value?
− Sử dụng hàm isset() để tìm cookie nếu nó đã được thiết lập
31
How to Delete a Cookie?
− Khi xóa một cookie, nên đảm bảo rằng nó đã hết hạn.
32
What if a Browser Does NOT Support Cookies?
− Nếu trình duyệt không hỗ trợ cookies => kết nối các dữ liệu
thông qua form.
33
PHP Sessions
− Biến session: lưu trữ, hoặc thay đổi các thiết lập cho một phiên
người dùng.
− Có tác dụng cho tất cả các trang trong một ứng dụng. − Lưu trữ thông tin người dùng trên server − Thông tin session là tạm thời và sẽ bị xóa sau khi người dùng rời
khỏi trang web.
− Session tạo ra một id duy nhất (UID) cho mỗi client. − UID được lưu trữ trong một cookie hoặc là gửi kèm trong URL.
34
Starting a PHP Session
− Hàm session_start(): khởi động session.
Lưu ý: hàm session_start() cần đặt trước thẻ
Session variables are set.
35
Storing a Session Variable
− $_SESSION: lưu trữ biến session
36
Destroying a Session
− Xóa dữ liệu session, sử dụng unset() hoặc session_destroy(). − Hàm unset(): giải phóng bộ nhớ biến session
− Hàm session_destroy()
− Lưu ý: hàm session_destroy() sẽ thiết lập lại session và sẽ mất tất
cả dữ liệu session đã được lưu trữ.
37
Destroying a Session
// destroy the session session_destroy(); ?>
38
PHP Filters
− Validating data = Determine if the data is in proper form. − Sanitizing data = Remove any illegal character from the data.
❖ Why Use Filters? − Many web applications receive external input. External
input/data can be:
▪ User input from a form
▪ Cookies
▪ Web services data
▪ Server variables
▪ Database query results
39
PHP Filters - PHP filter_var() Function
− The filter_var() function both validate and sanitize data. − The filter_var() function filters a single variable with a
specified filter. It takes two pieces of data:
▪ The variable you want to check
▪ The type of check to use
EX: Sanitize a String: Remove all HTML tags from a string
Hello World!
Hello World!"; $newstr = filter_var($str, FILTER_SANITIZE_STRING); echo $newstr;
?>
40
PHP Filters - PHP filter_var() Function
❖ Validate an Integer − If $int is an integer, the output of the code below will be:
"Integer is valid".
− If $int is not an integer, the output will be: "Integer is not
valid"
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
} ?>
Integer is valid
41
PHP Filters - PHP filter_var() Function
❖ Validate an IP Address − Check if the variable $ip is a valid IP address
if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {
echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
} ?>
127.0.0.1 is a valid IP address
42
PHP Filters - PHP filter_var() Function
❖ Sanitize and Validate an Email Address − Remove all illegal characters from the $email variable, then
check if it is a valid email address
// Remove all illegal characters from email $email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
} ?>
43
PHP Filters - PHP filter_var() Function
❖ Sanitize and Validate a URL − Remove all illegal characters from a URL, then check if $url is
a valid URL:
// Remove all illegal characters from a url $url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
} ?>
44
PHP Sending E-mails
❖ The PHP mail() Function − Hàm mail() được sử dụng để gửi email. ❖ Configuration: php.ini Default Name
Description
Changeable
"0"
PHP_INI_PERDIR
mail.add_x_he ader
Add X-PHP-Originating-Script that will include UID of the script followed by the filename. For PHP 5.3.0 and above
mail.log
NULL
PHP_INI_PERDIR
The path to a log file that will log all mail() calls. Log include full path of script, line number, To address and headers. For PHP 5.3.0 and above
SMTP
"localhost" Windows only: The DNS name or IP address of the SMTP server PHP_INI_ALL
smtp_port
"25"
PHP_INI_ALL
Windows only: The SMTP port number. For PHP 4.3.0 and above
sendmail_from NULL
PHP_INI_ALL
Windows only: Specifies the "from" address to be used when sending mail from mail()
PHP_INI_SYSTEM
sendmail_path "/usr/sbin/s endmail -t -i"
Specifies where the sendmail program can be found. This directive works also under Windows. If set, SMTP, smtp_port and sendmail_from are ignored
45
PHP Sending E-mails
46
PHP Simple E-Mail
− Sử dụng hàm mail() để gửi một email văn bản.
47
PHP Mail Form
− Tạo một form phản hồi ý kiến (feedback) trên trang web.
48
Lập trình ứng dụng mạng
PHP 5 String Functions
Function addcslashes()
Description Returns a string with backslashes in front of the specified characters
addslashes()
Returns a string with backslashes in front of predefined characters
bin2hex()
Converts a string of ASCII characters to hexadecimal values
chop()
Removes whitespace or other characters from the right end of a string
chr() chunk_split() convert_cyr_string()
Returns a character from a specified ASCII value Splits a string into a series of smaller parts Converts a string from one Cyrillic character-set to another
convert_uudecode() convert_uuencode() count_chars() crc32() crypt() echo() explode() fprintf() get_html_translation_table()
Decodes a uuencoded string Encodes a string using the uuencode algorithm Returns information about characters used in a string Calculates a 32-bit CRC for a string One-way string hashing Outputs one or more strings Breaks a string into an array Writes a formatted string to a specified output stream Returns the translation table used by htmlspecialchars() and htmlentities()
49
PHP 5 String Functions (2)
Function hebrev() hebrevc()
Description
Converts Hebrew text to visual text
Converts Hebrew text to visual text and new lines (\n) into
hex2bin()
Converts a string of hexadecimal values to ASCII characters
html_entity_decode() htmlentities() htmlspecialchars_decode()
Converts HTML entities to characters Converts characters to HTML entities Converts some predefined HTML entities to characters
htmlspecialchars() implode() join() lcfirst() levenshtein() localeconv()
Converts some predefined characters to HTML entities Returns a string from the elements of an array Alias of implode() Converts the first character of a string to lowercase Returns the Levenshtein distance between two strings Returns locale numeric and monetary formatting information
ltrim()
Removes whitespace or other characters from the left side of a string
md5() md5_file()
Calculates the MD5 hash of a string Calculates the MD5 hash of a file
50
PHP 5 String Functions (3)
Function metaphone() money_format() nl_langinfo() nl2br()
Description Calculates the metaphone key of a string Returns a string formatted as a currency string Returns specific local information Inserts HTML line breaks in front of each newline in a string
number_format() ord() parse_str() print() printf() quoted_printable_decode()
Formats a number with grouped thousands Returns the ASCII value of the first character of a string Parses a query string into variables Outputs one or more strings Outputs a formatted string Converts a quoted-printable string to an 8-bit string
quoted_printable_encode()
Converts an 8-bit string to a quoted printable string
quotemeta() rtrim()
Quotes meta characters Removes whitespace or other characters from the right side of a string
setlocale() sha1() sha1_file()
Sets locale information Calculates the SHA-1 hash of a string Calculates the SHA-1 hash of a file
51
PHP 5 String Functions (4)
Function similar_text() soundex() sprintf() sscanf() str_getcsv() str_ireplace() str_pad() str_repeat() str_replace() str_rot13() str_shuffle() str_split() str_word_count() strcasecmp() strchr()
Description Calculates the similarity between two strings Calculates the soundex key of a string Writes a formatted string to a variable Parses input from a string according to a format Parses a CSV string into an array Replaces some characters in a string (case-insensitive) Pads a string to a new length Repeats a string a specified number of times Replaces some characters in a string (case-sensitive) Performs the ROT13 encoding on a string Randomly shuffles all characters in a string Splits a string into an array Count the number of words in a string Compares two strings (case-insensitive) Finds the first occurrence of a string inside another string (alias of strstr())
strcmp() strcoll() strcspn()
Compares two strings (case-sensitive) Compares two strings (locale based string comparison) Returns the number of characters found in a string before any part of some specified characters are found
52
PHP 5 String Functions (5)
Function strip_tags() stripcslashes() stripslashes() stripos()
stristr()
strlen() strnatcasecmp()
strnatcmp()
strncasecmp()
Description Strips HTML and PHP tags from a string Unquotes a string quoted with addcslashes() Unquotes a string quoted with addslashes() Returns the position of the first occurrence of a string inside another string (case-insensitive) Finds the first occurrence of a string inside another string (case- insensitive) Returns the length of a string Compares two strings using a "natural order" algorithm (case- insensitive) Compares two strings using a "natural order" algorithm (case- sensitive) String comparison of the first n characters (case-insensitive)
strncmp()
String comparison of the first n characters (case-sensitive)
strpbrk() strpos()
Searches a string for any of a set of characters Returns the position of the first occurrence of a string inside another 53 string (case-sensitive)
PHP 5 String Functions (6)
Function strrchr() strrev() strripos()
strrpos()
strspn()
strstr()
strtok() strtolower() strtoupper() strtr() substr() substr_compare()
Description Finds the last occurrence of a string inside another string Reverses a string Finds the position of the last occurrence of a string inside another string (case-insensitive) Finds the position of the last occurrence of a string inside another string (case-sensitive) Returns the number of characters found in a string that contains only characters from a specified charlist Finds the first occurrence of a string inside another string (case- sensitive) Splits a string into smaller strings Converts a string to lowercase letters Converts a string to uppercase letters Translates certain characters in a string Returns a part of a string Compares two strings from a specified start position (binary safe and optionally case-sensitive)
54
PHP 5 String Functions (7)
Function substr_count() substr_replace() trim()
ucfirst() ucwords()
vfprintf() vprintf() vsprintf() wordwrap()
Description Counts the number of times a substring occurs in a string Replaces a part of a string with another string Removes whitespace or other characters from both sides of a string Converts the first character of a string to uppercase Converts the first character of each word in a string to uppercase Writes a formatted string to a specified output stream Outputs a formatted string Writes a formatted string to a variable Wraps a string to a given number of characters
55
PHP Error Handling
− Ba phương pháp xử lý lỗi:
▪ Function “die()”
▪ Custom Error Handler
▪ Error Report levels
56
Lập trình ứng dụng mạng
Basic Error Handling: Using the die() function
− Mở file văn bản:
− Nếu file không tồn tại, thông báo lỗi như sau:
57
Lập trình ứng dụng mạng
Basic Error Handling: Using the die() function
− Để tránh nhận thông báo lỗi như trên, nên kiểm tra file tồn tại
trước khi truy cập
− Nếu file không tồn tại, thông báo lỗi như sau:
58
Lập trình ứng dụng mạng
Basic Error Handling: Creating a Custom Error Handler
− Tạo ra một hàm và gọi nó khi có lỗi xảy ra trong PHP.
❖ Syntax
error_function(error_level, error_message, error_file, error_line, error_context)
59
Lập trình ứng dụng mạng
Basic Error Handling: Creating a Custom Error Handler
error_function(error_level, error_message, error_file, error_line, error_context)
60
Lập trình ứng dụng mạng
Basic Error Handling: Error Report levels
− Các kiễu báo lỗi:
61
Lập trình ứng dụng mạng
Basic Error Handling: Error Report levels
− Tạo ra một hàm xử lý lỗi
62
Lập trình ứng dụng mạng
Set Error Handler
− Xử lý lỗi mặc định cho PHP được xây dựng trong error handler.
set_error_handler("customError");
− Example: kiểm tra biến đầu ra có tồn tại không
− Output:
63
Lập trình ứng dụng mạng
Trigger an Error
− Hàm trigger_error(): kích hoạt lỗi khi dữ liệu nhập không hợp lệ.
− Output
64
Lập trình ứng dụng mạng
Trigger an Error
− Các kiểu lỗi có thể:
▪ E_USER_ERROR - Tạo run-time error. Lỗi không thể phục hồi
thì các kịch bản phải dừng lại
▪ E_USER_WARNING - Tạo run-time warning. Kịch bản thực thi
không phải dừng lại
▪ E_USER_NOTICE - Tạo run-time notice. Ghi chú các khi tìm
thấy lỗi
65
Lập trình ứng dụng mạng
Trigger an Error
− Output
66
Lập trình ứng dụng mạng
PHP Exception Handling
− Trường hợp ngoại lệ được sử dụng để thay đổi luồng mặc định
của một kịch bản nếu một lỗi nào đó xảy ra
− Các trường hợp có thể xảy ra khi một ngoại lệ được kích hoạt:
▪ Trạng thái code hiện tại được lưu trữ
▪ Code thực thi sẽ chuyển sang một hàm xử lý ngoại lệ
▪ Tùy thuộc vào tình huống xử lý, sau đó có thể:
• Tiếp tục thực hiện,
• Chấm dứt việc thực hiện kịch bản
• Hoặc tiếp tục kịch bản từ một vị trí khác trong code
67
Lập trình ứng dụng mạng
Basic Use of Exceptions
− Khi một ngoại lệ được ném ra, các code bên dưới nó sẽ không
được thực thi, và PHP sẽ cố gắng tìm "catch" phù hợp.
− Nếu không bắt ngoại lệ => hiện thông báo "Uncaught Exception"
68
Lập trình ứng dụng mạng
Try, throw and catch
− Mã lệnh thích hợp xử lý ngoại lệ bao gồm:
▪ Try - sử dụng ngoại lệ trong khối "try". Nếu trường hợp ngoại lệ không kích hoạt, mã lệnh sẽ tiếp tục. Nếu trường hợp ngoại lệ xuất hiện, ngoại lệ là "throw"
▪ Throw - Đây là cách kích hoạt ngoại lệ. Mỗi "throw" phải có ít
nhất một "catch"
▪ Catch - Một khối "catch" lấy một ngoại lệ và tạo ra một đối
tượng có chứa các thông tin ngoại lệ
69
Lập trình ứng dụng mạng
Try, throw and catch
70
Lập trình ứng dụng mạng
Creating a Custom Exception Class
− Tạo class với các hàm có thể được gọi khi một ngoại lệ xảy ra.
71