如何在php中检查url是否存在

4

我想在php中检查url http://example.com/file.txt 是否存在。我该怎么做?


可能是 https://dev59.com/W3E95IYBdhLWcg3whOLK 的重复问题。 - swapnesh
5个回答

4
if(! @ file_get_contents('http://www.domain.com/file.txt')){
  echo 'path doesn't exist';
}

这是最简单的方法。如果您不熟悉@,它将指示该函数在原本会抛出错误的情况下返回false。


OT: 是否有普遍共识,认为 @!!@ 更好?我使用前者,对后者感到有些奇怪——也许是因为在操作符之后加上 @ 感觉不应该有效,尽管显然应该。 - Tortoise
修复语法错误,并检查正确的返回类型。如果(@file_get_contents('http://localhost/mh/t.php')===false){ echo '路径不存在'; } - Mohammed H
请务必在php.ini中启用file_get_contents以访问其他域。 - ioan
@habeebperwad 如果你使用 @ 并且它失败了,它将返回 0 而不是 false - 你可以用 if 来测试它是否为 falsey 或者 ===0 但不是 ===false - doublesharp
PHP支持一个错误控制运算符:at符号(@)。当在PHP中将其放置在表达式之前时,该表达式可能生成的任何错误消息都将被忽略。@不会返回任何值,对吗?如果URL返回没有内容的文件,则上述代码将失败。 - Mohammed H

3

使用PHP的curl扩展:

$ch = curl_init();                                  // set up curl
curl_setopt( $ch, CURLOPT_URL, $url );              // the url to request
if ( false===( $response = curl_exec( $ch ) ) ){    // fetch remote contents
    $error = curl_error( $ch );                  
    // doesn't exist
}
curl_close( $ch );                                  // close the resource

是的。如果file_exists无法工作,则这是最经典正确的解决方案,尽管Landon的解决方案也可以。 - Tortoise

0

我同意这个回复,我通过这样做取得了成功。

$url = "http://example.com/file.txt";       
if(! @(file_get_contents($url))){
    return false;
}
$content = file_get_contents($url);
return $content;

你可以跟随代码检查文件是否存在于指定位置。

0

PHP中尝试Ping网站并返回结果的函数。

function urlExists($url=NULL)  
    {  
        if($url == NULL) return false;  
        $ch = curl_init($url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        $data = curl_exec($ch);  
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        curl_close($ch);  
        if($httpcode>=200 && $httpcode<300){  
            return true;  
        } else {  
            return false;  
        }  
    }

0
$filename="http://example.com/file.txt";    

if (file_exists($filename)) {
   echo "The file $filename exists";
} else {
   echo "The file $filename does not exist";
} 

或者

if (fopen($filename, "r"))
{
   echo "File Exists"; 
}
else
{
   echo "Can't Connect to File";
}

@habeebperwad 请尝试我回答中的第二个选项。 - Soojoo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接