Show default image if uploaded image not found using php


After uploading the image to website mysql entry "image name" is added to database, but at the same time it is important to check whether the image file is located in image directory or not to avoid the broken image path.

Image directory path example - www.yourdomain.com/uploads/profile/

Complete image path example - www.yourdomain.com/uploads/profile/IMG_pro1155.png

  • How to check if the image file exist using file_exists() function?


<?php

$filepath = 'www.yourdomain.com/uploads/profile/IMG_pro1155.png';
 
if(file_exists($filepath)){
 echo $filepath." File Exist";
}else{
 echo $filepath." File Does Not Exist";
}

?>

file_exists() is the php function which returns TRUE if the file path is valid else it will return FALSE.

  • How to set default picture image if uploaded image file failed to load?

Once the default user image is presented in website images directory there should not be any situation facing broken images. Below script can simply replace the image with default picture.


<?php

if(file_exists('www.yourdomain.com/uploads/profile/'.$userImage.'')) {
    $image = 'www.yourdomain.com/uploads/profile/'.$userImage;
} else {
    $image = 'www.yourdomain.com/img/defaultuser.jpg';
}

echo '';

?>
  • How to check if document file exists(.xls, .csv, .docx, .txt, .pdf)?

Not only the image file but other file format can also be checked whether they exist or not.


<?php

$document = '/.xls';

//you can use other format as same as .xls
 
if(file_exists($document)){
 echo $document." File Exist";
}else{
 echo $document." File Does Not Exist";
}


?>