I'm trying to display a default image in cakePHP when the entry for the file path to the image stored in the DB is empty. What I'm finding is happening with the code below, is that if the DB entry is empty the default image is displayed, but it's also displayed if there is an entry in the DB.
So, for some reason if there is an entry in the DB $image is not being displayed. Appreciate the help.
Paul
<?php
$image = $this->Html->image(
$news['News']['imgPath'],
array('title' => $news['News']['alt_tag'], 'class' => 'left'),
array('escape' => false));
$default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";
if(file_exists("$image")) $filename = $image;
else $filename = $default_image;
echo $filename;
?>
Resolution: Since $image is an html string, I added a variable to first check if the file path was empty, and then set the $filename by it.
$photo = $news['News']['imgPath'];
$image = $this->Html->image(
$news['News']['imgPath'],
array('title' => $news['News']['alt_tag'], 'class' => 'left'),
array('escape' => false));
$default_image = "<img src=\"/FBCW_new2/files/uploads/default.jpg\" class=\"left\" alt=\"default image\"/>";
if(!empty($photo)) $filename = $image;
else $filename = $default_image;
echo $filename;
You're checking whether $image
is a valid file path, but $image
holds an HTML string; therefore, file_exists
will almost invariably return false
. You want to check if the file path is valid:
if(file_exists(APP . WEBROOT_DIR . '/' . $news['News']['imgPath'])){
// ...
}
Note: Depending on where you're storing these images (and how your storing their file paths), you'll likely need to use the APP
constant (and others) to check the correct absolute file path.
You might want to create a helper that does image-replacement like this for you, see Helpers - CakePHP Cookbook 2.0.