2

cURL を使用して、複数の接続を使用して URL から画像をダウンロードし、プロセスを高速化しようとしています。

これが私のコードです:

function multiRequest($data, $options = array()) {

// array of curl handles
$curly = array();
// data to be returned
$result = array();

// multi handle
$mh = curl_multi_init();

// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d) {

    $path = 'image_'.$id.'.png';
    if(file_exists($path)) { unlink($path); }
    $fp = fopen($path, 'x');

    $url = $d;
    $curly[$id] = curl_init($url);
    curl_setopt($curly[$id], CURLOPT_HEADER, 0);
    curl_setopt($curly[$id], CURLOPT_FILE, $fp);

    fclose($fp);

    curl_multi_add_handle($mh, $curly[$id]);
}

// execute the handles
$running = null;
do {
    curl_multi_exec($mh, $running);
} while($running > 0);


// get content and remove handles
foreach($curly as $id => $c) {
    curl_multi_remove_handle($mh, $c);
}

// all done
curl_multi_close($mh);
}

そして実行:

$data = array(
    'http://example.com/img1.png',
    'http://example.com/img2.png',
    'http://example.com/img3.png'
);

$r = multiRequest($data);

したがって、実際には機能していません。3 つのファイルが作成されますが、ゼロ バイト (空) で、次のエラー (3 回) が表示され、元の .PNG の何らかのコンテンツが出力されます。

Warning: curl_multi_exec(): CURLOPT_FILE resource has gone away, resetting to default in /Applications/MAMP/htdocs/test.php on line 34

よろしければ、それを解決する方法を教えていただけますか?

よろしくお願いします。

4

1 に答える 1

1

あなたがしているのは、ファイルハンドルを作成してから、ループの終了前に閉じることです。これにより、curl に書き込むファイルがなくなります。次のようなことを試してください:

//$fp = fopen($path, 'x'); Remove

$url = $d;
$curly[$id] = curl_init($url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_FILE, fopen($path, 'x'));

//fclose($fp); Remove
于 2013-03-10T21:47:37.380 に答える