如何检查文件是否可读-产生无法解释的错误


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

我已经编写了以下代码段来检查图像文件是否可以打开:

    $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" />   
    <? } } ?>

这似乎不能产生正确的结果。

如果文件不存在,因此不能在指定的URL上打开,它返回一个杂项图像。

例如,当测试product_id = 12997时,浏览器会自动重定向到http://www.example.com/130/1997.jpg

所以理论上代码是工作的,然而,我如何防止浏览器选择最接近的匹配product_id时,所讨论的ID不存在。

当尝试使用fopen()访问http://example.com/130/12997.jpg时,浏览器应该产生404/403错误,而不是任意重定向到类似的现有product_id,即1997。

任何建议都会很好。

我找到了图像文件夹的完整服务器文件路径,现在is_readable正在评估为true。但是,当我在image src标签中使用相同的路径时,会显示破碎的图像。

知道为什么会这样吗?

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 } ?>

PHP函数is_readable($filename)(其中$filename是要检查的文件的名称)如果文件可读将返回TRUE,否则返回false。

例如:

<?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 } ?>

请注意,$filename变量必须是服务器上的路径,而不是公共http路径,因此您将编辑$filePath变量,使其指向服务器上的位置,而不是公共URL。