PHP Include File▪ 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ản
Trang 1PHÁT TRIỂN ỨNG DỤNG WEB
Bài 2:
PHP Nâng cao
Trang 3PHP Date() Function
gian
Trang 4PHP Date() - Format the Date
▪ 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
Trang 5PHP Date() - Adding a Timestamp
thời gian
dụng
Trang 6PHP Date() - Adding a Timestamp
Trang 7PHP Include File
▪ 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
Trang 9PHP include() Function
Trang 10PHP 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.
Trang 11PHP 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.
Trang 12PHP 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.
Trang 13PHP File Handling
định mode của file được mở ra
Trang 14PHP File Handling
Trang 15PHP File Handling
Trang 16Closing a File
Trang 17Check End-of-file
❖Lưu ý: Không thể đọc từ file đã mở trong mode w, a, x.
Trang 18Reading a File Line by Line
Trang 19Reading a File Character by Character
Trang 20PHP File Upload
❖Configure The "php.ini" File
set it to On:
file_uploads = On
Trang 21PHP File Upload - Create The HTML Form
they want to upload
<!DOCTYPE html >
<html>
<body>
< form action="upload_process.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type ="file" name ="fileToUpload" id ="fileToUpload">
<input type ="submit" value ="Upload Image" name ="submit">
</form>
</body>
</html>
Trang 22PHP File Upload - Create The Upload File PHP
<?php
$target_dir = "uploads/" ;
$target_file = $target_dir basename( $_FILES [ "fileToUpload" ][ "name" ]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION ));
// Check if image file is a actual image or fake image
if(isset( $_POST [ "submit" ])) {
$check = getimagesize( $_FILES [ "fileToUpload" ][ "tmp_name" ]);
Trang 23File Upload - Check if File Already Exists
− First, we will check if the file already exists in the "uploads" folder If it does, an error message is displayed, and
Trang 24File 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 500 KB, an error message is displayed, and $uploadOk is set to 0
// Check file size
if ( $_FILES [ "fileToUpload" ][ "size" ] > 500 000) {
echo "Sorry, your file is too large." ;
$uploadOk = 0;
}
Trang 25File Upload - Limit File Type
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;
Trang 26File Upload - Limit File Type
if ( isset ( $_POST ["submit"])) {
$check = getimagesize( $_FILES ["fileToUpload"]["tmp_name"]);
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
if (move_uploaded_file( $_FILES ["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file " basename( $_FILES ["fileToUpload"]["name"]) " has been uploaded.";
The complete "upload.php"
Trang 27PHP Cookies
▪ 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.
▪ Hàm setcookie() được sử dụng để thiết lập một cookie.
setcookie(name, value, expire, path, domain, secure, httponly);
Trang 28PHP 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ờ:
gửi cookie, và tự động giải mã khi nhận được
Trang 29PHP Cookies – Ví dụ
(60 sec * 60 min * 24 hours * 30 days)
Trang 30How to Retrieve a Cookie Value?
Trang 31How to Retrieve a Cookie Value?
Trang 32How to Delete a Cookie?
<?php
// set the expiration date to one hour ago
setcookie( "user" , "" , time() - 3600 );
Trang 33What if a Browser Does NOT Support Cookies?
thông qua form
Trang 34PHP Sessions
người dùng
− Lưu trữ thông tin người dùng trên server
khỏi trang web
Trang 35// Set session variables
$_SESSION [ "favcolor" ] = "green" ;
Lưu ý: hàm
session_start() cần đặt trước thẻ <html>
Trang 36Storing a Session Variable
− $_SESSION: lưu trữ biến session
Trang 37Destroying a Session
Trang 39PHP 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:
Trang 40PHP 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
<?php
$str = "<h1>Hello World!</h1>" ;
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
EX: Sanitize a String: Remove all HTML tags from a string
Trang 41PHP Filters - PHP filter_var() Function
if (!filter_var($int, FILTER_VALIDATE_INT) === false) {
echo ( "Integer is valid" );
Trang 42PHP Filters - PHP filter_var() Function
Trang 43PHP 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
<?php
$email = “nguyenvana@example.com" ;
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
Trang 44PHP 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:
<?php
$url = "https://www.google.com" ;
// 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 {
Trang 45PHP Sending E-mails
mail.add_x_he
ader
"0" Add X-PHP-Originating-Script that will include UID of the
script followed by the filename For PHP 5.3.0 and above
PHP_INI_PERDIR
mail.log NULL 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
PHP_INI_PERDIR
SMTP "localhost" Windows only: The DNS name or IP address of the SMTP server PHP_INI_ALL
Trang 46PHP Sending E-mails
Trang 47PHP Simple E-Mail
Trang 48PHP Mail Form
Trang 49PHP 5 String Functions
Function Description
addcslashes() 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() Returns a character from a specified ASCII value
chunk_split() Splits a string into a series of smaller parts
convert_cyr_string() Converts a string from one Cyrillic character-set to another
convert_uudecode() Decodes a uuencoded string
convert_uuencode() Encodes a string using the uuencode algorithm
count_chars() Returns information about characters used in a string
Trang 50PHP 5 String Functions (2)
Function Description
hebrev() Converts Hebrew text to visual text
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
hex2bin() Converts a string of hexadecimal values to ASCII characters
html_entity_decode() Converts HTML entities to characters
htmlentities() Converts characters to HTML entities
htmlspecialchars_decode() Converts some predefined HTML entities to characters
htmlspecialchars() Converts some predefined characters to HTML entities
implode() Returns a string from the elements of an array
join() Alias of implode()
lcfirst() Converts the first character of a string to lowercase
levenshtein() Returns the Levenshtein distance between two strings
localeconv() Returns locale numeric and monetary formatting information
Trang 51PHP 5 String Functions (3)
Function Description
metaphone() Calculates the metaphone key of a string
money_format() Returns a string formatted as a currency string
nl_langinfo() Returns specific local information
nl2br() Inserts HTML line breaks in front of each newline in a string
number_format() Formats a number with grouped thousands
ord() Returns the ASCII value of the first character of a string
parse_str() Parses a query string into variables
print() Outputs one or more strings
printf() Outputs a formatted string
quoted_printable_decode() Converts a quoted-printable string to an 8-bit string
quoted_printable_encode() Converts an 8-bit string to a quoted printable string
Trang 52PHP 5 String Functions (4)
Function Description
similar_text() Calculates the similarity between two strings
soundex() Calculates the soundex key of a string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_getcsv() Parses a CSV string into an array
str_ireplace() Replaces some characters in a string (case-insensitive)
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_rot13() Performs the ROT13 encoding on a string
str_shuffle() Randomly shuffles all characters in a string
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
strchr() Finds the first occurrence of a string inside another string (alias of strstr())
Trang 53PHP 5 String Functions (5)
string (case-insensitive)
(case-insensitive)
(case-insensitive)
(case-sensitive)
Trang 54PHP 5 String Functions (6)
string (case-insensitive)
string (case-sensitive)
only characters from a specified charlist
(case-sensitive)
Trang 55PHP 5 String Functions (7)
Function Description
string
uppercase
Trang 56PHP Error Handling
▪ Function “die()”
▪ Custom Error Handler
▪ Error Report levels
Trang 57Basic Error Handling: Using the die() function
Trang 58Basic Error Handling: Using the die() function
trước khi truy cập
Trang 59Basic Error Handling: Creating a Custom Error Handler
error_context)
Trang 60Basic Error Handling: Creating a Custom Error Handler
error_context)
Trang 61Basic Error Handling: Error Report levels
Trang 62Basic Error Handling: Error Report levels
Trang 63Set Error Handler
set_error_handler("customError");
− Example: kiểm tra biến đầu ra có tồn tại không
Trang 64Trigger an Error
Trang 66Trigger an Error
Trang 67PHP Exception Handling
của một kịch bản nếu một lỗi nào đó xảy ra
• 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
Trang 68Basic Use of Exceptions
được thực thi, và PHP sẽ cố gắng tìm "catch" phù hợp
Trang 69Try, throw and catch
▪ 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ệ
Trang 70Try, throw and catch
Trang 71Creating a Custom Exception Class