1. Trang chủ
  2. » Công Nghệ Thông Tin

Bài giảng Phát triển ứng dụng Web (GV Nguyễn Hữu Thể) Bài 2

71 10 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 71
Dung lượng 1,01 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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 1

PHÁT TRIỂN ỨNG DỤNG WEB

Bài 2:

PHP Nâng cao

Trang 3

PHP Date() Function

gian

Trang 4

PHP 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 5

PHP Date() - Adding a Timestamp

thời gian

dụng

Trang 6

PHP Date() - Adding a Timestamp

Trang 7

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ả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 9

PHP include() Function

Trang 10

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.

Trang 11

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.

Trang 12

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.

Trang 13

PHP File Handling

định mode của file được mở ra

Trang 14

PHP File Handling

Trang 15

PHP File Handling

Trang 16

Closing a File

Trang 17

Check End-of-file

Lưu ý: Không thể đọc từ file đã mở trong mode w, a, x.

Trang 18

Reading a File Line by Line

Trang 19

Reading a File Character by Character

Trang 20

PHP File Upload

Configure The "php.ini" File

set it to On:

file_uploads = On

Trang 21

PHP 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 22

PHP 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 23

File 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 24

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 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 25

File 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 26

File 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 27

PHP 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 28

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ờ:

gửi cookie, và tự động giải mã khi nhận được

Trang 29

PHP Cookies – Ví dụ

(60 sec * 60 min * 24 hours * 30 days)

Trang 30

How to Retrieve a Cookie Value?

Trang 31

How to Retrieve a Cookie Value?

Trang 32

How to Delete a Cookie?

<?php

// set the expiration date to one hour ago

setcookie( "user" , "" , time() - 3600 );

Trang 33

What if a Browser Does NOT Support Cookies?

thông qua form

Trang 34

PHP 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 36

Storing a Session Variable

− $_SESSION: lưu trữ biến session

Trang 37

Destroying a Session

Trang 39

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:

Trang 40

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

<?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 41

PHP Filters - PHP filter_var() Function

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {

echo ( "Integer is valid" );

Trang 42

PHP Filters - PHP filter_var() Function

Trang 43

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

<?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 44

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:

<?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 45

PHP 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 46

PHP Sending E-mails

Trang 47

PHP Simple E-Mail

Trang 48

PHP Mail Form

Trang 49

PHP 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 50

PHP 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 51

PHP 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 52

PHP 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 53

PHP 5 String Functions (5)

string (case-insensitive)

(case-insensitive)

(case-insensitive)

(case-sensitive)

Trang 54

PHP 5 String Functions (6)

string (case-insensitive)

string (case-sensitive)

only characters from a specified charlist

(case-sensitive)

Trang 55

PHP 5 String Functions (7)

Function Description

string

uppercase

Trang 56

PHP Error Handling

▪ Function “die()”

▪ Custom Error Handler

▪ Error Report levels

Trang 57

Basic Error Handling: Using the die() function

Trang 58

Basic Error Handling: Using the die() function

trước khi truy cập

Trang 59

Basic Error Handling: Creating a Custom Error Handler

error_context)

Trang 60

Basic Error Handling: Creating a Custom Error Handler

error_context)

Trang 61

Basic Error Handling: Error Report levels

Trang 62

Basic Error Handling: Error Report levels

Trang 63

Set Error Handler

set_error_handler("customError");

Example: kiểm tra biến đầu ra có tồn tại không

Trang 64

Trigger an Error

Trang 66

Trigger an Error

Trang 67

PHP 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 68

Basic Use of Exceptions

được thực thi, và PHP sẽ cố gắng tìm "catch" phù hợp

Trang 69

Try, 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 70

Try, throw and catch

Trang 71

Creating a Custom Exception Class

Ngày đăng: 30/10/2021, 05:15

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

🧩 Sản phẩm bạn có thể quan tâm

w