MDL-27125 better manage file handles when downloading multiple files.

Based on Dongsheng Cai's branch: s11_MDL-27125_curl_file_handler_master
This commit is contained in:
Jonathan Harker
2012-06-20 16:46:29 +12:00
parent f4a9bf65da
commit def4a8f5b7
3 changed files with 43 additions and 8 deletions
+41 -8
View File
@@ -2993,14 +2993,36 @@ class curl {
* Calls {@link multi()} with specific download headers
*
* <code>
* $c = new curl;
* $c = new curl();
* $file1 = fopen('a', 'wb');
* $file2 = fopen('b', 'wb');
* $c->download(array(
* array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
* array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
* array('url'=>'http://localhost/', 'file'=>$file1),
* array('url'=>'http://localhost/20/', 'file'=>$file2)
* ));
* fclose($file1);
* fclose($file2);
* </code>
*
* or
*
* <code>
* $c = new curl();
* $c->download(array(
* array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
* array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
* ));
* </code>
*
* @param array $requests An array of files to request
* @param array $requests An array of files to request {
* url => url to download the file [required]
* file => file handler, or
* filepath => file path
* }
* If 'file' and 'filepath' parameters are both specified in one request, the
* open file handle in the 'file' parameter will take precedence and 'filepath'
* will be ignored.
*
* @param array $options An array of options to set
* @return array An array of results
*/
@@ -3024,11 +3046,15 @@ class curl {
$results = array();
$main = curl_multi_init();
for ($i = 0; $i < $count; $i++) {
$url = $requests[$i];
foreach($url as $n=>$v){
$options[$n] = $url[$n];
if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
// open file
$requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
$requests[$i]['auto-handle'] = true;
}
$handles[$i] = curl_init($url['url']);
foreach($requests[$i] as $n=>$v){
$options[$n] = $v;
}
$handles[$i] = curl_init($requests[$i]['url']);
$this->apply_opt($handles[$i], $options);
curl_multi_add_handle($main, $handles[$i]);
}
@@ -3045,6 +3071,13 @@ class curl {
curl_multi_remove_handle($main, $handles[$i]);
}
curl_multi_close($main);
for ($i = 0; $i < $count; $i++) {
if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
// close file handler if file is opened in this function
fclose($requests[$i]['file']);
}
}
return $results;
}