PHP Force文件下载

Cra*_*ash 2 php download

我试图使用PHP强制下载客户端计算机(文件对话框 - 没有任何险恶).我发现很多页面建议我使用header()函数来控制PHP脚本的响应,但我没有运气.我的代码如下:

$file = $_POST['fname'];

if(!($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file)) {
    die('File not found.');
} else {
    header('Pragma: public');
    header('Content-disposition: attachment; filename="tasks.zip"');
    header('Content-type: application/force-download');
    header('Content-Length: ' . filesize($file));
    header('Content-Description: File Transfer');
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    ob_end_clean();
    readfile($baseDir . '\\AgcommandPortal\\agcommand\\php\\utils\\ISOxml\\' . $file);
}
Run Code Online (Sandbox Code Playgroud)

我用这个JavaScript调用它:

        $.ajax({
            url: url,
            success: function(text) {
                var req = new XMLHttpRequest();
                req.open("POST", 'php/utils/getXMLfile.php', true);
                req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                req.send('fname=' + encodeURIComponent(text));
            }
        });
Run Code Online (Sandbox Code Playgroud)

这将文件的内容作为文本返回,但不会触发下载对话框.有没有人有什么建议?

Nie*_*sol 6

不要使用AJAX,只需将浏览器重定向到相关的URL即可.当它收到content-disposition:attachment标题时,它将下载该文件.

  • ...并通过用`$ file = basename($ _ POST ['fname'])替换`$ file = $ _POST ['fname'];`来修复安全漏洞; (3认同)