确定PHP中是否存在URL的最快方法是什么?

Jus*_*tin 4 php url

我需要创建一个函数,如果URL可访问或有效,则返回该函数.

我目前正在使用以下内容来确定有效的网址:

static public function urlExists($url)
{
    $fp = @fopen($url, 'r');

    if($fp)
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

看起来会有更快的东西,也许只是抓取页面标题或其他东西.

roj*_*oca 11

您可以使用curl,如下所示:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true); // set to HEAD request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // don't output the response
curl_exec($ch);
$valid = curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200;
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)

  • 还要检查2xx和3xx,因为它可能是301 Moved Permanently或另一个http代码,这意味着url工作. (2认同)

Ale*_*x L 8

您可以查看http状态代码.

这是一个代码,您可以用来检查网址是否返回2xx或3xx http代码,以确保网址有效.

<?php

$url = "http://stackoverflow.com/questions/1122845";

function urlOK($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;
}

echo $url;
if (urlOK($url)) echo " is a working URL";
    else echo " is a bad URL";
?>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!


Ale*_*zzi 5

您可能仅限于发送某种HTTP请求.然后,您可以检查HTTP状态代码.

请务必仅发送"HEAD"请求,该请求不会撤回所有内容.这应该足够轻便了.