phpcakephpcakephp-2.0cakephp-2.6

Cakephp: Show image if uploaded or show text if image was not uploaded


I am developing a system where the user may upload up to four photos. If the user does not upload a photo I would like that the follow text will be displayed: 'empty'.

I have prepared the below code however I didn't managed :/ The problem is that when an image is uploaded it still prints 'empty' and the uploaded image does not show up.

<?php if (file_exists('../files/collection/photo2/' .$collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2'])) 
{
  echo $this->Html->image('../files/collection/photo2/' . $collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2']);}
else
{
  echo ('empty');
}
?>

I appreciate you guidance and help :)


Solution

  • TLDR: The file you're checking for doesn't exist. Fix your path.

    Detail: You're trying to use the same path for both your HTML <img> as well as the PHP file_exists() check.

    The problem is, that the HTML image is looking for a file via the user's browser, where the file_exists() method is looking for the file via your server. The two paths are very rarely the same.

    Try using a correct path in your PHP's file_exists() method, and it should pass the check.

    For example:

    if(file_exists(APP . 'files' . DS . 'collection' . DS . 'photos2' . $collection['Collection']['photo_dir2'] . DS . 'thumb_' . $collection['Collection']['photo2'])) {
        echo $this->Html->image('../files/collection/photo2/' . $collection['Collection']['photo_dir2'] . '/thumb_' . $collection['Collection']['photo2']);
    }
    else {
        echo ('empty');
    }