Search code examples
phpfile-exists

Using file_exists to check if image exist before echo


I'm trying to let my script check if an image exist before echoing it into my table. If it doesn't exist, it should echo another image in stead. My problem is that even though the image exist, it still goes to the else factor. Can anyone spot any coding mistakes?

<?php
mysql_select_db("xxxx");
$result = mysql_query("SELECT * FROM yyyy WHERE frivillig=1 ORDER BY stilling");
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td width="50px" class="frivillig"><?php  if (file_exists($url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg")) {
echo "<img" . " " . "src='" . $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg'" . " " . "height='50px'/>";
}
else {
echo "<img" . " " . "src='" . $url . "images/mangler.png'" . " " . "height='50px'/>";
}
?>

As you can see, I use $url for my complete url, and the images are placed in the /ansatte/ folder.

Thanks for any help!


Solution

  • Consider the below snippet for checking remote resources:

    $path = $url . "ansatte" . "/" . (utf8_encode($row['etternavn'])) . "%20" . (utf8_encode($row['fornavn'])) . ".jpg"
    
    $ch = curl_init($path);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode < 400) { // Filter out bad request, not found, etc
     // found
    } else {
     // not accessible
    }
    

    If you don't have php5-curl installed, you could also look at the following alternatives:

    getimagesize

    Again only certain streams are supported here, but usage is simple and it will validate the return better:

    if (getimagesize($path) !== FALSE) {
      //exists
    }
    

    fopen

    if (fopen($path,"r") !== FALSE) {
      // exists
    }
    

    get_headers

    $headers = get_headers($path, TRUE);
    if ($headers !== false && isset($headers['Content-Type']) && $headers['Content-Type'] == 'image/jpeg') {
      // exists
    }