@@ -7,7 +7,6 @@ class MultiCurl
7
7
public $ baseUrl = null ;
8
8
public $ multiCurl ;
9
9
public $ curls = array ();
10
- private $ curlFileHandles = array ();
11
10
private $ nextCurlId = 1 ;
12
11
private $ isStarted = false ;
13
12
@@ -75,20 +74,23 @@ public function addDownload($url, $mixed_filename)
75
74
$ curl = new Curl ();
76
75
$ curl ->setURL ($ url );
77
76
77
+ // Use tmpfile() or php://temp to avoid "Too many open files" error.
78
78
if (is_callable ($ mixed_filename )) {
79
79
$ callback = $ mixed_filename ;
80
80
$ curl ->downloadCompleteFunction = $ callback ;
81
- $ fh = tmpfile ();
81
+ $ curl -> fileHandle = tmpfile ();
82
82
} else {
83
83
$ filename = $ mixed_filename ;
84
- $ fh = fopen ($ filename , 'wb ' );
84
+ $ curl ->downloadCompleteFunction = function ($ instance , $ fh ) use ($ filename ) {
85
+ file_put_contents ($ filename , stream_get_contents ($ fh ));
86
+ };
87
+ $ curl ->fileHandle = fopen ('php://temp ' , 'wb ' );
85
88
}
86
89
87
- $ curl ->setOpt (CURLOPT_FILE , $ fh );
90
+ $ curl ->setOpt (CURLOPT_FILE , $ curl -> fileHandle );
88
91
$ curl ->setOpt (CURLOPT_CUSTOMREQUEST , 'GET ' );
89
92
$ curl ->setOpt (CURLOPT_HTTPGET , true );
90
93
$ this ->addHandle ($ curl );
91
- $ this ->curlFileHandles [$ curl ->id ] = $ fh ;
92
94
return $ curl ;
93
95
}
94
96
@@ -516,6 +518,10 @@ public function setUserAgent($user_agent)
516
518
*/
517
519
public function start ()
518
520
{
521
+ if ($ this ->isStarted ) {
522
+ return ;
523
+ }
524
+
519
525
foreach ($ this ->curls as $ ch ) {
520
526
$ this ->initHandle ($ ch );
521
527
}
@@ -536,9 +542,8 @@ public function start()
536
542
unset($ this ->curls [$ key ]);
537
543
538
544
// Close open file handles and reset the curl instance.
539
- if (isset ($ this ->curlFileHandles [$ ch ->id ])) {
540
- $ ch ->downloadComplete ($ this ->curlFileHandles [$ ch ->id ]);
541
- unset($ this ->curlFileHandles [$ ch ->id ]);
545
+ if (!($ ch ->fileHandle === null )) {
546
+ $ ch ->downloadComplete ($ ch ->fileHandle );
542
547
}
543
548
break ;
544
549
}
0 commit comments