Bài giảng Phát triển ứng dụng web - Bài 1: PHP cơ bản - Nguyễn Hữu Thể
− 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 1

Trang 2

Trang 3

Trang 4

Trang 5

Trang 6

Trang 7

Trang 8

Trang 9

Trang 10
Tải về để xem bản đầy đủ
Bạn đang xem 10 trang mẫu của tài liệu "Bài giảng Phát triển ứng dụng web - Bài 1: PHP cơ bản - Nguyễn Hữu Thể", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
Tóm tắt nội dung tài liệu: Bài giảng Phát triển ứng dụng web - Bài 1: PHP cơ bản - Nguyễn Hữu Thể
ầu với ký hiệu $.
− Cách khai báo biến:
− Ví dụ:
14
PHP is a Loosely Typed Language
− Trong PHP, biến không cần khai báo trước khi thêm giá trị.
− PHP tự động chuyển kiểu dữ liệu biến , tùy thuộc vào giá trị của
nó.
− Biến sẽ khai báo tự động khi bạn sử dụng nó.
15
Naming 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 _ )
− Tên biến không nên chứa các khoảng trống.
− Nếu tên biến nhiều hơn một từ, nên tách bằng một gạch
($my_string), hoặc với chữ hoa ($myString)
16
PHP String Variables
− Các biến chuỗi được sử dụng cho các giá trị có chứa ký tự.
17
echo and print
❖ There are two basic ways to get output: echo and print
− The echo statement can be used with or without parentheses:
echo or echo().
echo "Hello world!";
− The print statement can be used with or without parentheses:
print or print()
print "I'm about to learn PHP!";
18
Data Types
− Variables can store data of different types, and different data
types can do different things.
− PHP supports the following data types:
▪ String
▪ Integer
▪ Float (floating point numbers - also called double)
▪ Boolean
▪ Array
▪ Object
▪ NULL <?php
▪ Resource $x = 5985;
var_dump($x); int(5985)
?>
19
The Concatenation Operator
− Sử dụng dấu (.) để nối hai chuỗi với nhau.
20
The strlen() function
− Hàm strlen() được sử dụng để lấy độ dài của chuỗi.
21
The strpos() function
− Sử dụng để tìm kiếm một ký tự/văn bản trong một chuỗi.
▪ 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!":
22
PHP Operators
− Toán tử được sử dụng để tính toán giá trị biểu thức.
❖ Arithmetic Operators
23
Lập trình ứng dụng mạng
PHP Operators
❖ Assignment Operators
24
PHP Operators
❖ Comparison Operators
25
PHP Operators
❖ Logical Operators
26
Conditional Statements
− Câu lệnh điều kiện được sử dụng để thực hiện các hành động
khác nhau dựa trên các điều kiện khác nhau.
− Trong PHP:
▪ if statement
▪ if...else statement
▪ if...elseif...else statement
▪ switch statement
27
The if Statement
− Thực hiện một số mã lệnh chỉ khi điều kiện quy định là đúng.
❖ Syntax
❖ Example
28
The if...else Statement
− Thực hiện một số mã lệnh nếu điều kiện là đúng và một số mã
lệnh khác nếu điều kiện sai.
❖ Syntax
❖ Example
29
The if...elseif...else Statement
− Chọn một trong nhiều khối mã sẽ được thực hiện.
❖ Syntax
❖ Example
30
The PHP Switch Statement
− Thực hiện các hành động khác nhau dựa trên điều kiện khác
nhau.
❖ Syntax Syntax
31
The PHP Switch Statement
32
PHP Loops
− Trong PHP, có các dạng vòng lặp sau:
▪ while
▪ do...while
▪ for
▪ foreach
33
The while loop
− Thực thi một khối mã lệnh trong khi một điều kiện là đúng.
❖Syntax
while(condition)
{
code to be executed;
}
34
The while loop
35
The 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.
❖ Syntax
do
{
code to be executed;
}
while (condition is true);
36
The do...while Statement
37
For Loops
− Thực hiện một khối mã lệnh theo một số quy định của lần, hoặc
đến khi một điều kiện quy định là đúng.
❖ Syntax
− Parameters:
▪ init: thiết lập một giá trị khởi tạo
▪ condition: đkiện lặp. Nếu đk là TRUE, vòng lặp tiếp tục. Nếu đk
để FALSE, vòng lặp kết thúc.
▪ increment: bước tăng tiếp theo của biến lặp
38
For Loops
39
foreach
− Vòng lặp foreach được sử dụng để lặp qua mảng.
❖ Syntax
40
The foreach loop
41
PHP Functions
− Trong PHP, có hơn 700 hàm được tích hợp.
❖ Syntax
❖ PHP functions:
− Cung cấp các hàm để thực hiện công việc gì đó
− Tên hàm có thể bắt đầu bằng một chữ cái hoặc gạch dưới
42
PHP Functions
43
PHP Functions - Adding parameters
− Các tham số được đặt phía sau tên hàm, bên trong dấu ngoặc đơn.
44
PHP Functions - Adding parameters
− Hai tham số
45
PHP Functions - Return values
− Để cho phép hàm trả về giá trị, sử dụng lệnh return.
46
PHP Arrays
− Một mảng lưu trữ nhiều giá trị trong một biến duy nhất.
− Mỗi phần tử trong mảng có chỉ số riêng để truy cập
− 3 kiểu mảng:
▪ Indexed arrays - Arrays with a numeric index
▪ Associative arrays - Arrays with named keys
▪ Multidimensional arrays - Arrays containing one or more
arrays
47
Indexed Arrays
− Một mảng số lưu trữ mỗi phần tử mảng với một số chỉ mục.
− Có hai phương pháp để tạo ra một mảng số
▪ Chỉ mục được gán tự động (chỉ số bắt đầu từ 0)
▪ Chỉ mục được gán bằng tay
48
Indexed Arrays - EX
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
I like Volvo, BMW and Toyota.
49
Indexed Arrays - Get The Length of an Array
− The count() function is used to return the length (the number
of elements) of an array
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
3
50
Indexed Arrays - Print all the values of an indexed array
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "";
}
?>
Volvo
BMW
Toyota
51
Associative Arrays
− Trong mảng kết hợp, mỗi ID được kết hợp với một giá trị.
❖ Example 1: Sử dụng một mảng để phân định lứa tuổi
❖ Example 2
52
Associative Arrays - EX
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Peter is 35 years old.
53
Associative 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 "";
}
?>
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
54
Multidimensional Arrays
− A multidimensional array is an array containing one or
more arrays.
− PHP understands multidimensional arrays that are two,
three, four, five, or more levels deep.
▪ However, arrays more than three levels deep are hard to
manage for most people.
55
Multidimensional Arrays (Two-dimensional Arrays)
− A two-dimensional array is an array of arrays (a three-
dimensional array is an array of arrays of arrays).
− Look at the following table: We can store in a two-
dimensional array:
Name Stock Sold $cars = array
(
Volvo 22 18
array("Volvo",22,18),
BMW 15 13 array("BMW",15,13),
Saab 5 2 array("Saab",5,2),
array("Land Rover",17,15)
Land Rover 17 15 );
56
Multidimensional Arrays (Two-dimensional Arrays)
▪ Get access to the elements of the $cars array
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".";
?>
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.57
Multidimensional Arrays (Two-dimensional Arrays)
▪ Loop to get the elements of the $cars array
<?php
//displaying array elements at once using for loop.
echo "Array displayed using nested for loop:";
for($r=0;$r<count($cars);$r++){
for($c=0;$c<count($ cars[$r]);$c++){
echo $ cars[$r][$c]." ";
}
echo "";
}
58
Multidimensional Arrays (Two-dimensional Arrays)
▪ Loop to get the elements of the $cars array
<?php Row number 0
for ($row = 0; $row < count($cars); $row++) { •Volvo
echo "Row number $row"; •22
echo ""; •18
Row number 1
for ($col = 0; $col < count($ cars[$row]; $col++) {
•BMW
echo "".$cars[$row][$col].""; •15
} •13
echo ""; Row number 2
} •Saab
?> •5
•2
Row number 3
•Land Rover
•17
•15
59
Multidimensional Arrays
− Tạo một mảng đa chiều, với các ID gán tự động
Example: Hiển thị một giá trị từ
mảng ở trên:
60
Sorting Arrays
• alphabetical,
• numerical order,
• descending or ascending
❖ Function:
▪ 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
▪ krsort() - sort associative arrays in descending order, according to the
key
61
Sorting Arrays - Ascending Order
<?php
$cars = array("Volvo", "BMW", "Toyota");
BMW
sort($cars); Toyota
?> Volvo
<?php
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) { 2
4
echo $numbers[$x]; 6
echo ""; 11
} 22
62
Sorting Arrays - Descending Order
<?php
$cars = array("Volvo", "BMW", "Toyota"); Volvo
rsort($cars); Toyota
?> BMW
<?php
$numbers = array(4, 6, 2, 22, 11);
rsort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) { 22
echo $numbers[$x]; 11
6
echo ""; 4
} 2
63
Sorts 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 "";
}
?>
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
64
Sorts 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 "";
}
?>
Key=Ben, Value=37
Key=Joe, Value=43
Key=Peter, Value=35
65
Sorts 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 "";
}
?>
Key=Joe, Value=43
Key=Ben, Value=37
Key=Peter, Value=35
66
Sorts 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 "";
}
?>
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
67
PHP Forms and User Input
− Các biến PHP $_GET và $_POST: lấy thông tin từ các form.
− Các thành phần thuộc form của trang HTML đều hỗ trợ cho PHP
script.
❖ Example
68
PHP Forms and User Input
− Khi điền vào mẫu ở trên và nhấn nút gửi, dữ liệu được gửi đến
file "welcome.php".
− Nội dung file "welcome.php":
69
PHP $_GET Function
− Hàm $_GET: thu thập các giá trị trong form với method="get".
− Thông tin được gửi từ một 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.
70
PHP $_GET Function
− Khi nhấp vào nút "Submit", URL được gửi đến máy chủ:
− File "welcome.php" có thể sử dụng hàm $_GET để thu thập form
dữ liệu.
71
When 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.
− Lưu ý:
▪ 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ự.
− Tuy nhiên, vì các biến được hiển thị trong URL, nó có thể đánh
dấu trang. Điều này có thể hữu ích trong một số trường hợp.
72
PHP $_POST Function
− Hàm $_POST: thu thập các giá trị trong form với method="post".
− Thông tin được gửi từ một 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.
73
PHP $_POST Function
74
PHP $_POST Function
− Khi nhấp vào nút "Submit", URL được gửi đến máy chủ:
− File "welcome.php" có thể sử dụng hàm $_POST để thu thập dữ
liệu từ form
75
When to use method="post"?
− Thông tin được gửi từ một form với phương thức 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.
− Tuy nhiên, do các biến không được hiển thị trong URL, nó không
thể đánh dấu trang.
76
Form Validation
− Think SECURITY when
processing PHP forms.
− Validation of form data is
important to protect your form
from hackers and spammers.
The validation rules for the form above are as follows:
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)
Gender Required. Must select one
77
Form Validation
− $_SERVER["PHP_SELF"] : a super global variable that
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.
− htmlspecialchars() : function converts special characters to
HTML entities.
▪ This means that it will replace HTML characters like
with < and >.
▪ This prevents attackers from exploiting the code by injecting
HTML or Javascript code (Cross-site Scripting attacks) in forms.
78
Form Validation
− Validate Form Data With PHP
▪ 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"]);
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
79
<?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"]);
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
PHP Form Validation Example
">
Name:
E-mail:
Comment:
Gender:
Female
Male
Other
<?php
echo "Your Input:";
echo $name;
echo "";
echo $email;
echo "";
echo $comment;
echo "";
echo $gender; 80
?>
Form Validation
− Validate Form Data With PHP
▪ test_input(): check each $_POST variable
81File đính kèm:
bai_giang_phat_trien_ung_dung_web_bai_1_php_co_ban_nguyen_hu.pdf

