Загрузка большого файла с помощью curl


Мне нужно загрузить удаленный файл с помощью curl.

Вот пример кода, который у меня есть:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$st = curl_exec($ch);
$fd = fopen($tmp_name, 'w');
fwrite($fd, $st);
fclose($fd);

curl_close($ch);

Но он не может обрабатывать большие файлы, потому что сначала считывает их в память.

Можно ли передать файл напрямую на диск?

Author: animuson, 2011-06-20

5 answers

<?php
set_time_limit(0);
//This is the file where we save the    information
$fp = fopen (dirname(__FILE__) . '/localfile.tmp', 'w+');
//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
// write curl response to file
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// get curl response
curl_exec($ch); 
curl_close($ch);
fclose($fp);
?>
 147
Author: TheBrain, 2015-12-19 02:44:37

Я использую эту удобную функцию:

Загрузив его с шагом 4094 байта, он не заполнит вашу память

function download($file_source, $file_target) {
    $rh = fopen($file_source, 'rb');
    $wh = fopen($file_target, 'w+b');
    if (!$rh || !$wh) {
        return false;
    }

    while (!feof($rh)) {
        if (fwrite($wh, fread($rh, 4096)) === FALSE) {
            return false;
        }
        echo ' ';
        flush();
    }

    fclose($rh);
    fclose($wh);

    return true;
}

Использование:

     $result = download('http://url','path/local/file');

Затем вы можете проверить, все ли в порядке с:

     if (!$result)
         throw new Exception('Download error...');
 22
Author: dynamic, 2013-02-12 16:48:09

Найдите ниже код, если вы хотите загрузить содержимое указанного URL-адреса, а также хотите сохранить его в файл.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

Если вы хотите загрузить файл с FTP-сервера, вы можете использовать расширение php FTP. Пожалуйста, найдите ниже код:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>
 5
Author: Sanjeev Chauhan, 2011-06-20 10:09:53

Когда curl используется для загрузки большого файла, то CURLOPT_TIMEOUT является основным параметром, для которого вы должны установить.

CURLOPT_RETURNTRANSFER должно быть правдой, если вы получаете файл, такой как pdf/csv/изображение и т.д.

Вы можете найти более подробную информацию здесь (правильный URL) Документ Curl

С этой страницы:

curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins

curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false
 3
Author: prashant pandey, 2017-03-02 08:20:03

Вы можете использовать эту функцию, которая создает временный файл в файловой системе и возвращает путь к загруженному файлу, если все работало нормально:

function getFileContents($url)
{
    // Workaround: Save temp file
    $img = tempnam(sys_get_temp_dir(), 'pdf-');
    $img .= '.' . pathinfo($url, PATHINFO_EXTENSION);

    $fp = fopen($img, 'w+');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $result = curl_exec($ch);
    curl_close($ch);

    fclose($fp);

    return $result ? $img : false;
}
 2
Author: Matthias Kleine, 2017-07-30 22:55:17