Xem thêm

Ép download file bằng PHP: Cách đơn giản để tải file với một click

Huy Erick
Bạn có bao giờ gặp phải trường hợp khi tải một file từ trang web, thì nó lại được mở trong tab hoặc cửa sổ mới trên trình duyệt của bạn? Điều này có thể...

Bạn có bao giờ gặp phải trường hợp khi tải một file từ trang web, thì nó lại được mở trong tab hoặc cửa sổ mới trên trình duyệt của bạn? Điều này có thể trở nên khá phiền toái khi bạn muốn lưu file đó trực tiếp vào máy tính của mình mà không cần mở nó lên trước. Trong bài viết này, chúng tôi sẽ chia sẻ với bạn một cách đơn giản để tải file chỉ với một click duy nhất.

Ép download file trong trình duyệt

Khi bạn tạo chức năng download file trên trang web của bạn, mặc định file sẽ được mở trong trình duyệt, thường là trong một tab mới. Điều này rất tiện lợi đối với các file hình ảnh nhỏ hoặc file văn bản, nhưng không hợp lý đối với các file có kích thước lớn hoặc file có định dạng đặc biệt như CSV, PDF hoặc PHP.

Một đoạn mã PHP đơn giản để tải file

Dưới đây là một đoạn mã PHP đơn giản giúp bạn "ép" download file từ trang web của bạn chỉ với một click. Đầu tiên, bạn tạo một file PHP mới có tên "function.php" và dán đoạn mã sau:

function output_file($Source_File, $Download_Name, $mime_type='') {
    if(!is_readable($Source_File)) die('File not found or inaccessible!');
    $size = filesize($Source_File);
    $Download_Name = rawurldecode($Download_Name);

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($Source_File,"."),1));
        $known_mime_types=array(
            "pdf" => "application/pdf",
            "csv" => "application/csv",
            "txt" => "text/plain",
            "html" => "text/html",
            "htm" => "text/html",
            "exe" => "application/octet-stream",
            "zip" => "application/zip",
            "doc" => "application/msword",
            "xls" => "application/vnd.ms-excel",
            "ppt" => "application/vnd.ms-powerpoint",
            "gif" => "image/gif",
            "png" => "image/png",
            "jpeg" => "image/jpg",
            "jpg" => "image/jpg",
            "php" => "text/plain"
        );
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };

    // off output buffering to decrease Server usage
    @ob_end_clean();

    // if IE, otherwise Content-Disposition ignored
    if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$Download_Name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');
    header("Cache-control: private");
    header('Pragma: private');
    header("Expires: Thu, 26 Jul 2012 05:00:00 GMT");

    // multipart-download and download resuming support
    if(isset($_SERVER['HTTP_RANGE'])){
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end){
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }
        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    // output the file itself
    $chunksize = 1*(1024*1024); //you may want to change this
    $bytes_send = 0;

    if ($Source_File = fopen($Source_File, 'r')) {
        if(isset($_SERVER['HTTP_RANGE'])) fseek($Source_File, $range);
        while(!feof($Source_File) && (!connection_aborted()) && ($bytes_send<$new_length) ) {
            $buffer = fread($Source_File, $chunksize);
            print($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }
        fclose($Source_File);
    } else die('Error - can not open file.');
    die();
}

Sử dụng đoạn code PHP để tải file

Để sử dụng đoạn code trên, bạn chỉ cần nhúng file "function.php" vào trang web của mình và sử dụng như sau:

include("function.php");
set_time_limit(0);
$file_path="phpgang.csv";
output_file($file_path, 'phpgang.csv', 'application/csv');

Trong đoạn code trên, bạn chỉ cần thay đổi giá trị của biến $file_path và tham số thứ 2 của hàm output_file để tải file mà bạn muốn.

Với đoạn mã PHP đơn giản này, bạn có thể tải file từ trang web của mình chỉ với một click. Điều này sẽ giúp tiết kiệm thời gian và tăng trải nghiệm người dùng trên trang web của bạn.

Bài viết tham khảo: Ép download file bằng PHP

code Snippets, download, file, PHP tips, Ép download file Hình ảnh chỉ mang tính chất minh họa

Nguồn ảnh: nanado.edu.vn

1