简体   繁体   English

无法使file_exists函数在PHP中工作

[英]Can't make the file_exists function work in PHP

I'm facing a problem. 我遇到了一个问题。

I have actually this code: 我实际上有以下代码:

// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(file_exists($src)) {
    $src = $src;
}
else {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';

This code check for an image existence. 此代码检查图像是否存在。

But each time I have the fallback image default.jpg whereas I should have 007.jpg . 但是每次我都有后备图像default.jpg而我应该有007.jpg

I check my path and it works. 我检查我的路径,它有效。 My 007.jpg image is into the same directory as my default.jpg image. 我的007.jpg图像与default.jpg图像位于同一目录中。

I already test with if(@getimagesize($src)) { ... } . 我已经使用if(@getimagesize($src)) { ... } The same. 相同。

Why ? 为什么呢

Even that your file is placed at some directory, doesn't mean that the current path of the PHP process is the same. 即使您的文件放在某个目录中,也并不意味着PHP进程的当前路径是相同的。 Use the absolute path instead: 改用绝对路径:

// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(!file_exists(__DIR__.'/'.$src)) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';

I think you are over doing it make it simpler might solve your issue Try This: 我认为您已经完成了此操作,使其变得更简单,可能会解决您的问题。

<?php
$src = '../assets/app/images/hotel-logos/007.jpg';

if (!file_exists($src)) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}
echo '<center><img src="'.$src.'" width="200"></center>';

?>

Ok, I get it working by using: 好的,我通过使用以下命令使其正常工作:

$_SERVER['DOCUMENT_ROOT']


// Check if image exist for the hotel
$src = '../assets/app/images/hotel-logos/007.jpg';

if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/assets/app/images/hotel-logos/007.jpg')) {
    $src = '../assets/app/images/hotel-logos/default.jpg';
}

echo '<center><img src="'.$src.'" width="200"></center>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM