duanrong0738 2012-09-29 22:49
浏览 50
已采纳

通过PHP下载文件[关闭]

I'm trying to initiate a file download through PHP. It downloads, however, the file can't be opened. My path is correct because I did a test through previewing the image via the image tags in HTML.

    $findPage = mysql_query("SELECT * FROM pages WHERE page_id = '$pageId' LIMIT 1");
    $pg = mysql_fetch_array($findPage);

    $fullPath = $pg['page_link'];
    $explode = explode(".", $fullPath);

    $ext = $explode[count($explode)-1];

    header('Content-disposition: attachment; filename="Name.'.$ext.'"');
    header('Content-type: image/'.$ext);
    readfile($fullPath);
  • 写回答

1条回答 默认 最新

  • doumeng2637 2012-09-29 23:32
    关注

    What do you get if you try the following:

    $fullPath = 'https://www.google.co.uk/images/srpr/logo3w.png';
    
    list($w,$h,$t) = getimagesize($fullPath);  
    $mimetype = image_type_to_mime_type($t);
    $extension = end(explode('.', $fullPath));
    
    header('Content-disposition: attachment; filename="Name.'.$extension.'"');
    header('Content-type: '.$mimetype);
    readfile($fullPath);
    

    You should get Google's logo downloading... I do on my local set-up.

    *(this code will require fopen_wrappers enabled on your server)*

    If you do get Google's logo downloading correctly then I would suggest it's either a problem with the data being served from your db, or a permissions problem when readfile tries to access and read your file.

    file_exists( $fullPath ) /// will tell you if the file exists or not
    
    is_readable( $fullPath ) /// could be useful to detect a read error
    

    If you don't get Google's logo then either fopen_wrappers are disabled on your server or something odd is going on elsewhere in your code.

    extra notes

    Where is $pageId being set? If it is being passed into your script from the outside world - as in through a URL - I would insist that you use a different way of building your database query. At the very least you should be running some kind of escaping function on the $pageId value before you insert it to your query. Otherwise it's quite a security problem. This is because anyone who has access to your URL can obviously modify it, and by doing so they can directly modify your query. The quickest way you can protect your database when dealing with simple IDs is to make sure the value is a number.

    $pageId = (int) $pageId;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?