2. Làm việc với file và thư mục
Upload và download file
Tạo ảnh mới, thay đổi kích cỡ ảnh, làm việc với
transparency
Mục tiêu
Bài 6 - Tải file và hình ảnh lên website 2
3. Liệt kê danh sách file
Đọc và ghi file
Đọc và ghi dữ liệu CSV
Sao chép, đổi tên, xóa một file
Làm việc với file và thư mục
Bài 6 - Tải file và hình ảnh lên website 3
4. Ba hàm kiểm tra một file/folder đã tồn tại chưa:
Hàm lấy về folder hiện tại:
Hằng chứa ký tự phân cách đường dẫn:
Hàm liệt kê danh sách folder:
Làm việc với thư mục (folder)
Bài 6 - Tải file và hình ảnh lên website 4
is_file($path)
is_dir($path)
file_exists($path)
getcwd()
DIRECTORY_SEPARATOR
scandir($path)
5. Hiển thị danh sách folder:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 5
$path = getcwd();
$items = scandir($path);
echo "<p>Content of path: </p>";
echo "<ul>";
foreach ($items as $item) {
echo '<li>' . $item .
'</li>';
}
echo '</ul>';
6. Hiển thị các file từ danh sách folder:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 6
$path = getcwd();
$items = scandir($path);
$files = array();
foreach ($items as $item) {
$item_path = $part .
DIRECTORY_SEPARATOR . $item;
if (is_file($item_path)) {
$file[] = $item;
}
}
echo "<p>Files in $path </p>";
echo '<ul>';
foreach ($files as $file) {
echo '<li>' . $file . '</li>';
}
echo '</ul>';
7. Ba hàm đọc file:
File($name)
File_get_contents($name)
Readfile($name)
Hàm ghi file:
File_put_contents($name, $data)
Làm việc với file
Bài 6 - Tải file và hình ảnh lên website 7
8. Đọc nội dung từ file txt:
Ghi nội dung vào file txt:
Đọc và ghi file txt
Bài 6 - Tải file và hình ảnh lên website 8
$text = file_get_contents('message.txt');
$text = htmlspeacialchars($text);
echo '<div>' . $text . '</div>';
$text = "This is line 1. nThis is line 2. n";
file_put_contents('message.txt', $text);
9. Đọc file và hiển thị dưới dạng danh sách:
Ghi mảng vào file:
Đọc và ghi các mảng
Bài 6 - Tải file và hình ảnh lên website 9
$name = file('usernames.txt');
foreach ($names as $name) {
echo '<div>' . $name . '</div>';
}
$name = array('joelmurach', 'rayharris', 'mikemurach');
$name = implode("n", $names);
file_put_contents('usernames.txt', $names);
10. Các chế độ mở file của hàm fopen
Bài 6 - Tải file và hình ảnh lên website 10
rb
wb
ab
xb
11. Hàm mở/đóng file:
fopen($path, $mode)
feof($file)
fclose($file)
Hàm đọc/ghi file:
fread($file, $length)
fgets($file)
fwrite($file, $data)
Các hàm thao tác với file
Bài 6 - Tải file và hình ảnh lên website 11
12. Đọc từ một file:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 12
$file = fopen('usernames.txt', 'rb');
$name = '';
while (!feof($file)) {
$name = fgets($file);
if ($name == false) {continue; }
$name = trim($name);
if (strlen($name) == 0 || subtr($name, 0, 1) ==
'#') {continue; }
$names .= "<div>" . $name . "</div>n";
}
fclose($file);
echo $names;
13. Ghi vào một file:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 13
$path = getcwd();
$items = scandir($path);
$file = fopen('listing.txt', 'wb');
foreach ($items as $item) {
$item_path = $path . DIRECTORY_SEPARATOR . $item;
if (is_dir($item_path)) {
fwrite($file, $item . "n");
}
}
fclose($file);
14. Hàm đọc/ghi file CSV:
fgetcsv($file)
fputcsv($file, $array)
Ví dụ một file CSV đơn giản:
Hàm thao tác với file CSV
Bài 6 - Tải file và hình ảnh lên website 14
15. Ghi dữ liệu vào file CSV:
Đọc dữ liệu từ file CSV:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 15
$products = array( array('MMS-1234', 'Trumpet', 199.95),
array('MMS-8521', 'Flute', 149.95));
$file = fopen('products.csv', 'wb');
foreach ($products as $product) {
fputcsv($file, $product);
}
fclose($file);
$file = fopen('products.csv', 'rb');
$products = array();
while (!feof($file)) {
$product = fgetcsv($file);
if ($product == false) continue;
$products[] = $product;
echo "<div>$product[0] | $product[1] | $product[2]</div>";
}
16. Hàm copy file:
copy($oldname, $newname)
Hàm đổi tên file:
rename($oldname, $newname)
Hàm xóa một file:
unlink($name)
Hàm copy, đổi tên, xóa file
Bài 6 - Tải file và hình ảnh lên website 16
17. Copy một file:
Đổi tên một file:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 17
$name1 = 'message.txt';
$name2 = 'message_2.txt';
if (file_exists($name1)) {
$success = copy($name1, $name2);
if ($success) {
echo '<div>File was copied.</div>';
}
}
$name2 = 'message_2.txt';
$name3 = 'message_copy.txt';
if (file_exists($name2)) {
$success = rename($name2, $name3);
if ($success) {
echo '<div>File was renamed.</div>';
}
}
18. Xóa một file:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 18
$name3 = 'message_copy.txt';
if (file_exists($name3)) {
$success = unlink($name3);
if ($success) {
echo '<div>File was deleted.</div>';
}
}
19. Form HTML để upload file
Mã PHP làm việc với file upload
Upload file
Bài 6 - Tải file và hình ảnh lên website 19
20. Để upload file thì form HTML cần có thành phần
tối thiểu như sau:
Kết quả hiển thị:
Form HTML để upload file
Bài 6 - Tải file và hình ảnh lên website 20
<form action="upload.php" method="post"
enctype="multipart/form-data">
<input type="file" name="file1"/> <br/>
<input type="submit" value="Upload"/>
</form>
21. Các thành phần của mảng $_FILES:
Name
Size
Tmp_name
Type
Error
Các mã lỗi thường gặp:
UPLOAD_ERR_OK: không xảy ra lỗi
UPLOAD_ERR_INI_SIZE: kích thước file vượt quy định
UPLOAD_ERR_PARTIAL
Làm việc với file upload
Bài 6 - Tải file và hình ảnh lên website 21
22. Hàm lưu file đã upload:
move_uploaded_file($tmp, $new)
Ví dụ:
Làm việc với file upload
Bài 6 - Tải file và hình ảnh lên website 22
$tmp_name = $_FILES['file1']['tmp_name'];
$path = getcwd() . DIRECTORY_SEPARATOR . 'images';
$name = $path . DIRECTORY_SEPARATOR .
$_FILES['file1']['name'];
$success = move_uploaded_file($tmp_name, $name);
if ($success) {
$upload_message = $name . ' has been uploaded';
}
23. Lấy thông tin về một ảnh
Đọc và ghi ảnh
Thay đổi kích cỡ ảnh
Làm việc với độ trong suốt của ảnh
Làm việc với file ảnh
Bài 6 - Tải file và hình ảnh lên website 23
24. Hàm lấy thông tin về một file ảnh:
getimagesize($path)
Các hằng IMAGETYPE thông dụng:
IMAGETYPE_JPEG
IMAGETYPE_GIF
IMAGETYPE_PNG
Lấy thông tin về ảnh
Bài 6 - Tải file và hình ảnh lên website 24
25. Lấy thông tin về một file ảnh:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 25
//Thiết lập đường dẫn tới file ảnh
$image_path = getcwd() . DIRECTORY_SEPARATOR .
'gibson_sg.png';
//Lấy thông số chiều dài, chiều rộng và loại ảnh
$image_info = getimagesize($image_path);
$image_width = $image_info[0];
$image_height = $image_info[1];
$image_type = $image_info[2];
26. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 26
//Hiển thị loại ảnh
switch($image_type) {
case IMAGETYPE_JPEG:
echo 'This is a JPEG image.<br/>';
break;
case IMAGETYPE_GIF:
echo 'This is a GIF image.<br/>';
break;
case IMAGETYPE_PNG:
echo 'This is a PNG image.<br/>';
break;
default:
echo 'File must be a JPEG, GIF or PNG
image.<br/>';
exit;
}
28. Đọc và ghi file ảnh:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 28
//Thiết lập đường dẫn cho ảnh
$image_path = getcwd() . DIRECTORY_SEPARATOR .
'gibson_sg.png';
$image_path_2 = getcwd() . DIRECTORY_SEPARATOR .
'gibson_sg_2.png';
//Lấy thông số chiều rộng, chiều dài và loại ảnh
$image_info = getimagesize($image_path);
$image_type = $image_info[2];
29. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 29
//Thiết lập tên hàm ứng với mỗi loại ảnh
switch($image_type) {
case IMAGETYPE_JPEG:
$image_from_file = 'imagecreatefromjpeg';
$image_to_file = 'imagejpeg';
break;
case IMAGETYPE_GIF:
$image_from_file = 'imagecreatefromgif';
$image_to_file = 'imagegif';
break;
case IMAGETYPE_PNG:
$image_from_file = 'imagecreatefrompng';
$image_to_file = 'imagepng';
break;
default:
echo 'File must be a JPEG, GIF or PNG image';
exit;
}
30. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 30
//Tạo ảnh mới từ một file có sẵn
$image = $image_from_file($image_path);
//Kiểm tra chiều dài và chiều rộng bức ảnh
$image_width = imagesx($image);
$image_height = imagesy($image);
//Ghi ảnh vào một file
$image_to_file($image, $image_path_2);
//Giải phóng bộ nhớ mà bức ảnh chiếm
imagedestroy($image);
32. Thay đổi kích cỡ ảnh thành tối đa là 100x100
pixels:
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 32
//Thiết lập các biến
$old_path = getcwd() . DIRECTORY_SEPARATOR .
'gibson_sg.png';
$new_path = getcwd() . DIRECTORY_SEPARATOR .
'gibson_sg_100.png';
$image_type = IMAGETYPE_PNG;
//Lấy ảnh cũ và các thông số dài rộng của nó
$old_image = imagecreatefrompng($old_path);
$old_width = imagesx($old_image);
$old_height = imagesy($old_image);
//Tính toán tỷ lệ ảnh sao cho kích cỡ tối đa là 100x100
$width_ratio = $old_width / 100;
$height_ratio = $old_height / 100;
33. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 33
//Nếu ảnh lớn hơn tỷ lệ định sẵn thì tạo ảnh mới
if ($width_ratio > 1 || $height_ratio > 1) {
//Tính chiều dài và chiều rộng cho ảnh mới
$ratio = max($width_ratio, $height_ratio);
$new_height = round($old_height / $ratio);
$new_width = round($old_width / $ratio);
//Tạo ảnh mới
$new_image = imagecreatetruecolor($new_width,
$new_height);
//Copy ảnh cũ thành ảnh mới để thay đổi kích thước
$new_x = 0;
$new_y = 0;
$old_x = 0;
$old_y = 0;
imagecopyresampled($new_image, $old_image, $new_x,
$new_y, $old_x, $old_y,$new_width, $new_height,
$old_width, $old_height);
34. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 34
//Ghi ảnh mới vào file
imagepng($new_image, $new_path);
//Giải phóng bộ nhớ dùng cho ảnh mới
imagedestroy($new_image);
}
//Giải phóng bộ nhớ dùng cho ảnh cũ
imagedestroy($old_image);
35. imagecolorallocatealpha($i, $r, $g, $b, $a)
imagecolortransparent($i, $a)
imagealphablending($i, $f)
imagesavealpha($i, $f)
Hàm làm việc với
độ trong suốt của ảnh
Bài 6 - Tải file và hình ảnh lên website 35
36. Ví dụ
Bài 6 - Tải file và hình ảnh lên website 36
//Tính chiều dài và chiều rộng của ảnh mới và thiết lập loại
ảnh
$new_image = imagecreatetruecolor($new_width, $new_height);
//Thiết lập độ trong suốt tùy thuộc vào loại ảnh
if ($image_type == IMAGETYPE_GIF) {
$alpha = imagecolorallocatealpha($new_image, 0, 0, 0,
127);
imagecolortransparent($new_image, $alpha);
}
if ($image_type == IMAGETYPE_PNG || $image_type ==
IMAGETYPE_GIF) {
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
}
37. Giao diện người dùng:
Kết quả
Bài 6 - Tải file và hình ảnh lên website 37
38. PHP cung cấp nhiều hàm làm việc với file, bao
gồm cả các file định dạng CSV
Thư viện GD là một thư viện của PHP chuyên xử
lý ảnh, nó gồm các hàm xử lý ảnh có kiểu định
dạng JPEG, GIF và PNG
Độ trong suốt là thông số thể hiện tỉ lệ trong
suốt của một bức ảnh. Thông tin này được lưu
trong kênh alpha (alpha channel) của ảnh. Khi
đó, trình duyệt có thể kết hợp các phần trong
suốt của ảnh với hình nền để tạo ra hiệu ứng
trong suốt. Quá trình này gọi là quá trình trộn
alpha (alpha blending).
Tổng kết bài học
Bài 6 - Tải file và hình ảnh lên website 38