PHP Curl Multi-threaded batch open URL class

Source: Internet
Author: User
PHP Curl Multi-threaded batch open URL class

The code is as follows:

Class curl_multi{
Curl Handle
Private $curl _handle=null;
Url
Private $url _list=array ();
Parameters
Private $curl _setopt=array (
' Curlopt_returntransfer ' =>1,//returns the result to the variable
' Curlopt_header ' =>0,//want an HTTP header?
' Curlopt_nobody ' =>0,//not content?
' Curlopt_followlocation ' =>0,//automatic tracking
' Curlopt_timeout ' =>6//timeout (s)
);
function __construct ($seconds =30) {
Set_time_limit ($seconds);
}
/*
* Set URL
* @list Array
*/
Public Function Seturllist ($list =array ()) {
$this->url_list= $list;
}
/*
* Set parameters
* @cutPot Array
*/
Public Function setopt ($cutPot) {
$this->curl_setopt= $cutPot + $this->curl_setopt;
}
/*
* Implementation
* @return Array
*/
Public function exec () {
$MH =curl_multi_init ();
foreach ($this->url_list as $i = + $url) {
$conn [$i]=curl_init ($url);
foreach ($this->curl_setopt as $key = + $val) {
curl_setopt ($conn [$i],preg_replace ('/(Curlopt_\w{1,})/ie ', ' $ A ', $key), $val);
}
Curl_multi_add_handle ($MH, $conn [$i]);
}
$active =false;
do{
$MRC =curl_multi_exec ($MH, $active);
}while ($MRC ==curlm_call_multi_perform);

while ($active and $MRC ==curlm_ok) {
if (Curl_multi_select ($MH)! =-1) {
do{
$MRC =curl_multi_exec ($MH, $active);
}while ($MRC ==curlm_call_multi_perform);
}
}
$res =array ();
foreach ($this->url_list as $i = + $url) {
$res [$i]=curl_multi_getcontent ($conn [$i]);
Curl_close ($conn [$i]);
Curl_multi_remove_handle ($MH, $conn [$i]);//Release resources
}
Curl_multi_close ($MH);
return $res;
}

}

Examples of use are:

$url _array=array (' http://www.baidu.com ', ' http://www.scutephp.com ', ' http://www.taobao.com ');

$curl =new Curl_multi;
$curl->seturllist ($url _array);
$result = $curl->exec ();
Echo '
';
Print_r ($result);
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.