Wednesday, February 2, 2022

[FIXED] CakePHP 3: How to check if file or image exists

Issue

I am just trying to check if an image exists or not, I can do it by using PHP. For example:-

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

$file_exists = file_exists($file);

It's working fine for me. But I have tried also tried using elementExists like this:-

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

This check is not working. How can I do this in CakePHP?


Solution

CakePHP is written in PHP, so if you already have a simple solution like file_exists() use that. So you can write something like this:-

if (file_exists(WWW_ROOT . $employees->front_image)):
   echo $this->Html->image('../' . $employees->front_image);
endif;

elementExists() is intended for checking that a View element exists, not if files exist in the webroot, so should not be used like you are trying. It does do a file_exists() check, but this scans all available View element paths only.



Answered By - drmonkeyninja

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.