不要仅检查域名

时间:2012-01-27 13:02:48

标签: php phpbb

Soooo再次使用此功能......

我的功能正常。

function http_file_exists($url)
{
  $f = @fopen($url,"r");
  if($f)
  {
    fclose($f);
  return true;
  }
return false;
} 

这就是用法:

if ($submit || $preview || $refresh)
{
 $post_data['your_url'] = "http://www.google.com/this"; //remove the equals and url value if using in real post
  $your_url = $post_data['your_url'];
  $your_url_exists = (isset($your_url)) ? true : false;
  $your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);

  if ($your_url_exists && http_file_exists($your_url) == true)
  {
    trigger_error('exists!');
  }

如何让它检查整个网址而不仅仅是域名?例如http://www.google.com/this

2 个答案:

答案 0 :(得分:0)

使用curl并检查HTTP状态代码。如果它不是200 - 很可能该网址不存在或无法访问。

还要注意

$your_url_exists = (isset($your_url)) ? true : false;

毫无意义。看来你想要

$your_url_exists = (bool)$your_url;

或只是检查$your_url而不是$your_url_exists

答案 1 :(得分:0)

测试的网址是http://www.google.com/abadurltotest

以下代码来源= What is the fastest way to determine if a URL exists in PHP?

function http_file_exists($url) 
{
  //$url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $url); 
$url_data = parse_url ($url);
    if (!$url_data) return FALSE;

   $errno="";
   $errstr="";
   $fp=0;

   $fp=fsockopen($url_data['host'],80,$errno,$errstr,30);

   if($fp===0) return FALSE;
   $path ='';
   if  (isset( $url_data['path'])) $path .=  $url_data['path'];
   if  (isset( $url_data['query'])) $path .=  '?' .$url_data['query'];

   $out="GET /$path HTTP/1.1\r\n";
   $out.="Host: {$url_data['host']}\r\n";
   $out.="Connection: Close\r\n\r\n";

   fwrite($fp,$out);
   $content=fgets($fp);
   $code=trim(substr($content,9,4)); //get http code
   fclose($fp);
   // if http code is 2xx or 3xx url should work
   return  ($code[0] == 2 || $code[0] == 3) ? TRUE : FALSE;
}

将顶级代码添加到functions_posting.php中,替换上一个函数

if ($submit || $preview || $refresh)
{
 $post_data['your_url'] = " http://www.google.com/abadurltotest"; 
  $your_url = $post_data['your_url'];
  $your_url_exists = (request_var($your_url, '')) ? true : false;
  $your_url = preg_replace(array('#&\#46;#','#&\#58;#','/\[(.*?)\]/'), array('.',':',''), $your_url);

  if ($your_url_exists === true && http_file_exists($your_url) === false)
  {
    trigger_error('A bad url was entered, Please push the browser back button and try again.');
  }