bài 6 tải file và hình ảnh lên website - xây dựng ứng dụng web
DESCRIPTION
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 transparencyTRANSCRIPT
Bài 6Tải file và hình ảnh lên website
Làm việc với file và thư mụcUpload và download fileTạo ảnh mới, thay đổi kích cỡ ảnh, làm việc vớitransparency
Mục tiêu
Bài 6 - Tải file và hình ảnh lên website 2
Liệt kê danh sách fileĐọc và ghi fileĐọc và ghi dữ liệu CSVSao 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
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)
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>';
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>';
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
Đọ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);
Đọ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);
Các chế độ mở file của hàm fopen
Bài 6 - Tải file và hình ảnh lên website 10
rbwbabxb
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
Đọ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;
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);
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
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>";
}
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
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>';}
}
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>';}
}
Form HTML để upload fileMã 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
Để upload file thì form HTML cần có thành phầntố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>
Các thành phần của mảng $_FILES:NameSizeTmp_nameTypeError
Các mã lỗi thường gặp:UPLOAD_ERR_OK: không xảy ra lỗiUPLOAD_ERR_INI_SIZE: kích thước file vượt quy địnhUPLOAD_ERR_PARTIAL
Làm việc với file upload
Bài 6 - Tải file và hình ảnh lên website 21
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';}
Lấy thông tin về một ảnhĐọc và ghi ảnhThay đổi kích cỡ ảnhLà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
Hàm lấy thông tin về một file ảnh:getimagesize($path)Các hằng IMAGETYPE thông dụng:
IMAGETYPE_JPEGIMAGETYPE_GIFIMAGETYPE_PNG
Lấy thông tin về ảnh
Bài 6 - Tải file và hình ảnh lên website 24
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];
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 26
//Hiển thị loại ảnhswitch($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;
}
imagecreatefromxxx($path)imagesx($image)imagesy($image)imagexxx($image, $path)imagedestroy($image)
Các hàm thao tác với file ảnh
Bài 6 - Tải file và hình ảnh lên website 27
Đọ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];
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 ảnhswitch($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;
}
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ếmimagedestroy($image);
imagecreatetruecolor($w, $h)imagecopyresampled($di, $si, $dx, $dy, $sx, $sy,$dw, $dh, $sw, $sh)
Hàm thay đổi kích cỡ ảnh
Bài 6 - Tải file và hình ảnh lên website 31
Thay đổi kích cỡ ảnh thành tối đa là 100x100pixels:
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;
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ớiif ($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);
Ví dụ
Bài 6 - Tải file và hình ảnh lên website 34
//Ghi ảnh mới vào fileimagepng($new_image, $new_path);
//Giải phóng bộ nhớ dùng cho ảnh mớiimagedestroy($new_image);
}//Giải phóng bộ nhớ dùng cho ảnh cũimagedestroy($old_image);
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
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 ảnhif ($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);
}
Giao diện người dùng:
Kết quả
Bài 6 - Tải file và hình ảnh lên website 37
PHP cung cấp nhiều hàm làm việc với file, baogồm cả các file định dạng CSVThư 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 địnhdạng JPEG, GIF và PNGĐộ trong suốt là thông số thể hiện tỉ lệ trongsuốt của một bức ảnh. Thông tin này được lưutrong kênh alpha (alpha channel) của ảnh. Khiđó, trình duyệt có thể kết hợp các phần trongsuốt của ảnh với hình nền để tạo ra hiệu ứngtrong suốt. Quá trình này gọi là quá trình trộnalpha (alpha blending).
Tổng kết bài học
Bài 6 - Tải file và hình ảnh lên website 38