如何使单个PHP语句的警告静音


How to silence the warning of a single PHP statement?

我正在尝试检查某个域是否处于活动状态。我的想法是用file_get_contents()读取内容,并检查它是成功还是失败。

$line = file_get_contents('http://www.domain.com'); 
if ($line==false)
    echo 'Domain is dead';
else
    echo 'Domain is live';

我遇到的问题是,当它失败时,它会在网页上输出警告。通过PHP配置关闭所有警告不是一个选项,因为我在其他部分需要它们。有没有办法让这句话不输出警告?

或者有没有更好的方法来检查域是否处于活动状态?我试过checkdnsrr(),但速度很慢。

使用@符号抑制警告:

$line = @file_get_contents('http://www.domain.com');

你可以使用fopen来代替,并检查它是否为空:

 $fp = fopen('http://www.domain.com', 'r');
 if($fp) { 
    echo 'Domain is live'; 
 }

您可以使用抑制运算符@

从开发者的角度来看,使用抑制算子通常是个坏主意。您应该只在最坏的情况下使用它。

只要可能,尽量找到一个不会产生失控错误的替代方案。

您还应该查看:

  • @运算符使用不当

您可以使用@符号来消除PHP错误。

PHP:错误控制运算符

注意PHP手册中关于使用@:时性能的注释

请注意,使用@是非常缓慢的,因为PHP会增加以这种方式抑制误差。这是速度和方便

试试这个:

$line = @file_get_contents('http://www.domain.com'); 

使用错误抑制器:http://php.net/manual/en/language.operators.errorcontrol.php

尽可能避免使用错误抑制运算符(@)。如果您尝试以下代码,那么在您的案例中仍然存在问题。

if ( fopen('http://www.google.com/', 'r')) {
     $line = file_get_contents( 'http://www.google.com/' ); 
     if ( $line==false )
          echo 'Domain is dead';
      else
          echo 'Domain is live';
}
else {
    echo 'Domain not exists';
}

如果此域不存在,则它将再次通过警告。警告:fopen():php_network_getaddresses:gethostbyname失败。对于您的案例,您可以使用@。我还认为这并不是检查域名是否有效的最佳方法。我找到了一个剧本,请试一下。

https://github.com/HelgeSverre/Domain-Availability

您不应该完全下载该页面(出于速度目的)。只需使用HEAD方法进行检查:

$url = 'http://example.com/';
$code = FALSE;
$options['http'] = array(
    'method' => "HEAD", 
    'follow_location' => 0
);
$context = stream_context_create($options);
file_get_contents($url, NULL, $context);
if (!empty($http_response_header))
    echo 'Domain is live';
else echo 'Domain is dead';

参见https://hakre.wordpress.com/2011/09/17/head-first-with-php-streams/