PHP-下载不正常

PHP-Download doesn't work properly

我想使用 PHP 作为网络客户端从我的网络服务器下载一张照片。

因此,我编写了以下 PHP-脚本:

header('Content-Description: File Transfer');
header('Content-Type: image/jpg');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));

readfile("/var/www/_old/pictures/".$filename);

($filename 是文件名,如screenshot_03.06.2016-19:36:50.jpg)

问题是,这个下载图片的内容不是图片本身,而是当前网站的代码。下载没问题,就是无法正常打开图片...

好的。

一段时间后,我找到了可行的解决方案。

我的问题是,我在一些输出后写了 header-commands。根据 php 文档,这是被禁止的。

所以我所做的就是这个,我创建了一个新的 .php-file 并检查 session(我之前在其中存储了所需的信息 - 文件名和 download-command)是否设置正确。在上一页,我收到了 POST-information,将其存储到 session 并重定向(也使用 header-command)到新创建的 php-file.

然后我写了这些header-commands:

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($filename).'"');

    readfile($filename);

现在,所有浏览器(包括 IE!)都可以下载。


这是我所有的代码,我希望这可以帮助别人:

第 1 页(我收到 POST-infos):

session_start();

...
...

if(isset($_POST["galerie_submitBt"])){

    if($_POST["galerie_submitBt"] === "Herunterladen") {            //Das Herunterladen muss in einer eigenen Datei passieren, bevor jeglichen Outputs

        $_SESSION["download_Screenshot"] = true;
        $_SESSION["filename"] = "/var/www/_old/pictures/".$_POST["filename"];

        header("Location:modules/php/download_Screenshot.php");
    }
}

?>
<!DOCTYPE html>
<html>
    <head>
       <title>...

2、新建php-page(我实际下载图片的地方):

session_start();

if(isset($_SESSION["download_Screenshot"])){

  if(isset($_SESSION["filename"]) && file_exists($_SESSION["filename"])) {

    $filename = $_SESSION["filename"];          //Filename also includes the path! (absolute path)

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($filename).'"');

    readfile($filename);

    unset($_SESSION["filename"]);
    unset($_SESSION["download_Screenshot"]);
  }
}