Hướng dẫn php download big file from url - php tải xuống tệp lớn từ url

Sao chép tệp một đoạn nhỏ cùng một lúc

/**
 * Copy remote file over HTTP one small chunk at a time.
 *
 * @param $infile The full URL to the remote file
 * @param $outfile The path where to save the file
 */
function copyfile_chunked($infile, $outfile) {
    $chunksize = 10 * (1024 * 1024); // 10 Megs

    /**
     * parse_url breaks a part a URL into it's parts, i.e. host, path,
     * query string, etc.
     */
    $parts = parse_url($infile);
    $i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
    $o_handle = fopen($outfile, 'wb');

    if ($i_handle == false || $o_handle == false) {
        return false;
    }

    if (!empty($parts['query'])) {
        $parts['path'] .= '?' . $parts['query'];
    }

    /**
     * Send the request to the server for the file
     */
    $request = "GET {$parts['path']} HTTP/1.1\r\n";
    $request .= "Host: {$parts['host']}\r\n";
    $request .= "User-Agent: Mozilla/5.0\r\n";
    $request .= "Keep-Alive: 115\r\n";
    $request .= "Connection: keep-alive\r\n\r\n";
    fwrite($i_handle, $request);

    /**
     * Now read the headers from the remote server. We'll need
     * to get the content length.
     */
    $headers = array();
    while(!feof($i_handle)) {
        $line = fgets($i_handle);
        if ($line == "\r\n") break;
        $headers[] = $line;
    }

    /**
     * Look for the Content-Length header, and get the size
     * of the remote file.
     */
    $length = 0;
    foreach($headers as $header) {
        if (stripos($header, 'Content-Length:') === 0) {
            $length = (int)str_replace('Content-Length: ', '', $header);
            break;
        }
    }

    /**
     * Start reading in the remote file, and writing it to the
     * local file one chunk at a time.
     */
    $cnt = 0;
    while(!feof($i_handle)) {
        $buf = '';
        $buf = fread($i_handle, $chunksize);
        $bytes = fwrite($o_handle, $buf);
        if ($bytes == false) {
            return false;
        }
        $cnt += $bytes;

        /**
         * We're done reading when we've reached the conent length
         */
        if ($cnt >= $length) break;
    }

    fclose($i_handle);
    fclose($o_handle);
    return $cnt;
}

Điều chỉnh biến $ chunksize theo nhu cầu của bạn. Điều này chỉ được thử nghiệm nhẹ. Nó có thể dễ dàng phá vỡ vì một số lý do.

Usage:

copyfile_chunked('http://somesite.com/somefile.jpg', '/local/path/somefile.jpg');

Kịch bản:

Có các phương pháp chuyên nghiệp khác để tải xuống các tệp lớn với PHP như Curl hoặc & NBSP; ________ 5. Nhưng nếu bạn chỉ muốn sử dụng giải pháp PHP thuần túy, tập lệnh trên sẽ hoạt động cho hầu hết các trường hợp sử dụng.
Tệp này chứa văn bản unicode hai chiều có thể được giải thích hoặc biên dịch khác với những gì xuất hiện dưới đây. Để xem xét, hãy mở tệp trong một trình soạn thảo cho thấy các ký tự Unicode ẩn. Tìm hiểu thêm về các ký tự unicode hai chiều
/**
* Tải xuống một tập tin lớn ở xa đến một điểm đến cục bộ.
*
/**
* Tải xuống một tập tin lớn ở xa đến một điểm đến cục bộ.
/**
* Tải xuống một tập tin lớn ở xa đến một điểm đến cục bộ.
*
* Tệp để tải xuống
* @param ressource $ Dest
* Đường dẫn tệp cục bộ hoặc Ressource (Trình xử lý tệp)
* @return boolean true hoặc thông báo lỗi
*/
Chức năng tĩnh công khai DownloadDistantFile ($ url, $ Dest)
{
$ tùy chọn = mảng (
Curlopt_file => is_resource ($ dest)? $ Dest: Fopen ($ Dest, 'W'),> is_resource($dest) ? $dest : fopen($dest, 'w'),
Curlopt_followlocation => true,> true,
Curlopt_url => $ url,> $url,
Curlopt_failonerror => true, // mã http> 400 sẽ ném lỗi Curl> true, // HTTP code > 400 will throw curl error
);
$ CH = curl_init ();
curl_setopt_array ($ CH, $ tùy chọn);
$ return = curl_exec ($ CH);
if ($ return === false)
{
trả về curl_error ($ CH);
}
khác
{
trả về curl_error ($ CH);
}
}

Nói chung, các tệp được tải xuống được tải vào bộ nhớ dưới dạng mảng byte.Đây không phải là vấn đề khi xử lý các tệp nhỏ, nhưng trong trường hợp các tệp lớn (XXX MB hoặc GB), một tác vụ đơn giản như tải xuống tệp có thể dẫn đến lỗi ngoài bộ nhớ.Phương pháp đơn giản nhất để giải quyết vấn đề này trong PHP là chunking.Hãy cùng xem làm thế nào để thực hiện điều đó trong hướng dẫn này.Chunking. Let’s see how to accomplish that in this tutorial.

Prerequisite:

  1. Php 5.6 trở lên
  2. Enable allow_fopen_url in php.ini
  3. fopen (), đọc () và write () hàm.

Kịch bản:

$url = 'https://my_file_url';

// use basename() function to get the file name
$file_name = basename($url);

# 8 MB per one chunk of file.
$chunk_size = 8 * (1024 * 1024);

# send the proper headers to the browser
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment;filename="' . basename($filename) . '"');

// load the URL as a stream
$input_stream = fopen($url, 'r');

// this will download the file from the web in small chunks
if ($input_stream) {
    // save the file to the current directory
    $output_stream = fopen('./' . $file_name, 'wb');

    if ($output_stream) {
        // set the buffer size to 8Mb which is suitable for downloading large files
        while (!feof($input_stream)) {
            $chunk = fread($input_stream, $chunk_size);
            fwrite($output_stream, $chunk, $chunk_size);
        }
    }
}
if ($input_stream) {
    fclose($input_stream);
}
if ($output_stream) {
    fclose($output_stream);
}

Conclusion:

Có các phương pháp chuyên nghiệp khác để tải xuống các tệp lớn với PHP như Curl hoặc & NBSP; ________ 5.Nhưng nếu bạn chỉ muốn sử dụng giải pháp PHP thuần túy, tập lệnh trên sẽ hoạt động cho hầu hết các trường hợp sử dụng.