Hướng dẫn download remote file php - tải xuống tệp từ xa php

Trang chủ & nbsp; & nbsp; Cách buộc tải xuống tệp từ máy chủ từ xa trong PHP

Trong ứng dụng web, nói chung, tệp được tải xuống từ cùng một máy chủ. Nhưng đôi khi tập tin cần được tải xuống từ máy chủ từ xa. Để tải xuống tệp với PHP, bạn cần buộc trình duyệt tải xuống tệp. Buộc tải xuống trong PHP giúp tải xuống các tệp từ máy chủ và lưu chúng vào ổ đĩa cục bộ.

Trong đoạn mã ví dụ, chúng tôi sẽ chỉ cho bạn cách buộc tải xuống tệp từ URL trong PHP. Bạn có thể tải xuống bất kỳ loại tệp nào [hình ảnh, zip, video, âm thanh, v.v.] từ máy chủ từ xa bằng PHP.

Sử dụng hàm readFile [] với tiêu đề loại nội dung application/x-file-to-save, để tải xuống tệp zip từ URL từ xa bằng PHP.readfile[] function with application/x-file-to-save Content-type header, to download a ZIP file from remote URL using PHP.

// Remote download URL
$remoteURL '//www.example.com/files/project.zip';// Force download
header["Content-type: application/x-file-to-save"]; 
header["Content-Disposition: attachment; filename=".basename[$remoteURL]];
ob_end_clean[];
readfile[$remoteURL];
exit;

Lưu ý rằng: hàm ob_end_clean [] sẽ giúp tải xuống một tệp lớn từ máy chủ từ xa trong PHP.ob_end_clean[] function will help to download a large file from the remote server in PHP.

I want to download a remote file with php, save it and output it to the user. I want to buffer files because some users can download the same file at the same time and save bandwidth.

I found a script to download a file from remote server directly:

set_time_limit[0];

$url = '//example.com/example.zip';
$file = basename[$url];

$fp = fopen[$file, 'w'];

$ch = curl_init[$url];
curl_setopt[$ch, CURLOPT_FILE, $fp];

$data = curl_exec[$ch];

curl_close[$ch];
fclose[$fp];

header['Content-Description: File Transfer'];
header['Content-Type: application/octet-stream'];
header['Content-Disposition: attachment; filename='.basename[$file]];
header['Content-Transfer-Encoding: binary'];
header['Expires: 0'];
header['Cache-Control: must-revalidate'];
header['Pragma: public'];
header['Content-Length: ' . filesize[$file]];
ob_clean[];
flush[];
readfile[$file];
exit;

Chin Leung

14.2k3 gold badges28 silver badges54 bronze badges3 gold badges28 silver badges54 bronze badges

asked Feb 7, 2018 at 16:55Feb 7, 2018 at 16:55

2

Here a little snippet.

You check locally if the file exists, if so: you fetch the content and send it to the client.

Otherwise you make the curl request to fetch and store the file content

set_time_limit[0];

$url = '//example.com/example.zip';

$file = basename[$url];
if[!file_exists[$file]] {
    $ch = curl_init[$url];
    curl_setopt[$ch, CURLOPT_RETURNTRANSFER, true];
    $data = curl_exec[$ch];
    curl_close[$ch];
    file_put_contents[$file, $data];
}

header['Content-Description: File Transfer'];
header['Content-Type: application/octet-stream'];
header['Content-Disposition: attachment; filename='.basename[$file]];
header['Content-Transfer-Encoding: binary'];
header['Expires: 0'];
header['Cache-Control: must-revalidate'];
header['Pragma: public'];
header['Content-Length: ' . filesize[$file]];
ob_clean[];
flush[];
readfile[$file];
exit;

answered Feb 7, 2018 at 17:07Feb 7, 2018 at 17:07

3

Đã đăng vào Dec 3rd, 2021 12:47 a.m. 2 phút đọc 2 phút đọc

Hôm nay mình xin chia sẻ kinh nghiệm cách download file csv từ 1 FTP, SFTP server về local của mình và đọc file csv đó,sau đó sẽ hiển thị ra dữ liệu. Hiện tại trên FTP, SFTP server mình đã uploaded sẵn 1 file csv có tên là SampleCSV.csv, bên dưới đây là các bước kết nối đến FTP,SFTP server, download về local, hiển thị dữ liệu.1. Thực hiện kết nối đến FTP server
Hiện tại trên FTP, SFTP server mình đã uploaded sẵn 1 file csv có tên là SampleCSV.csv,
bên dưới đây là các bước kết nối đến FTP,SFTP server, download về local, hiển thị dữ liệu.
1. Thực hiện kết nối đến FTP server

// 1. Kết nối và login to FTP server
$ftp_server = "Your host name";
$ftp_conn = ftp_connect[$ftp_server] or die["Could not connect to $ftp_server"];
$login = ftp_login[$ftp_conn, 'Your user name', 'Your password'];
ftp_pasv[$ftp_conn, TRUE];

// 2.Khái báo 2 biến như bên dưới
$local_file = $_SERVER['DOCUMENT_ROOT']."/SampleCSV.csv"; // Đường dẫn dến file csv trên local của mình[Ban đầu chưa có file nhé]
$server_file = "SampleCSV.csv";//tên file csv trên FPT server

// 3.Cấp quyền cho file csv
if [file_exists[$local_file]] {
        chmod[$local_file, 0777];
}

// 4. Thực hiện download file về local
if [ftp_get[$ftp_conn, $local_file, $server_file, FTP_ASCII]] {
            if [file_exists[$local_file]] {
                if [[$handle = fopen[$local_file, "r"]] !== FALSE] {
                    while [[$data = fgetcsv[$handle, 99999, ","]] !== FALSE] {
                        echo "
";
                        print_r[$data]; // hiển thị dữ liệu tương ứng với mỗi row trong file csv
                        echo "
"
; } fclose[$handle]; } } else { echo "File không tồn tại dưới local"; } } else { echo "Xẩy ra lỗi trong quá trình download file về local"; }

2. Thực hiện kết nối đến SFTP server bằng libssh2 library Do mình sẽ dùng libssh2 library để kết nối đến SFTP server, hiện tại trên server local của mình[xampp] chưa cài đặt libssh2 library, do đó mình sẽ thực hiện download và cài đặt trên server local của mình trước nhé. Link download: //pecl.php.net/package/ssh2 Version mới nhất ở thời điểm mình làm ví dụ là 1.3.1 như ảnh bên dưới và click vào icon windows màu xanh có chứ DLL.
Do mình sẽ dùng libssh2 library để kết nối đến SFTP server, hiện tại trên server local của mình[xampp] chưa cài đặt libssh2 library,
do đó mình sẽ thực hiện download và cài đặt trên server local của mình trước nhé.
Link download: //pecl.php.net/package/ssh2
Version mới nhất ở thời điểm mình làm ví dụ là 1.3.1 như ảnh bên dưới và click vào icon windows màu xanh có chứ DLL.

Màn hình tiếp theo mình sẽ chọn bản phù hợp với phiên bản php hiện tại mình đang dùng là php 7.4

Giải nén file vừa download về và copy 2 files php_ssh2.dll, php_ssh2.pdb trong folder giải nén vào thư mục xampp\php\ext trên server local như ảnh bên dưới.

Bước tiếp theo để sử dụng được thư viện này chúng ta phải vào file php.ini để thêm dòng ở ô màu đỏ bên dưới để enable thư viện đó nhé.

Bây giờ mình sẽ khơi động lại xampp để viết code sử dụng thư viện libssh2 nhé!

Source code:

    $connection = ssh2_connect['Your host name'];
     
    // Kiểm tra login
    if [!ssh2_auth_password[$connection, 'Your user name', 'Your password']] {
        throw new Exception['Unable to connect.'];
    } else {
        echo "connected";
    }

    // Tạo kết nối đến SFTP server
    if [!$sftp = ssh2_sftp[$connection]] {
        throw new Exception['Unable to create SFTP connection.'];
    } else {
        echo "connected2";
    }

    //Biến chứa danh sách các files sẽ lấy từ SFTP server
    $files = array[];
    //Đường dẫn thư mục chứa file csv trên SFTP server
    $dirHandle = opendir["ssh2.sftp://$sftp/csv/"];
     
    // Tìm các files trong thư mục, bỏ qua các files có đuôi kiểu [. & ..]
    while [false !== [$file = readdir[$dirHandle]]] {
        if [$file != '.' && $file != '..'] {
            $files[] = $file;
        }
    }

    // Đường dẫn dến file csv trên local của mình[Ban đầu chưa có file nhé]
    $local_file = $_SERVER['DOCUMENT_ROOT']."/localDirectory/SampleCSV.csv";
    if [count[$files]] {
        foreach [$files as $fileName] {
            if [$fileName == "SampleCSV.csv"] {
                // Remote stream
                if [!$remoteStream = @fopen["ssh2.sftp://$sftp/csv/$fileName", 'r']] {
                    throw new Exception["Unable to open remote file: $fileName"];
                } 
         
                // Local stream
                if [!$localStream = @fopen[$_SERVER['DOCUMENT_ROOT']."/localDirectory/$fileName", 'w']] {
                    throw new Exception["Unable to open local file for writing: /localDirectory/$fileName"];
                }
         
                // Write from our remote stream to our local stream
                $read = 0;
                $fileSize = filesize["ssh2.sftp://$sftp/csv/$fileName"];
                while [$read 

Bài Viết Liên Quan

Chủ Đề