简体   繁体   English

检查图像是否存在,如果不存在,请使用php选择另一个图像

[英]Check if image exists and if not select another one with php

I want to display an image with php . 我想用php显示图像。

How can I check if it exists and if not, link to another one? 如何检查它是否存在,如果不存在,则链接到另一个?

This is what i've got: 这就是我所拥有的:

<img class="MyClass" src="Images/<?php echo $image1?>.png">

So if image1 doesn't exist it should link to image2 因此,如果image1不存在,则应链接到image2

there are some way but this is the way that I use: 有一些方法,但这是我使用的方法:

php documentation PHP文档

<?php
  $filename="images/".$image_name;
  if(is_readable($filename)){
     $fileToShow=$filename;
  }else{
    $fileToShow="images/default.jpg";
  }
    echo '<img class="MyClass" src="<?php  echo $fileToShow; ?>"/>';
?>

First i need to know are you saving image files without extention. 首先,我需要知道您是否在不扩展图像的情况下保存图像文件。 If so see the code below 如果是这样,请参见下面的代码

$filename = 'Images/'.$image1.'.png';

 if (file_exists($filename)) {
echo '<img class="MyClass" src="Images/<?php echo $image1;?>.png">';
} 
else {
 echo '<img class="MyClass" src="Images/<?php echo $image2;?>.png">';;
 }

Try this 尝试这个

<?php
  $file_name="images/".$image_name;
  if(file_exists($file_name))
  {
     $path=$file_name;
  }
  else
  {
    $path="images/default.jpg";
  }
    echo '<img class="MyClass" src="<?php  echo $path; ?>"/>';
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM