Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $urls = array(
- "http://www.google.com",
- "http://www.yahoo.com",
- );
- $mh = curl_multi_init();
- $activeDownloads = array();
- foreach ($urls as $i => $url) {
- $curlHandle = curl_init();
- $key = (int) $curlHandle;
- curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true);
- // curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curlHandle, CURLOPT_HEADER, 0);
- curl_setopt($curlHandle, CURLOPT_URL, $url);
- $destinationFilepath = '/tmp/download_' . $key;
- $file = fopen($destinationFilepath, "w");
- curl_setopt($curlHandle, CURLOPT_FILE, $file);
- curl_multi_add_handle($mh, $curlHandle);
- $activeDownloads[$key] = array(
- 'url' => $url,
- 'filepath' => $destinationFilepath,
- 'filehandle' => $file,
- );
- }
- while (true) {
- usleep(50000);
- curl_multi_exec($mh, $running);
- // Call select to see if anything is waiting for us
- $select = curl_multi_select($mh);
- if ($select < 1) {
- // echo 'No download is ready yet' . PHP_EOL;
- continue;
- }
- // Since something's waiting, give curl a chance to process it
- do {
- $status = curl_multi_exec($mh, $running);
- usleep(10000);
- } while ($status == CURLM_CALL_MULTI_PERFORM || $running);
- // Now grab the information about the completed requests
- while ($info = curl_multi_info_read($mh)) {
- $ch = $info['handle'];
- $key = (int) $ch;
- // This outputs all the content correctly when CURLOPT_RETURNTRANSFER is true and the CURLOPT_FILE flag is not set
- // $content = curl_multi_getcontent($ch);
- // var_dump($content);
- // die;
- $download = $activeDownloads[$key];
- // This is needed!!! Without this the file_get_contents() below only reads the first 40960 characters!
- fclose($download['filehandle']);
- $info = curl_getinfo($ch);
- curl_close($ch);
- // print_r($info); die;
- $content = file_get_contents($download['filepath']);
- // This output is cut off at 40960 characters if the original filehandle is not closed first, why?
- echo $content . PHP_EOL;
- echo strlen($content) . PHP_EOL;
- die;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement