user4423224
user4423224

Reputation:

file_exists() not working codeigniter

I am working with codeigniter. I want to display images but if some image is not exist it should show image-not-found-medium.jpg which is dummy image..

below is my code

<?php
    $image_path_medium = site_url('assets/images-products/medium');
    $image_not_found_medium =  $image_path_medium . "/" . "image-not-found-medium.jpg";
    $image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";

    if (file_exists($image_name_with_path)) {
        echo $image_name_with_path;
    } else {
        echo $image_not_found_medium;
    }
    ?>

but it always shows $image_not_found_medium i think there is problem with my if condition. Please help.

Upvotes: 1

Views: 7750

Answers (4)

Yogendra Tomar
Yogendra Tomar

Reputation: 121

Use like this.

$g = base_url().'upload/image.jpg';
if(file_exists($g) !== null){//your code..}

This is works for me in CI.

Upvotes: 0

Kavita
Kavita

Reputation: 79

Instead of file_exists() prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.

Upvotes: 0

Robin Garg
Robin Garg

Reputation: 213

You are using absolute path for file existence which is wrong. You have to use real path because the file_exists() function checks whether or not a file or directory exists on the current server.

If your assets folder is placed in root then just use getcwd() - Gets the current working directory as

$image_path_medium = getcwd().'assets/images-products/medium';

Otherwise give the proper path to the assets folder like

$image_path_medium = getcwd().'application/views/assets/images-products/medium';

Upvotes: 0

user3625145
user3625145

Reputation:

<?php
    $image_path_medium = site_url('assets/images-products/medium');
    $image_not_found_medium =  $image_path_medium . "/" . "image-not-found-medium.jpg";
    $image_name_with_path = $image_path_medium . "/" . $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your image url
    $image_file_path=FCPATH.'assets/images-products/medium'. $home_technology[$key]->product_sku . "-" . "a" . "-medium.jpg";//this is your file path

   if (file_exists($image_file_path)) //file_exists of a url returns false.It should be real file path
   {
       echo $image_name_with_path;
   } 
   else 
   {
      echo $image_not_found_medium;
   }
?>

Upvotes: 4

Related Questions