doukun8670 2014-08-11 15:42
浏览 37
已采纳

如何检查文件是否可读 - 产生莫名其妙的错误?

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?

  • 写回答

2条回答 默认 最新

  • dongzhe3171 2014-08-11 15:50
    关注

    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 } ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊