Rocco The Taco
Rocco The Taco

Reputation: 3797

PHP file_get_contents does not really determine if file is present

I'm trying to use file_get_contents to test if a .jpg exists in a directory and if so display it else just stop the loop.

This appears to work great EXCEPT when the .jpg is not in the directory it continues to look and display missing thumbnails up to 10 images.

Is there something else besides file_get_contents? I've tried to use absolute path as well with the same results.

<?
$image = "<br>";
$ListingRid = $row['MLS_NUMBER'];
$img_cnt = 1;
for ($c=1;$c<11;$c++) {
    if ($c<10)
        $c_ext = "".$c;
    else
        $c_ext = $c;

    if (file_get_contents("http://mydomain.com/images/{$ListingRid}_{$c_ext}.jpg"))
        $image .= "<img src=http://mydomain.com/images/{$ListingRid}_{$c_ext}.jpg alt='' width='100' height='75' border='0' />";
    else
        $c=12;

    $img_cnt++;
    if ($img_cnt == 3) {
        $image .= "<br>";
        $img_cnt = 0;
    }

}

?>

Upvotes: 0

Views: 167

Answers (3)

user399666
user399666

Reputation: 19909

You can check to see if a file exists over HTTP by using cURL. Also, by using the CURLOPT_NOBODY option, you can check for a file's existence without actually having to download the content:

$ch = curl_init("http://mydomain.com/images/{$ListingRid}_{$c_ext}.jpg");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

var_dump($retcode);

In your case:

<?php

$image = "<br>";
$ListingRid = $row['MLS_NUMBER'];
$img_cnt = 1;
for ($c=1;$c<11;$c++) {
    if ($c<10)
        $c_ext = "".$c;
    else
        $c_ext = $c;


    $ch = curl_init("http://mydomain.com/images/{$ListingRid}_{$c_ext}.jpg");

    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($retcode == '200')
        $image .= "<img src=http://mydomain.com/images/{$ListingRid}_{$c_ext}.jpg alt='' width='100' height='75' border='0' />";
    else
        $c=12;

    $img_cnt++;
    if ($img_cnt == 3) {
        $image .= "<br>";
        $img_cnt = 0;
    }

}

Upvotes: 4

dotty
dotty

Reputation: 41503

PHP has a handy function called file_exists which returns a bool.

Upvotes: 0

Ryan Leonard
Ryan Leonard

Reputation: 997

PHP has file_exists.

bool file_exists ( string $filename )
Checks whether a file or directory exists.

http://php.net/manual/en/function.file-exists.php

Upvotes: 4

Related Questions