CakePHP3:如何检查文件或图像是否存在

CakePHP3:如何检查文件或图像是否存在,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,我只是想检查一个图像是否存在,我可以用PHP来做。例如: $file = WWW_ROOT .'uploads' . DS . 'employee' . DS .'_'.check.jpg; $file_exists = file_exists($file); 这对我来说很好。但我也尝试过这样使用elementExists:- if($this->elementExists("../".$employees->front_image)) { echo $this->H

我只是想检查一个图像是否存在,我可以用PHP来做。例如:

$file = WWW_ROOT .'uploads' . DS . 'employee' . DS .'_'.check.jpg;

$file_exists = file_exists($file);
这对我来说很好。但我也尝试过这样使用
elementExists
:-

if($this->elementExists("../".$employees->front_image))
{
   echo $this->Html->image("../".$employees->front_image); // image output fine without condition.
}

// Here $employees->front_image = uploads/employee/employeename.jpg
if (file_exists(WWW_ROOT . $employees->front_image)):
   echo $this->Html->image('../' . $employees->front_image);
endif;

这张支票不起作用。我如何在CakePHP中实现这一点

我认为这在Cake 3中有效(您应该在
afterFind
方法IMO中执行此操作):


您的方法是检查视图元素是否存在。

CakePHP是用PHP编写的,所以如果您已经有了像
file\u exists()
这样的简单解决方案,请使用它。所以你可以这样写:-

if($this->elementExists("../".$employees->front_image))
{
   echo $this->Html->image("../".$employees->front_image); // image output fine without condition.
}

// Here $employees->front_image = uploads/employee/employeename.jpg
if (file_exists(WWW_ROOT . $employees->front_image)):
   echo $this->Html->image('../' . $employees->front_image);
endif;

用于检查视图元素是否存在,而不是webroot中是否存在文件,因此不应像您尝试的那样使用。它确实执行了一个
file\u exists()
检查,但这只扫描所有可用的视图元素路径。

我可以通过file\u exists()来解决它。我的问题是,cakephp中有什么方法可以做同样的事情吗?我不知道。您试图做的是一个非常简单的检查,CakePHP提供的任何替代方法都可能是多余的,因为您只需调用一个包装函数,该函数最终将调用
file\u exists()
。如果您查看
elementExists()
的代码,您将看到Cake使用
file\u exists()
本身来检查文件是否存在。如果图像文件存在,您可能确切地知道它将存在于哪个目录中,因此最好的解决方案(也是对性能最好的)是直接调用
file\u exists()