Home  >  Article  >  php教程  >  php使用curl多线程提交

php使用curl多线程提交

WBOY
WBOYOriginal
2016-06-06 19:49:001747browse

php不想java可以直接继承Thread接口或者实现Runnable接口,进行多线程的开发,不过php中提供了强大的curl工具支持多线程, php中可以使用curl_multi_init()等来模仿并行处理和多线程程序功能。同时可以使用curl_multi_init()模仿多线程的提交。如下面程序所

php不想java可以直接继承Thread接口或者实现Runnable接口,进行多线程的开发,不过php中提供了强大的curl工具支持多线程,

php中可以使用curl_multi_init()等来模仿并行处理和多线程程序功能。同时可以使用curl_multi_init()模仿多线程的提交。如下面程序所示:

<?php include "log.php";
 $stime=microtime(true); 
$urls = array(
   "http://localhost/index.php",
   "http://localhost/index.php",
   "http://localhost/index.php",
   "http://localhost/index.php",
    "http://localhost/index.php",
   "http://localhost/index.php",
   "http://localhost/index.php",
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
    $conn[$i] = curl_init($url);
    curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($conn[$i], CURLOPT_POST, 1);
    curl_setopt($conn[$i], CURLOPT_POSTFIELDS, array('offset'=>$i)); //提交数据
    curl_multi_add_handle($mh, $conn[$i]);
}

do {
    $status = curl_multi_exec($mh, $active);
    $info = curl_multi_info_read($mh);
    if (false !== $info) {
        //var_dump($info);
    }
} while ($status === CURLM_CALL_MULTI_PERFORM || $active);

foreach ($urls as $i => $url) {
    $res[$i] = curl_multi_getcontent($conn[$i]); //获取返回内容
    curl_close($conn[$i]);
}
echo "<pre class="brush:php;toolbar:false">";
print_r($res);
$etime=microtime(true);//获取程序执行结束的时间    
$total=$etime-$stime;   //计算差值     
$str_total = var_export($total, TRUE);
echo $str_total;
程序启动7个curl分别向index.php页面发送请求,在index.php中可以根据发送过来的参数来处理请求,就可以模拟多进程的并行提交了.....同时也可以应用进行

数据访问的测试!

             

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn