【问题标题】:adding generic image if empty or broken如果为空或损坏,则添加通用图像
【发布时间】:2013-05-16 22:53:33
【问题描述】:

我有一个产品组合,每个产品组合都有一个图像,如果数据库字段“图像”为空,我正在加载通用图像,但如果在某些情况下该字段具有图像值但文件不存在我也想使用通用图像,我尝试使用下面的代码,但仅适用于空字段:

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

感谢您的宝贵时间!

【问题讨论】:

  • 这是一个错字$row-&gt;imagen
  • 使用is_file 而不是file_exists。如果路径是目录,最后一个也将返回 true。

标签: php file-exists


【解决方案1】:

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

【讨论】:

  • 这很好用!以前的答案也很好,到底有什么区别,我错过了路径。
【解决方案2】:

好的代码应该是这样的:

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

【讨论】:

  • 错字是翻译错误,这是真实的字段名称,数据库是西班牙语。谢谢
【解决方案3】:

注意拼写错误 $row->imagen。 我看到 $row->image 只包含文件名。除非图片在您当前的工作目录中,否则您需要 file_exists 的完整路径:

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

要了解您需要的路径,请将包含内容的 php 文件放入图片文件夹中

die(__FILE__);

最好的问候

【讨论】:

  • 感谢您的回答!所有解决方案都有效,我错过了路径,非常感谢
【解决方案4】:

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

【讨论】:

  • @Ph.T 你能帮帮我吗?
猜你喜欢
  • 1970-01-01
  • 2016-05-24
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多