Search code examples
phpfile-exists

adding generic image if empty or broken


i have a products portfolio each one has an image, if the DB field 'image' is empty i'm loading a generic image, but if in some case the field has an image value but the file doesn't exists i want to use the generic image too, i've tried using the code below but only works for empty fields:

<div class="wrapper"><a href="store.php?url=<?php echo $row->url ?>"><img src="images/stores/category/

<?php           
if (empty($row->image) or file_exists($row->image)==false) { 
    echo 'generic.jpg';
}else{                  
    echo $row->imagen; }?>" alt="<?php echo $row->seo ?>"/></a></div>        
    </div>
    <?php } ?>

Thanks for your time!


Solution

  • good code should be like this:

    Note 1: use is_file to check of the file actually exists and is available

    Note 2: use the relative path from your script to the file since the field contains only the file name

    Note 3: typo on the $row->imagen

    <div class="wrapper"><a href="store.php?url=<?php echo $row->url ?>"><img src="images/stores/category/
    
    <?php           
    if (empty($row->image) || !is_file('images/stores/category/' . $row->image)) { 
        echo 'generic.jpg';
    }else{                  
        echo $row->image; }?>" alt="<?php echo $row->seo ?>"/></a></div>        
        </div>
        <?php } ?>