时间:2021-07-01 10:21:17 帮助过:4人阅读
curl函数使用代码
publicfunctionxcurl($url,$ref=null,$post=array(),$ua="Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre",$print=false) {$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
if(!empty($ref)) {
curl_setopt($ch, CURLOPT_REFERER, $ref);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($ua)) {
curl_setopt($ch, CURLOPT_USERAGENT, $ua);
}
if(count($post) > 0){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
$output = curl_exec($ch);
curl_close($ch);
if($print) {
print($output);
} else {
return$output;
}
}
fsockopen 函数使用代码:
publicfunctioncurl_request_async($url, $params, $type='GET')
{// set referer$referer = $_SERVER['HTTP_HOST'];
foreach ($paramsas$key => &$val) {
if (is_array($val)) $val = implode(',', $val);
$post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);
$parts=parse_url($url);
@$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 2);
if(!$fp){
echo"$errstr ($errno)
\n";
}else{
if('GET' == $type) $parts['path'] .= '?'.$post_string;
$out = "$type ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Referer: ".$referer."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Connection: Close\r\n\r\n";
// Data goes in the request body for a POST requestif ('POST' == $type && isset($post_string)) $out.= $post_string;
fwrite($fp, $out);
fclose($fp);
}
}
仅仅 从如上的函数,使用上的区别其中重要的一点就是:
curl 请求某个Url 需要等待结果返回,而 fsockopen 不需要返回,发送请求后就继续执行代码。除非你使用 fsockopen 需要打印请求后返回的结果。
版权声明:转载请注明出处:http://blog.csdn.net/m0sh1
以上就介绍了php curl , fsockopen 函数,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。