Aar*_*ire 155 php performance curl http-headers
我正在使用CURL来获取站点的状态,如果它是向上/向下或重定向到另一个站点.我希望尽可能简化它,但效果不佳.
<?php
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
?>
Run Code Online (Sandbox Code Playgroud)
我把它包裹在一个函数中.它工作正常,但性能不是最好的,因为它下载整个页面,如果我删除$output = curl_exec($ch);它返回0所有的时间.
有谁知道如何使性能更好?
Moo*_*ite 230
首先确保URL实际上是否有效(字符串,而不是空,良好的语法),这可以快速检查服务器端.例如,首先执行此操作可以节省大量时间:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
Run Code Online (Sandbox Code Playgroud)
确保只获取标题,而不是正文内容:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
Run Code Online (Sandbox Code Playgroud)
有关获取URL状态http代码的更多详细信息,请参阅我发布的另一篇文章(它还有助于以下重定向):
整体来说:
$url = 'http://www.example.com';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo 'HTTP code: ' . $httpcode;
Run Code Online (Sandbox Code Playgroud)
Dee*_*tel 117
// must set $url first....
$http = curl_init($url);
// do your curl thing here
$result = curl_exec($http);
$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);
curl_close($http);
echo $http_status;
Run Code Online (Sandbox Code Playgroud)
小智 22
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$rt = curl_exec($ch);
$info = curl_getinfo($ch);
echo $info["http_code"];
Run Code Online (Sandbox Code Playgroud)
Rap*_*eta 15
试试PHP的" get_headers "功能.
有点像:
<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
Run Code Online (Sandbox Code Playgroud)
curl_getinfo\xe2\x80\x94 获取有关特定传输的信息
<?php\n// Create a curl handle\n$ch = curl_init(\'http://www.yahoo.com/\');\n\n// Execute\ncurl_exec($ch);\n\n// Check if any error occurred\nif(!curl_errno($ch))\n{\n $info = curl_getinfo($ch);\n\n echo \'Took \' . $info[\'total_time\'] . \' seconds to send a request to \' . $info[\'url\'];\n}\n\n// Close handle\ncurl_close($ch);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
196974 次 |
| 最近记录: |