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);