Bài này gồm 3 phần chính:
- PHP core: Giới thiệu về ngôn ngữ PHP.
- PHP in web development: Ứng dung PHP trong lập trình web cơ bản.
- PHP Example: Ví dụ về 1 web viết bằng PHP.
I. PHP core
1.1. Basic syntax
1.1.1. Variables & Operators
a. Array
– Mảng là 1 trong những thứ linh hoạt nhất trong PHP. Khai báo mảng bằng từ khoá array().
– Mảng ở trong PHP có thể chứa nhiều kiểu dữ liệu khác nhau. Có 2 loại mảng sau trong PHP:
i. Mảng chỉ số – indexed array
Mảng 1 chiều:
– Khai báo:
$arr1 = array(“hello”, 5, true, “vcttai”);
– Truy cập: dùng chỉ số như thông thường
echo $arr1[2];
Mảng 2 chiều:
– Khai báo:
$arr2 = array(
array(“vcttai”, 23, “hcmc”),
array(“hqtoan”, 22, “hcmc”),
array(“httong”, 25, “hcmc”)
);
– Truy cập: dùng chỉ số
echo $arr2[1][2];
ii. Mảng kết hợp – associative array
– Khai báo: dựa trên “key” => “value”
vd:
$age = array(
“vcttai” => 23,
“hqtoan” => 22,
“httong” => 25
);
– Truy cập: dùng key
vd: echo $age[‘vcttai’];
b. Data types – Variables – Operators
i. Data types – Kiểu dữ liệu
– PHP không quy định phải khai báo kiểu dữ liệu, PHP sẽ tự nhận biết.
vd:
$foo = ‘Hello !’; // string
$number = 123456; // number (integer)
$success = TRUE; // boolean
ii. Variable – Biến
– Khai báo 1 biến bằng dấu “$”, không cần khai báo kiểu dữ liệu
vd:
$num1 = 243;
$str1 = “Hello”;
iii. Operators – Toán tử
1.1.2. Control structures
a. Include & Require
– Include và require dùng để ghép nối 2 file php riêng rẽ lại với nhau.
=> Trình biên dịch sẽ tự nối code 2 file lại và biên dịch
Công dụng:
– Dùng để gom các phần code chung lại 1 file duy nhất, chỗ nào cần chạy thì include vào.
b. use
– Dùng để add tham chiếu thư viện, add tham chiếu file cần dùng.
vd: Cần sử dụng source code được định nghĩa ở file math_function.php
-> use math_function.php
c. Control structures
– Các cấu trúc điều khiển trong PHP tương tự như các ngôn ngữ lập trình khác, có cú pháp tương tự ngôn ngữ C, bao gồm:
i. Cấu trúc vòng lặp:
++ For
++ while
++ do … while
++ foreach
ii. Cấu trúc điều kiện:
++ if … else
++ switch … case
1.1.3. Functions
a. Common functions
Là các hàm xây dựng sẵn của PHP được sử dụng nhiều.
i. Variable handling
1. var_dump()
– Dùng để hiển thị thông tin về cấu trúc của 1 biến nào đó.
vd: var_dump($a);
2. print_r()
– Dùng để hiển thị thông tin về 1 biến
vd: print_r($a)
3. empty()
– Hàm kiểm tra xem biến có rỗng hay không.
4. isset()
– Kiểm tra 1 biến đã được set và khác NULL.
ii. String functions
1. htmlspecialchars ()
– Dùng để convert các kí tự đặc biệt thành HTML entities. Hay dùng để escape chuỗi, phòng tránh lỗi tấn công XSS.
2. nl2br()
– Chèn html tag <br> vào những chỗ xuống dòng trong chuỗi.
iii. Array functions
1. array_key_exists()
– Kiểm tra xem 1 key có tồn tại trong mảng hay không
2. unset()
– Xoá 1 phần tử trong mảng
3. array_search()
– Tìm trong mảng xem có tồn tại “value” nào đó hay không.
iv. Filesystem functions
1. file_exists — Checks whether a file or directory exists
2. fopen — Opens file or URL
3. fgets — Gets line from file pointer
4. fwrite — Binary-safe file write
5. file_get_contents — Reads entire file into a string
b. Functions
i. User-defined functions
– Để khai báo hàm trong PHP, ta dùng cú pháp sau:
function function_name()
{
// body of function
}
hoặc
function function_name($param1, $param2=’default’)
{
// body of function
// param2 is optional param with defaule value is ‘default’
}
ii. Global variable
– Có thể truy cập các biến của PHP một cách global bằng lệnh global
$num = 5;
function foo()
{
echo “a\n”;
echo $num . “\n”; // <<<——- ERROR !!!
global $num; // use “global” to access var $num
// (!!! USING GLOBAL VARIABLE IS NOT RECOMMENDED !!!)
$num = 7;
echo $num . “\n”;
}
iii. Reference variable
– Biến tham chiếu, gần giống với con trỏ trong C++
$a = 3;
$b = &$a;
echo $b . “\n”; // 3
$b = 4;
echo $a; // 4
iv. Passing argument by reference
– Mặc định, tham số truyền vào hàm là “tham trị”, để truyền kiểu “tham biến” thì thêm dấu “&”
vd:
function foo( &$hoge )
{
$hoge = ‘new value’;
}
$hoge = ‘test’;
foo( $hoge ); // $hoge = ‘new value’
Thuật ngữ tiếng anh:
Pass by value: truyền tham trị
Pass by reference: truyền tham chiếu / tham biến
1.2. Object oriented programming
– Tham khảo: http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners–net-12762
1.2.1. Classes & Objects
a. Define a class
– Cú pháp để khai báo tương tự như C
– Lưu ý: hàm khởi tạo có tên là __construct() (PHP 5)
class User
{
// Constants are always publicly visible
const MIN_PASSWORD_LENGTH = 8;
private $_name;
private $_age;
private $_password;
// Constructor
public function __construct()
{
}
// Destructor
public function __destruct()
{
echo ‘I am dead!’;
}
public function sayHello()
{
echo ‘Hello’;
}
}
b. Instantiate an object
– Để khởi tạo 1 đối tượng, dùng từ khoá new như thông thường
vd:
$user = new User(‘Bop’, 18);
$user->sayHello(); // Call sayHello() method
c. Inheritance
– Để kế thừa trong PHP, dùng từ khoá extends
vd:
class ClsA
{
public function execute()
{
echo ‘A’;
}
}
// ClsB class inherits from the ClsA class
class ClsB extends ClsA
{
// Override execute() method of ClsA
public function Execute()
{
echo ‘B’;
}
}
// ClsC class inherits from the ClsA class
class ClsC extends ClsA
{
public function execute()
{
parent::execute(); // Call Execute() method of the parent class
echo ‘C’;
}
}
$b = new ClsB();
$b->execute();
//Output: B
$c = new ClsC();
$c->execute();
//Output: AC
1.2.2. Namespace
– Tham khảo:
http://www.sitepoint.com/php-53-namespaces-basics/
http://www.sitepoint.com/php-namespaces-import-alias-resolution/
http://www.sitepoint.com/how-to-use-php-namespaces-part-3-keywords-and-autoloading/
1.3. Access to Database
1.3.1. Choose API
– PHP đưa ra 3 cách, tham khảo ở: http://php.net/mysqlinfo.api.choosing
– Khuyến khích sử dụng mysqli, vì nó mới và hướng đối tượng.
<?php
// mysqli
$mysqli = new mysqli(“example.com”, “user”, “password”, “database”);
$result = $mysqli->query(“SELECT ‘Hello, dear MySQL user!’ AS _message FROM DUAL”);
$row = $result->fetch_assoc();
echo htmlentities($row[‘_message’]);
// PDO
$pdo = new PDO(‘mysql:host=example.com;dbname=database’, ‘user’, ‘password’);
$statement = $pdo->query(“SELECT ‘Hello, dear MySQL user!’ AS _message FROM DUAL”);
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row[‘_message’]);
// mysql
$c = mysql_connect(“example.com”, “user”, “password”);
mysql_select_db(“database”);
$result = mysql_query(“SELECT ‘Hello, dear MySQL user!’ AS _message FROM DUAL”);
$row = mysql_fetch_assoc($result);
echo htmlentities($row[‘_message’]);
?>
1.3.2. Using MySqli
– http://codular.com/php-mysqli
– http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
1.3.3. Using PDO
– http://codular.com/php-pdo-how-to
II. Web development
2.1. Handling request
2.1.1. GET
– Sử dụng $_GET[param_name] để lấy giá trị tham của tham số truyền đi bởi phương thức GET
vd:
======== hello.php ===========
<html>
<head>
<title>PHP Test</title>
</head>
<body>
Hello <?php echo(htmlspecialchars($_GET[‘name’]));?>!
</body>
</html>
====================================
Truy cập vào trang hello.php với đường dẫn: http://localhost/hello.php?name=Bop
========== result ==============
Hello Bop!
=====================
2.1.2. POST
– Sử dụng $_POST[param_name] để lấy giá trị tham của tham số truyền đi bởi phương thức POST
vd: bắt đầu truy cập từ form.php
========= form.php ================
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<form action=”form_action.php” method=”post”>
<p>Your name: <input type=”text” name=”name” /></p>
<p>Your age: <input type=”text” name=”age” /></p>
<p><input type=”submit” /></p>
</form>
</body>
</html>
==========================
=========form_action.php===========
<html>
<head>
<title>PHP Test</title>
</head>
<body>
Hi <?php echo (htmlspecialchars($_POST[‘name’]));?>!<br/>
You are <?php echo (int)$_POST[‘age’];?> years old.
</body>
</html>
=======================
========== result ===============
Hi Bop!
You are 20 years old.
==========================
2.2. Cookies / Sessions
2.2.1. Cookies
– Tham khảo: http://www.w3schools.com/php/php_cookies.asp
2.2.2. Session
– Tham khảo:
Short: http://www.w3schools.com/php/php_sessions.asp
Full: http://www.phpro.org/tutorials/Introduction-To-PHP-Sessions.html
2.3. HTTP Header fields
III. Example
Vcttai