添加通用图像,如果空或破碎


adding generic image if empty or broken

我有一个产品组合,每个都有一个图像,如果DB字段'image'是空的,我正在加载一个通用图像,但如果在某些情况下该字段有一个图像值,但文件不存在,我想使用通用图像,我也尝试使用下面的代码,但只适用于空字段:

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

谢谢你的时间!

file_exists应该指向文件系统中的某个内容。

试试这样写:

if (file_exists('/Library/WebServer/Documents/theimage.jpg')) {
  echo 'File exists';
} else {
  echo 'Does not exist';
}

if (file_exists('./theimage.jpg')) {
  echo 'File exists';
} else {
  echo 'Does not exist';
}

如果我把它应用到你的代码中,它将是:

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

好的代码应该像这样:

注释1:使用is_file来检查文件是否实际存在并且可用

注意2:使用从脚本到文件的相对路径,因为字段只包含文件名

注3:$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 } ?>

注意$row->imagen的错别字。如我所见,$row->image只包含文件名。除非图片位于当前工作目录中,否则需要file_exists的完整路径:

file_exists('htdocs/path/to/my/images/' . $row->image)==false)

要了解所需的路径,请将php文件放入内容为

的pictures文件夹中
die(__FILE__);

我们有几乎相同的问题。但对我来说;如何不能显示从我的数据库使用克罗克图像/空图像<?php if(!empty($row[image])){ ?>"; <img class='img-size' src='admin/upload_images/".$row['image']."'> <?php } ?>这行不通。