Created
October 3, 2011 09:47
-
-
Save damienalexandre/1258787 to your computer and use it in GitHub Desktop.
Download large file from the web via php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Download a large distant file to a local destination. | |
* | |
* This method is very memory efficient :-) | |
* The file can be huge, PHP doesn't load it in memory. | |
* | |
* /!\ Warning, the return value is always true, you must use === to test the response type too. | |
* | |
* @author dalexandre | |
* @param string $url | |
* The file to download | |
* @param ressource $dest | |
* The local file path or ressource (file handler) | |
* @return boolean true or the error message | |
*/ | |
public static function downloadDistantFile($url, $dest) | |
{ | |
$options = array( | |
CURLOPT_FILE => is_resource($dest) ? $dest : fopen($dest, 'w'), | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_URL => $url, | |
CURLOPT_FAILONERROR => true, // HTTP code > 400 will throw curl error | |
); | |
$ch = curl_init(); | |
curl_setopt_array($ch, $options); | |
$return = curl_exec($ch); | |
if ($return === false) | |
{ | |
return curl_error($ch); | |
} | |
else | |
{ | |
return true; | |
} | |
} |
Nicely done. Thanks mate!
public static function uploadFromRemoteServer(string $remoteFileURL, mixed $destinationFilepath): string|bool
{
$options = [
CURLOPT_URL => $remoteFileURL,
CURLOPT_FILE => is_resource($destinationFilepath) ? $destinationFilepath : fopen($destinationFilepath, 'wb'),
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_FAILONERROR => true,
];
$curl = curl_init();
curl_setopt_array($curl, $options);
$returnResult = curl_exec($curl);
return (false === $returnResult) ? curl_error($curl) : true;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great snippet, saved me a bunch of time transferring files between servers, good job! Transferred 1.2Gb file in around 30 seconds