Search code examples
phpfile-get-contentspathinfo

How to display a replacement image when one is not found in PHP?


I have a first PHP script that allows me to display an image on a remote server. This one works and I'd like to make a condition so that when it doesn't find the image in the $file variable it displays the image in the $newfile variable instead.

But I get the error "Warning: file_get_contents(): Filename cannot be empty in C:\wamp64\www..."

Where's my error?

<!-- Old Script -->
<?php

$file = '//Alcyons/it/PhotoShoot/Photos_Outil/A1111_0070_1.jpg';
$type = pathinfo($file, PATHINFO_EXTENSION);

?>
</td>
<td valign=top align=center>
  <img src="<?php echo "data:image/$type;base64,",
     base64_encode(file_get_contents($file)) ?>" border=0 width="180"></a>
</td>
<td width=10></td>


<!-- New Script -->
<?php
$file = '//Alcyons/it/PhotoShoot/retail/Photos/SS20,FW1920/A1127G_00_1.jpg';
$newfile = '//Alcyons/it/PhotoShoot/retail/Photos/SS20,FW1920/A1119_4023_1.jpg';
$type = pathinfo($file, PATHINFO_EXTENSION);

?>
</td>
<td valign=top align=center>
  <img src="<?php 

  if ($file = NULL)
{

    echo "data:image/$type;base64,", base64_encode(file_get_contents($newfile));
}
else 
{  
  echo "data:image/$type;base64,", base64_encode(file_get_contents($file));

}

?>" border=0 width="180"></a>
</td>
<td width=10></td>

Solution

  • Error is right here:

    if ($file = NULL)
    

    You are setting the $file variable to be "null" and you probably want a comparison:

    if ($file == NULL)
    

    Or check if the file exists on the file system

    if (!file_exists($file))