[英]file_exists() in PHP and file path
I have a folder uploads
in the root folder. 我在根文件夹中
uploads
了一个文件夹。 There is another folder A
in the root, and contains a PHP file. 根目录中还有另一个文件夹
A
,它包含一个PHP文件。 I have the following code in the PHP file: 我在PHP文件中有以下代码:
$imgpath = '/uploads/' . $filename;
echo '<img src="' . $imgpath . '" />';
echo (file_exists($imgpath))?'true':'false';
It will show the image, so the file exists, but file_exists
shows false
. 它将显示图像,因此文件存在,但
file_exists
显示为false
。
If I change '/uploads/'
to '../uploads/'
, it will show the image and file_exists
shows true
. 如果我将
'/uploads/'
更改为'../uploads/'
,它将显示图像, file_exists
显示为true
。 Even if there is no image, file_exists
always shows true
. 即使没有图像,
file_exists
总是显示为true
。
What is the problem? 问题是什么?
* Update * *更新*
I tried echo dirname(__FILE__);
我试过
echo dirname(__FILE__);
. 。 It shows
/....../A
, the uploads
folder is located at /....../uploads
. 它显示
/....../A
,在uploads
文件夹位于/....../uploads
。 Moreover, I have another similar PHP file in folder /....../m/A
. 此外,我在文件夹
/....../m/A
有另一个类似的PHP文件。 So I need some kind of universal path. 所以我需要某种普遍的道路。 How to get the root path, ie,
/....../
? 如何获得根路径,即
/....../
?
I also tried $_SERVER['DOCUMENT_ROOT']
, but the image cannot be shown, although the path is 100% correct. 我也试过了
$_SERVER['DOCUMENT_ROOT']
,但是图片无法显示,尽管路径是100%正确的。
To avoid problems, it's easiest to use an absolute path with file_exists(). 为避免出现问题,最简单的方法是使用file_exists()的绝对路径。 The system root
/
is not the same as your web root (eg,) /var/www
系统root
/
与您的Web根目录(例如) /var/www
Try 尝试
# /var/www/A/script.php
$imgpath = '/uploads/' . $filename;
# check in /var/www/uploads/filename
if( file_exists(dirname(__FILE__) . '/..' . $imgpath) ) {
echo '<img src="' . $imgpath . '" />';
}
EDIT for PHP >= 5.3 编辑PHP> = 5.3
$path = "/uploads/${filename}";
if (file_exists(sprinf("%s/..%s", __DIR__, $path)) {
echo "<img src=\"{$path}\">;
}
Starting out with "/" means a relative path on the web, but on file systems that is referencing the folder "uploads" inside the root "/" directory. 以“/”开头表示Web上的相对路径,但是在根目录“/”目录中引用文件夹“uploads”的文件系统上。
Try ./uploads
notation or use dirname(__FILE__)
. 尝试
./uploads
表示法或使用dirname(__FILE__)
。
The reason is that your absolute path in HTML is relative to your website root, but in PHP it is relative to the file-system root. 原因是HTML中的绝对路径与您的网站根目录相关,但在PHP中它与文件系统根目录相关。 They are not the same.
她们不一样。
My website root is http://www.example.com/ but my site is developed on the file-system at /var/www/
So if I was in /var/www/index.php
and used the path /uploads/
, in html that would be http://www.example.com/uploads/ but for a file-system that would be /uploads/
. 我的网站根目录是http://www.example.com/但我的网站是在
/var/www/
文件系统上开发的,如果我在/var/www/index.php
并使用了路径/uploads/
,在http://www.tmlample.com/uploads/的 html中,但对于/uploads/
的文件系统。 I'm not even in my website directory anymore! 我甚至不在我的网站目录中了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.