Asynchronous cURL using POST

若如初见. 提交于 2019-12-04 10:53:27

You'll need to create a new curl handle for every request, and then register it with http://www.php.net/manual/en/function.curl-multi-add-handle.php

here is some code i ripped out and adapted from my code base, have in mind that you should add error checking in there.

function CreateHandle($url , $data) {
    $curlHandle = curl_init($url);

    $defaultOptions = array (
        CURLOPT_COOKIEJAR => 'cookies.txt' ,
        CURLOPT_COOKIEFILE => 'cookies.txt' ,

        CURLOPT_ENCODING => "gzip" ,
        CURLOPT_FOLLOWLOCATION => true ,
        CURLOPT_RETURNTRANSFER => true ,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data
    );

    curl_setopt_array($curlHandle , $defaultOptions);

    return $curlHandle;
}

function MultiRequests($urls , $data) {
    $curlMultiHandle = curl_multi_init();

    $curlHandles = array();
    $responses = array();

    foreach($urls as $id => $url) {
        $curlHandles[$id] = CreateHandle($url , $data[$id]);
        curl_multi_add_handle($curlMultiHandle, $curlHandles[$id]);
    }

    $running = null;
    do {
        curl_multi_exec($curlMultiHandle, $running);
    } while($running > 0);

    foreach($curlHandles as $id => $handle) {
        $responses[$id] = curl_multi_getcontent($handle);
        curl_multi_remove_handle($curlMultiHandle, $handle);
    }
    curl_multi_close($curlMultiHandle);

    return $responses;
}

There's a faster, more efficient option ... that doesn't require that you use any curl at all ...

http://uk3.php.net/manual/en/book.pthreads.php http://pthreads.org

See github for latest source, releases on pecl ....

I will say this, file_get_contents may seem appealing, but PHP was never designed to run threaded in this manner, it's socket layers and the like give no thought to consumption you might find that it's better to fopen and sleep inbetween little reads to conserve CPU usage ... however you do it it will be much better ... and how you do it depends on what kind of resources you want to dedicate the task ...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!