CURL - 获取HTTP代码 [英] CURL - Getting HTTP code
问题描述
使用CURL获取网站的状态(如果网站上/下或重定向到其他网站)。我想尽可能精简,但是效果不好。
Im using CURL to get the status of a site, if its up/down or redirecting to another site. I want to get it as streamlined as possible, but it's not working well.
<?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;
?>
我有一个函数。它工作正常,但性能不是最好的,因为它下载整个页面,如果我删除 $ output = curl_exec($ ch);
它返回 0
所有的时间。
I have this wrapped in a function. It works fine but performance is not the best because it downloads the whole page, thing in if I remove $output = curl_exec($ch);
it returns 0
all the time.
有谁知道如何使性能更好?
Does anyone know how to make the performance better?
推荐答案
首先确保url是否真正有效(一个字符串,不是空的,好的语法),这是快速检查服务器端。例如,这样做可以节省很多时间:
first make sure if the url is actually valid (a string, not empty, good syntax), this is quick to check server side. for example, doing this first could save a lot of time:
if(!$url || !is_string($url) || ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url)){
return false;
}
请确保您只获取标题,而不是正文内容:
make sure you only fetch the headers, not the body content:
@curl_setopt($ch, CURLOPT_HEADER , true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY , true); // we don't need body
有关获取url状态的详细信息http代码我指的是另一个帖子我做了(它也有助于以下重定向):
for more details on getting the url status http code I refer to another post I made (it also helps with following redirects):
- check if an URL exists in PHP
作为一个整体:
$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;
这篇关于CURL - 获取HTTP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!