-
-
Save seyfer/98110fd07beaa2eab97e1898e38ba7d9 to your computer and use it in GitHub Desktop.
Curl PHP multiple files downloading
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 | |
function multiple_download(array $urls, $save_path = '/tmp') | |
{ | |
$multi_handle = curl_multi_init(); | |
$file_pointers = []; | |
$curl_handles = []; | |
// Add curl multi handles, one per file we don't already have | |
foreach ($urls as $key => $url) { | |
$file = $save_path . '/' . basename($url); | |
if(!is_file($file)) { | |
$curl_handles[$key] = curl_init($url); | |
$file_pointers[$key] = fopen($file, "w"); | |
curl_setopt($curl_handles[$key], CURLOPT_FILE, $file_pointers[$key]); | |
curl_setopt($curl_handles[$key], CURLOPT_HEADER, 0); | |
curl_setopt($curl_handles[$key], CURLOPT_CONNECTTIMEOUT, 60); | |
curl_multi_add_handle($multi_handle,$curl_handles[$key]); | |
} | |
} | |
// Download the files | |
do { | |
curl_multi_exec($multi_handle,$running); | |
} while ($running > 0); | |
// Free up objects | |
foreach ($urls as $key => $url) { | |
curl_multi_remove_handle($multi_handle, $curl_handles[$key]); | |
curl_close($curl_handles[$key]); | |
fclose ($file_pointers[$key]); | |
} | |
curl_multi_close($multi_handle); | |
} | |
// Files to download | |
$urls = [ | |
'http://static.scribd.com/docs/cdbwpohq0ayey.pdf', | |
'http://static.scribd.com/docs/8wyxlxfufftas.pdf', | |
'http://static.scribd.com/docs/9q29bbglnc2gk.pdf' | |
]; | |
multiple_download($urls); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment