In certain situations, it is often necessary to obtain the http status code of the accessed page without returning the content of the page. How can such a function be achieved? Please see the key code below:
[php]
Function GetHttpStatusCode($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);//Get content url
curl_setopt($curl,CURLOPT_HEADER,1);//Get http header information
curl_setopt($curl,CURLOPT_NOBODY,1);//Does not return html body information
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//Return the data stream, no direct output
curl_setopt($curl,CURLOPT_TIMEOUT,30); //Timeout duration, unit seconds
curl_exec($curl);
$rtn= curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
return
}
$url="http://www.BkJia.com";
echo GetHttpStatusCode($url);
?>
function GetHttpStatusCode($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);//Get content url
curl_setopt($curl,CURLOPT_HEADER,1);//Get http header information
curl_setopt($curl,CURLOPT_NOBODY,1);//Does not return html body information
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//Return the data stream, do not output directly
curl_setopt($curl,CURLOPT_TIMEOUT,30); //Timeout duration, unit seconds
curl_exec($curl);
$rtn= curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
Return $rtn;
}
$url="http://www.BkJia.com";
echo GetHttpStatusCode($url);
?>
If Baidu can be accessed normally, of course the result of running the above code will be 200.
For detailed usage of curl, please refer to: http://cn2.php.net/manual/zh/ref.curl.php
Excerpted from The Pure Land of the Soul