PHP 的 file_exists() 对我不起作用?
-
18-09-2019 - |
题
由于某种原因,下面的 PHP 代码将无法工作,我无法弄清楚。
这很奇怪,file_exists似乎没有看到图像确实存在,我已经检查了以确保将一个好的文件路径插入到file_exists函数中,并且仍在行动
如果我将 file_exists 更改为 !file_exists 它将返回存在的图像和不存在的图像
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($thumb_name)) {
$img_name = $thumb_name;
}else{
$img_name = $noimg;
}
echo $img_name;
解决方案
file_exists()
需要使用的硬盘驱动器,而不是URL上的文件路径。所以,你应该有更多的东西一样:
$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($thumb_name)) {
some_code
}
其他提示
文档 说:
从 PHP 5.0.0 开始,该函数还可以与 一些 URL 包装器。参考 支持的协议/包装器列表 获取哪些包装器支持的列表
stat()
功能族。
file_exists
并仅在本地文件系统上工作。
所以,如果你使用这种尝试的本地主机的:
$thumb_name = 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($_SERVER['DOCUMENT_ROOT'].$thumb_name)) {
$img_name = SITE_PATH2.$thumb_name;
} else {
$img_name = $noimg;
}
你有没有启用,它允许您使用外部URL的选项?您可以设置它在php.ini:
allow_url_fopen = 1
http://php.net/manual/en/function.file -exists.php
你检查下面的意见?
只是阅读它的一部分,但似乎有几个问题。
缓存可能是一个问题。 当打开FTP网址,它总是返回true(他们在评论中说的) ...
您必须写像"file:///C:/Documents%20and%20Settings/xyz/Desktop/clip_image001.jpg"
的文件路径。
尝试下面之一。它为我工作
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if ($fileopen = @fopen($thumb_name)) {
$img_name = $thumb_name;
fclose($fileopen);
}else{
$img_name = $noimg;
}
echo $img_name;
不隶属于 StackOverflow