Download File trong PHP

Trong bài viết này mình chia sẻ cách để download file trong php nhé.Các bạn tham khảo.

Tạo các file xử lý để download file

Tạo file downloadfile.php có nhiệm vụ xử lý để download file,toàn bộ code như sau  :

<?php
$nameFile = "hinh1.jpg"; // thay đổi tên file từ csdl tại đây
$FileExtension = explode(".",$nameFile)[count(explode(".",$nameFile))-1];
$file_url = $_SERVER['DOCUMENT_ROOT'].'/downloadfile/files/'.$nameFile;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=file-".md5(rand(0,1000)).".".$FileExtension); 
readfile($file_url);
?>

 

Tiếp theo file index.php có nhiệm vụ tạo thẻ a đường link để người dùng có thể click vào download file.Code như sau:

<a href="downloadfile.php">Click Download File</a>

Tiến hành chạy chương trình :

download file trong php
Chạy file index.php

Chúc các bạn thực hiện thành công!

 

 

0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận
x