在PHP中检查URL是否存在

61
if (!(file_exists(http://example.com/images/thumbnail_1286954822.jpg))) {   
$filefound = '0';                         
}

为什么这个不起作用?


https://dev59.com/HXNA5IYBdhLWcg3wZ81R - ArK
7个回答

90
if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {   
$filefound = '0';
}

1
如果(!file_exists($base_url.'images/thumbnail_1286954822.jpg')){ $filefound ='0'; }实际上就像这样,抱歉。 - anonymous
3
抱歉,实际上不是这样的。你所请求的并不是$base_url + images/thumbnail_1286954822.jpg,而是http://mysite.com/images/thumbnail_1286954822.jpg。 - Robert Pounder

36
  1. 该函数要求传入一个字符串。

  2. file_exists() 无法正确处理HTTP URL。


你有什么解决方案吗? - Joyner

20

file_exists 函数检查指定路径下是否存在文件。

语法:

file_exists ( string $filename )

如果指定的文件或目录存在,则返回 TRUE;否则返回 FALSE

$filename = BASE_DIR."images/a/test.jpg";
if (file_exists($filename)){
    echo "File exist.";
}else{
    echo "File does not exist.";
}

你可以使用另一种替代方法getimagesize(),如果指定路径中的文件/目录不可用,它将返回0(零)。

if (@getimagesize($filename)) {...}

8
你也可以使用 PHPget_headers() 函数。
例子:
function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

对我来说,file_exists()没有起作用。我正在尝试定位一个PDF文件。但是你的解决方案有效。谢谢。你知道为什么file_exists()对我没用吗? - Nguai al
1
这取决于代码。https://dev59.com/f3M_5IYBdhLWcg3wp06l - 这可能会回答你的问题。 - Pradeep Kumar
一行代码if(stripos(get_headers($file)[0],'200 OK')) - iKev61

6

根据您对Haim的评论,这是您自己服务器上的文件吗?如果是的话,您需要使用文件系统路径,而不是url(例如file_exists('/path/to/images/thumbnail.jpg'))。


3

对我来说,file_exists()函数也无法正常工作。因此,我找到了这个替代解决方案。希望这个解决方案能帮助到其他人。

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

getimagesize()函数将确定任何支持的给定图像文件的大小,并返回尺寸以及文件类型和高度/宽度文本字符串,以在普通HTML IMG标记内使用,并对应HTTP内容类型。 - Nashir

2
请查看下面的代码。
if ($user->image) {
        $filename = "images/" . $user->image;
        if (file_exists($filename)) {
            echo '<br />';
            echo "File exist.";
        } else {
            echo '<br />';
            echo "File does not exist.";
        }
    }

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