使用curl获取PHP中的HTTP代码 [英] Getting HTTP code in PHP using curl

查看:93
本文介绍了使用curl获取PHP中的HTTP代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CURL来获取网站的状态(如果该网站处于打开/关闭状态或重定向到另一个网站).我想使其尽可能地精简,但是效果不佳.

I'm using CURL to get the status of a site, if it's 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):

整体上:

$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获取PHP中的HTTP代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆