XtGem Forum catalog

ChiaSeIT.Mobie.In

Hàm tạo file Zip bằng PHP

Việc nén (zip) file bằng PHP thật ra rất đơn giản, nó cũng giống như là các bạn thực hiện thao tác zip file trên destop vậy. Hôm nay ChiaseIT.Mobie.In sẽ chia sẻ cho các bạn một hàm đơn giản là create_zip , và các bạn sẽ chỉ cần sử dụng lại hàm này mỗi khi cần nén file nào đó.





/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

//close the zip -- done!
$zip->close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}


Và đây là cách sử dụng :

$files_to_zip = array(
'preload-images/1.jpg',
'preload-images/2.jpg',
'preload-images/5.jpg',
'kwicks/ringo.gif',
'rod.jpg',
'reddit.gif'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');


Hàm mà mình giới thiệu cho các bạn có 2 tham số, tham số thứ nhất có thể là một file, hoặc là một mảng chứa nhiều file. Tham số thứ 2 sẽ là nơi chúng ta điền thông tin tên fize zip cũng như đường dẫn sẽ chứa file zip này. Hàm này sẽ trả về giá trị true nếu như việc nén file thành công, ngược lại sẽ trả về false.
Mình hy vọng với bài viết hôm nay, các bạn sẽ có thêm một kinh nghiệm lập trình php cũng như một hàm php hữu ích để các bạn sử dụng sau này.

Bình luận
Từ Khóa
Hàm tạo file Zip bằng PHP , Việc, nén, (zip), file, bằng, PHP, thật, ra, rất, đơn, giản,, nó, cũng, giống, n , Tìm hiểu Hàm tạo file Zip bằng PHP làm theo và học hỏi , Bài viết Hot Hàm tạo file Zip bằng PHP ,
Cùng Chuyên Mục
Share code PHP game tìm Boom
Hiển thị số lượng Facebook likes / Shares / Comments với PHP
Hàm giải nén file Zip bằng PHP
Tự tay làm Tags Cloud cho trang web của bạn bằng PHP
Upload và giải nén file zip ngay trên web server với PHP
Share code PHP phát hiện Địa chỉ người dùng
Share code Get Link xem Video max BW Onbox.vn
Share code PHP tạo Bộ đếm cho Website của bạn
Share code tìm kiếm trong Database
Share code PHP tạo Captcha dạng toán từng bước đơn giản
Chia sẻ coding miễn phí © 2017
Thiết kế: Mạnh Tuân

sitemap.xml robots.txt U-ONC-STAT