dtlhy0771 2016-04-09 10:05
浏览 66
已采纳

PHP下载仅适用于包含文本的文件

I want to be able to download files from my server with php. It works so far so good, but only for files with text in it (.txt .php, so files with simple text (even if there I have an interesting phenomenon, always having one empty line before text starts... ideas why?), but when I try to download an .jpg file or an .exe it's not working at all (error when trying to open...)

Here is the code I used:

<?php

session_start();

$file = basename($_GET['file']);

$path = 'uploads/'.$_SESSION['userid']."/".$file;
?>

<?php
if(!file_exists($path)){
    die("file not found");
} else {
    header('Content-Description: File Transfer');
    header('Content-Disposition: attachment; filename="'.$file.'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($path);
    exit;
}
  • 写回答

2条回答 默认 最新

  • douzhang8144 2016-04-09 10:35
    关注

    The reason the files have an empty line in is just because there is an empty line in your code

    ...
    $path = 'uploads/'.$_SESSION['userid']."/".$file;
    ?>
                           <--- There's the empty line.
    <?php
    if(!file_exists($path)){
        die("file not found");
    ...
    

    The solution is to join both your PHP blocks together in to one rather than having two separate blocks.

    This also breaks non-text files because they will actually interpret blank lines as data and try and process it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题