dtlhy0771 2016-04-09 02: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 02: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部