file_exists()没有工作的codeigniter

时间:2015-01-14 09:35:01

标签: php codeigniter

我正在使用codeigniter。我想显示图像,但如果某些图像不存在,则应显示image-not-found-medium.jpg,这是虚拟图像..

下面是我的代码

<?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;
    }
    ?>

但它始终显示$image_not_found_medium我认为if condition存在问题。 请帮忙。

4 个答案:

答案 0 :(得分:2)

<?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;
   }
?>

答案 1 :(得分:0)

您正在使用文件存在的绝对路径,这是错误的。您必须使用实际路径,因为file_exists()函数会检查当前服务器上是否存在文件或目录。

如果您的assets文件夹放在root中,那么只需使用getcwd() - 获取当前工作目录

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

否则给出资产文件夹的正确路径,如

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

答案 2 :(得分:0)

而不是file_exists()在检查文件时更喜欢is_file(),因为file_exists()在目录上返回true。此外,您可能希望查看getimagesize()是否返回FALSE以确保您有图像。

答案 3 :(得分:0)

像这样使用。

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

这对我来说适合CI。