aphextwix
aphextwix

Reputation: 1858

How to check whether file is readable - producing inexplicable error?

I've written the following segment of code to check whether an image file can be opened:

    $sql="SELECT * FROM product 
          WHERE brand_id = '".$id."'
          ORDER BY active DESC, 
          product_id DESC";

    $result=mysql_query($sql);

    while($rows=mysql_fetch_array($result)){ 



    $filePath = 'http://www.example.com/130/'.$rows['product_id'].'.jpg';

    $handle = fopen($filePath,"r");
    if($handle){ ?>
    <img src="http://www.example.com/130/<?=$rows['product_id']?>.jpg"
    alt="" width="130" height="130" border="0" onerror="this.src='http://www.example.com/220/no_image.jpg'"/>
    <? } else { ?>
    <img src="http://www.example.com/220/no_image.jpg" alt="" width="130" height="130" border="0" />   
    <? } } ?>

This doesn't seem to be producing the correct result.

If when the file doesn't exist and therefore cannot be opened at the URL specified, it returns a miscellaneous image.

For example when testing this with product_id = 12997, the browser automatically redirects to http://www.example.com/130/1997.jpg.

So in theory the code is working, however, how do I prevent the browser from choosing the closest match product_id when the ID in question does not exist.

When trying to access the file at http://example.com/130/12997.jpg using fopen() the browser should produce a 404/403 error rather than arbitrarily redirecting to a similar exisiting product_id i.e. 1997.

Any advice would be great.

UPDATE

I found the full server file path for the images folder, and now is_readable is evaluating to true. However, when I use the same path within the image src tag a broken image is shown.

Any idea why this may be happening?

Upvotes: 0

Views: 121

Answers (2)

mjsa
mjsa

Reputation: 4399

The PHP function is_readable($filename) (where $filename is the of the file to check) will return TRUE if the file is readable, false if not.

For example:

<?php if (is_readable($filePath) == TRUE) { ?>
   <img src="<?php echo $filePath; ?>" alt="" width="130" height="130" border="0" />
<?php } else { ?>
   <img src="http://www.example.com/220/no_image.jpg" alt="" width="130" height="130" border="0" />
<?php } ?>

Note that the $filename variable must be the path on the server, not the public http path, so you will to edit your $filePath variable so it points to the location on the server instead of the public URL.

Upvotes: 0

Tibor B.
Tibor B.

Reputation: 1690

is_readable should work for you. It check if the file exists and is readable:

<?php if (is_readable($filePath)) { ?>
   <img src="<?php echo $filePath; ?>" alt="" width="130" height="130" border="0" />
<?php } else { ?>
   <img src="http://www.example.com/220/no_image.jpg" alt="" width="130" height="130" border="0" />
<?php } ?>

Upvotes: 3

Related Questions