Giới thiệu về PHP− PHP : Rasmus Lerdorf in 1994 được phát triển để phát sinh các form đăng nhập sử dụng giao thức HTTP của Unix − PHP 2 1995 : Chuyển sang ngôn ngữ script xử lý trên ser
Trang 1PHÁT TRIỂN ỨNG DỤNG WEB
Bài 1:
PHP Cơ bản
Nguyễn Hữu Thể
Trang 2Nội dung
▪ Giới thiệu PHP
▪ Cơ chế hoạt động của WebServer
▪ Cú pháp & Quy ước trong PHP
Trang 3Giới thiệu về PHP
− PHP : Rasmus Lerdorf in 1994 (được phát triển để phát sinh các form
đăng nhập sử dụng giao thức HTTP của Unix)
− PHP 2 (1995) : Chuyển sang ngôn ngữ script xử lý trên server Hỗ trợ
CSDL, Upload File, biến, mảng, hàm đệ quy, câu điều kiện, …
− PHP 3 (1998) : Hỗ trợ ODBC, đa hệ điều hành , giao thức email
(SNMP, IMAP)
− PHP 4 (2000) : Parser đổi tên thành Zend Engine Bổ sung các tính
năng bảo mật cho PHP
− PHP 5 (2005) : Bổ sung Zend Engine II hỗ trợ lập trình HĐT , XML ,
SOAP cho Web Services, SQLite
− PHP 7 (2015): Cải thiện hiệu năng, tính năng ngôn ngữ mới
Trang 4Giới thiệu về PHP – Ưu điểm 1
programming language we know (https://w3techs.com/technologies/details/pl-php/all/all)
Popular sites using PHP
Trang 5Giới thiệu về PHP – Ưu điểm 2
Trang 6Cơ chế hoạt động của WebServer
6 7
Trang 8− PHP là viết tắt của PHP Hypertext Preprocessor
Solid, PostgreSQL, SQL Server,…)
Trang 9PHP
Trang 10PHP + MySQL
trong Windows, Unix
Trang 12PHP Syntax
− Một khối PHP scripting bắt đầu với <?php và kết thúc bằng ?>
PHP
Trang 13Comments in PHP
− Sử dụng / / để tạo ra một comment hoặc /* và */ để tạo ra một khối comment
Trang 14PHP Variables
− Bắt đầu với ký hiệu $
Trang 15PHP is a Loosely Typed Language
− PHP tự động chuyển kiểu dữ liệu biến , tùy thuộc vào giá trị của nó
Trang 16Naming Rules for Variables
− Tên biến: bắt đầu bằng một chữ cái hoặc dấu gạch dưới "_"
− Tên biến chỉ có thể chứa các ký tự chữ-số và gạch dưới (a-z,
A-Z, 0-9, and _ )
Trang 17PHP String Variables
Trang 18echo and print
echo or echo().
echo "Hello world!<br>";
− The print statement can be used with or without parentheses:
print or print()
print "I'm about to learn PHP!";
Trang 19Data Types
− Variables can store data of different types, and different data
types can do different things
Trang 20The Concatenation Operator
− Sử dụng dấu (.) để nối hai chuỗi với nhau
Trang 21The strlen() function
Trang 22The strpos() function
▪ Nếu kết quả được tìm thấy, hàm trả về vị trí của ký tự đầu tiên
▪ Nếu không tìm thấy, nó sẽ trả về FALSE.
− Ví dụ: tìm chuỗi "world" trong chuỗi "Hello world!":
Trang 23PHP Operators
− Toán tử được sử dụng để tính toán giá trị biểu thức
Trang 24PHP Operators
Trang 25PHP Operators
Trang 26PHP Operators
Trang 27Conditional Statements
khác nhau dựa trên các điều kiện khác nhau
Trang 28The if Statement
Trang 29The if else Statement
lệnh khác nếu điều kiện sai
Trang 30The if elseif else Statement
Trang 31The PHP Switch Statement
nhau
Trang 32The PHP Switch Statement
Trang 34The while loop
Trang 35The while loop
Trang 36The do while Statement
− Thực hiện khối mã một lần, sau đó nó sẽ kiểm tra điều kiện, và lặp lại vòng lặp trong khi điều kiện là đúng
Trang 37The do while Statement
Trang 38For Loops
đến khi một điều kiện quy định là đúng
để FALSE, vòng lặp kết thúc.
Trang 39For Loops
Trang 40foreach
Trang 41The foreach loop
Trang 42PHP Functions
Trang 43PHP Functions
Trang 44PHP Functions - Adding parameters
Trang 45PHP Functions - Adding parameters
Trang 46PHP Functions - Return values
− Để cho phép hàm trả về giá trị, sử dụng lệnh return.
Trang 47PHP Arrays
arrays
Trang 48Indexed Arrays
▪ Chỉ mục được gán tự động (chỉ số bắt đầu từ 0)
▪ Chỉ mục được gán bằng tay
Trang 49$cars = array ( "Volvo" , "BMW" , "Toyota" );
echo "I like " $cars[ 0 ] ", " $cars[ 1 ] " and " $cars[ 2 ] "." ;
Trang 50Indexed Arrays - Get The Length of an Array
Trang 51Indexed Arrays - Print all the values of an indexed array
Trang 52Associative Arrays
Trang 53Associative Arrays - EX
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
echo "Peter is " $age[ 'Peter' ] " years old." ;
?>
Peter is 35 years old.
Trang 54Associative Arrays - Print all the values
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
foreach ($age as $x => $x_value) {
echo "Key=" $x ", Value=" $x_value;
echo "<br>" ;
}
?>
Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43
Trang 56Multidimensional Arrays (Two-dimensional Arrays)
three-dimensional array is an array of arrays of arrays).
Trang 57two-Multidimensional Arrays (Two-dimensional Arrays)
echo $cars[ 0 ][ 0 ] ": In stock: ".$cars[ 0 ][ 1 ] ", sold: ".$cars[ 0 ][ 2 ] ".<br>";
echo $cars[ 1 ][ 0 ] ": In stock: ".$cars[ 1 ][ 1 ] ", sold: ".$cars[ 1 ][ 2 ] ".<br>";
echo $cars[ 2 ][ 0 ] ": In stock: ".$cars[ 2 ][ 1 ] ", sold: ".$cars[ 2 ][ 2 ] ".<br>";
echo $cars[ 3 ][ 0 ] ": In stock: ".$cars[ 3 ][ 1 ] ", sold: ".$cars[ 3 ][ 2 ] ".<br>";
?>
Volvo: In stock: 22, sold: 18.
Trang 58Multidimensional Arrays (Two-dimensional Arrays)
<?php
//displaying array elements at once using for loop.
echo "<b>Array displayed using nested for loop:</b><br>" ;
for ( $r = 0 ; $r < count ( $cars ); $r ++ ){
for ( $c = 0 ; $c < count ( $ cars [ $r ]); $c ++ ){
echo $ cars [ $r ][ $c ] " " ; }
echo "<br>" ;
}
Trang 59Multidimensional Arrays (Two-dimensional Arrays)
<?php
for ($row = 0 ; $row < count ( $cars ) ; $row++) {
echo "<p><b>Row number $row</b></p>";
Trang 60Multidimensional Arrays
Example: Hiển thị một giá trị từ
mảng ở trên:
Trang 61▪ sort() - sort arrays in ascending order
▪ rsort() - sort arrays in descending order
▪ asort() - sort associative arrays in ascending order, according to the
value
▪ ksort() - sort associative arrays in ascending order, according to the key
▪ arsort() - sort associative arrays in descending order, according to the value
Trang 62Sorting Arrays - Ascending Order
Trang 63Sorting Arrays - Descending Order
Trang 64Sorts an associative array in ascending order: value
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
asort($age);
foreach ($age as $x => $x_value) {
echo "Key=" $x ", Value=" $x_value;
echo "<br>" ;
}
?>
Key=Peter, Value=35 Key=Ben, Value=37 Key=Joe, Value=43
Trang 65Sorts an associative array in ascending order: key
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
ksort($age);
foreach ($age as $x => $x_value) {
echo "Key=" $x ", Value=" $x_value;
echo "<br>" ;
}
?>
Key=Ben, Value=37 Key=Joe, Value=43 Key=Peter, Value=35
Trang 66Sorts an associative array in descending order: value
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
arsort($age);
foreach ($age as $x => $x_value) {
echo "Key=" $x ", Value=" $x_value;
echo "<br>" ;
}
?>
Key=Joe, Value=43 Key=Ben, Value=37 Key=Peter, Value=35
Trang 67Sorts an associative array in descending order: key
<?php
$age = array ( "Peter" => "35" , "Ben" => "37" , "Joe" => "43" );
krsort($age);
foreach ($age as $x => $x_value) {
echo "Key=" $x ", Value=" $x_value;
echo "<br>" ;
}
?>
Key=Peter, Value=35 Key=Joe, Value=43 Key=Ben, Value=37
Trang 68PHP Forms and User Input
script
Trang 69PHP Forms and User Input
file "welcome.php"
− Nội dung file "welcome.php":
Trang 70PHP $_GET Function
− Hàm $_GET: thu thập các giá trị trong form với method="get"
▪ Có thể nhìn thấy tất cả mọi người (hiển thị trong thanh địa chỉ của trình duyệt)
▪ Có giới hạn về số lượng thông tin gửi.
Trang 72When to use method="get"?
− Khi sử dụng method="get" trong các form HTML, tất cả các tên biến và giá trị được hiển thị trong URL
▪ Không nên sử dụng khi gửi mật khẩu hoặc các thông tin nhạy cảm khác!
▪ Không nên sử dụng khi giá trị vượt quá 2000 ký tự.
dấu trang Điều này có thể hữu ích trong một số trường hợp
Trang 73PHP $_POST Function
− Hàm $_POST: thu thập các giá trị trong form với method="post"
▪ Vô hình với người khác
▪ Không có giới hạn về số lượng thông tin gửi.
Trang 74PHP $_POST Function
Trang 76When to use method="post"?
▪ Vô hình cho người khác
▪ Không có giới hạn về số lượng thông tin để gửi.
thể đánh dấu trang
Trang 77Form Validation
processing PHP forms
− Validation of form data is
important to protect your form
from hackers and spammers.
Field Validation Rules
Name Required + Must only contain letters and whitespace
E-mail Required + Must contain a valid email address (with @ and ) Comment Optional Multi-line input field (textarea)
The validation rules for the form above are as follows:
Trang 78Form Validation
returns the filename of the currently executing script
▪ $_SERVER["PHP_SELF"] sends the submitted form data to the
page itself, instead of jumping to a different page
▪ This way, the user will get error messages on the same page as the form.
HTML entities
▪ This means that it will replace HTML characters like < and > with < and >
▪ This prevents attackers from exploiting the code by injecting
HTML or Javascript code (Cross-site Scripting attacks) in forms.
Trang 79Form Validation
▪ test_input() : check each $_POST variable
<?php
$name = $email = $gender = $comment = $website = "" ;
if ( $_SERVER [ "REQUEST_METHOD" ] == "POST" ) {
$name = test_input( $_POST [ "name" ]);
$email = test_input( $_POST [ "email" ]);
$comment = test_input( $_POST [ "comment" ]);
$gender = test_input( $_POST [ "gender" ]);
Trang 80< body >
<?php
$name = $email = $gender = $comment = $website = "" ;
if ( $_SERVER [ "REQUEST_METHOD" ] == "POST" ) {
$name = test_input( $_POST ["name"]);
$email = test_input( $_POST ["email"]);
$comment = test_input( $_POST ["comment"]);
$gender = test_input( $_POST ["gender"]);
< h2 > PHP Form Validation Example </ h2 >
< form method ="post" action =" <?php echo htmlspecialchars( $_SERVER ["PHP_SELF"]);?>" >
Name: < input type ="text" name = "name" > < br >< br >
E-mail: < input type ="text" name = "email" > < br >< br >
Comment:
< textarea name ="comment" rows = "5" cols = "40" ></ textarea >
< br >< br >
Gender:
< input type ="radio" name = "gender" value = "female" > Female
< input type ="radio" name = "gender" value = "male" > Male
< input type ="radio" name = "gender" value = "other" > Other < br >< br >
< input type ="submit" name = "submit" value = "Submit" >
Trang 81Form Validation
▪ test_input() : check each $_POST variable
Trang 82PHÁT TRIỂN ỨNG DỤNG WEB
Bài 2:
PHP Nâng cao
Nguyễn Hữu Thể
Trang 84PHP Date() Function
gian
Trang 85PHP 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 86PHP Date() - Adding a Timestamp
thời gian
dụng
Trang 87PHP Date() - Adding a Timestamp
Trang 88PHP Include File
menu (thay vì cập nhật các liên kết trên tất cả các trang
Trang 90PHP include() Function
− file "menu.php", nên sử dụng trên tất cả các trang
Trang 91PHP include() Function
bản sẽ tiếp tục thực hiện.
Trang 92PHP require() Function
dừng lại.
Trang 93PHP require() Function
thực hiện sau khi xuất hiện lỗi.
Trang 94PHP File Handling
định mode của file được mở ra
Trang 95PHP File Handling
Trang 96PHP File Handling
Trang 97Closing a File
− Hàm fclose(): đóng một file đã mở
Trang 98Check End-of-file
− Hàm feof() kiểm tra nếu kết thúc file (“end-of-file” - EOF).
Trang 99Reading 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
Trang 100Reading 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
Trang 101PHP File Upload
− Upload files to the server
− 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
Trang 102PHP File Upload - Create The HTML Form
they want to upload
<html>
<body>
< form action ="upload_process.php" method ="post" enctype ="multipart/form-data">
Select image to upload:
</form>
</body>
</html>
Trang 103PHP File Upload - Create The Upload File PHP
if(isset( $_POST [ "submit" ])) {
$check = getimagesize( $_FILES [ "fileToUpload" ][ "tmp_name" ]);
Trang 104File 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 105File Upload - Limit File Size
"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" ] > 500 000) {
echo "Sorry, your file is too large." ;
$uploadOk = 0;
}
Trang 106File Upload - Limit File Type
and GIF files
$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 107File Upload - Limit File Type
if ( isset ( $_POST [ "submit" ])) {
$check = getimagesize( $_FILES [ "fileToUpload" ][ "tmp_name" ]);
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." ;
if (move_uploaded_file( $_FILES [ "fileToUpload" ][ "tmp_name" ], $target_file)) {
echo "The file " basename( $_FILES [ "fileToUpload" ][ "name" ]) " has been uploaded." ;
} else {
The complete "upload.php"
Trang 108PHP 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 109PHP 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 110PHP 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)
Trang 111How to Retrieve a Cookie Value?
Trang 112How to Retrieve a Cookie Value?