【发布时间】:2012-08-27 09:17:00
【问题描述】:
在下面的代码中,我的网站类中的 get_status() 方法返回 1 而不是我想要的 true 或 false。谁能告诉我为什么?我认为这可能是我课堂上的一个错误,我不确定这行代码在 get_status() 方法中是否是好的做法?
$httpcode = $this->get_httpcode();
当我回显 $siteUp 时,无论我将网址设置为 http://www.google.com 还是 http://www.dsfdsfsdsdfsdfsdf.com,它始终为 1
我对面向对象的 php 相当陌生,这是我第一次自学课程,这是我正在构建的学习 oop 的示例。目的是检查一个网站的状态,并根据httpcode判断它是up还是down。
您在为什么这不起作用方面提供的任何提示都会受到极大的欢迎。提前致谢!
class website {
protected $url;
function __construct($url) {
$this->url = $url;
}
public function get_url() {
return $this->url;
}
public function get_httpcode() {
//get the http status code
$agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
$ch=curl_init();
curl_setopt ($ch, CURLOPT_URL,$this->url);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_VERBOSE,false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
$page=curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode;
}
public function get_status() {
$httpcode = $this->get_httpcode();
if ($httpcode>=200 && $httpcode<400) {
$siteUp = true;
} else {
$siteUp = false;
}
return $siteUp;
}
}
// create an instance of the website class and pass the url
$website = new website("http://www.google.com");
$url = $website->get_url();
$httpcode = $website->get_httpcode();
$siteUp = $website->get_status();
echo "site up is set to: " . $siteUp;
【问题讨论】:
-
您是否尝试过先回显
$httpcode? -
为什么不只是
return $httpcode>=200 && $httpcode<400;? -
除了http代码之外,检查
curl_exec的值也是明智的(在你的情况下,变量$page)。$page的值在失败时为 false,