CURLOPT_FILE, curl_multi_exec and fclose

I built a curl class that can load images in parallel using curl_multi_init.

Download function below

public function download(AbstractRequest $request, $f) {

    // Initiate a new curl
    $ch = curl_init();
    // Set curl options
    curl_setopt_array($ch, [
        CURLOPT_URL => $request->getUrl(),
        CURLOPT_FILE => $f,
        CURLOPT_TIMEOUT => 99,
    ]);
    // Add to curl multi handle
    curl_multi_add_handle($this->multiCh, $ch);
}

destructor for the class invokes parallel queries.

My question is: how can I return a file resource from curl_multi_execto close it with fclose()?

Is curl automatically closing a file descriptor for me?

thank

+4
source share
1 answer

cURL, PHP cURL. PHP , script , script , cURL, .

PHP flush , .

:

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// open two temp files for requests
$fp1 = fopen('/tmp/1.txt', 'w+');
$fp2 = fopen('/tmp/2.txt', 'w+');

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch1, CURLOPT_FILE, $fp1);

curl_setopt($ch2, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_FILE, $fp2);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
echo "Begin requests\n";
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

echo "Done\n";

var_dump($fp1, $fp2); // valid resources

echo "Sleep\n";
sleep(10);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

fwrite($fp1, "\n\nTEST MORE DATA\n");
fwrite($fp2, "\n\nAND MORE TEST DATA\n");

var_dump($fp1, $fp2); // valid file handles

echo "Last sleep\n";
sleep(10);

// data automatically flushed to disk here
// file handles will be closed by PHP when script terminates here

, , , cURL. . PHP 7.0.5 5.6.20.

, PHP/cURL . CURLOPT_FILE ch->handlers->write->fp .

, .

, :

$fileHandles = array();
//..
$fileHandles[] = $fp1;
$fileHandles[] = $fp2;

, curl_multi_exec :

foreach($fileHandles as $fp) {
    fclose($fp);
}

: cURL PHP , PHP .

cURL, . script, , .

+2

All Articles