Read/download PHP 中 FTP 上的 .doc 文件

Read/download a .doc file on a FTP in PHP

我正在尝试能够在无框架 PHP 服务器上从 FTP 读取/下载文件(是)。我实施的方法适用于 PDF 文件:它打开一个选项卡并毫无问题地显示它们。但是 .doc.docxeven .odt 文件有问题。使用 Libre Office,我得到一个包含不可读内容的文件,例如:��R#���X�A9#]��ja��b(�>e��-�8a�1�1,!~k��#��׫�Lލ��j��dl����。但是,我确定 FTP 服务器上存储的文件是有效的。 (如果我用 FTP 客户端下载它,我会得到一个可读文件)。

这是我获取文件的方式:

    header("Content-type: $mimeType");
    header('Content-Disposition: inline; filename="' . basename($filename) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');
    
    if (!ftp_get($connexion, "php://output", $filename, FTP_BINARY)) {
        echo "Couldn't read $filename";
    }
    ftp_close($connexion);

一些信息:

存储在本地的文件有效,使用

    ob_end_clean();
    readfile($file);

。当我使用 ftp_get() 时,问题确实发生了。 $mimeType 根据文件扩展名动态设置。我尝试使用 FTP_ASCII 模式,我尝试使用其他所有 php:// flux,我尝试设置 Content-Transfer-Encoding: 8bit 而不是 binary... 还是一样。

感谢04FS, it works. The funny thing is that my initial way eventually works after trying 04FS的解决方案,只需在~~之前清除输出缓冲区。

04FS的建议解决方案:

    $filename = "ftp://".FTP_USER.":".FTP_PASS."@".FTP_HOST."/$filename";
    ob_clean();
    $content = file_get_contents($filename);
    $handle = fopen('php://memory', 'w');
    fwrite($handle, $content);
    rewind($handle);
    header("Content-type: $mimeType");
    header('Content-Disposition: attachment;filename="' . $filename . '";');
    fpassthru($handle);
    fclose($handle);

然后我用 ob_clean() 尝试了我的初始解决方案并且......它有效。

    ob_clean();
    header("Content-type: $mimeType");
    header('Content-Disposition: inline; filename="' . basename($filename) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Accept-Ranges: bytes');

    if (!ftp_get($connexion, "php://output", $filename, FTP_BINARY)) {
        echo "Couldn't read $filename";
    }
    ftp_close($connexion);

.pdf 个文件不需要它,但 .doc.docx 等文件需要它...