PHP-简单的下载脚本 [英] PHP - simple download script

查看:83
本文介绍了PHP-简单的下载脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个简单的下载脚本,我的用户可以在其中下载自己的图像等.

I'm making a simple download script, where my users can download their own images etc.

但是我有一些奇怪的问题.

But I'm having some weird problem.

下载文件后,无论我下载了哪种文件类型,它都具有index.php文件中的内容.我的代码如下:

When I've downloaded the file, it's having the contents from my index.php file no matter what filetype I've downloaded.. My code is like so:

$fullPath = $r['snptFilepath'] . $r['snptFilename'];

if (file_exists($fullPath)) {

    #echo $fullPath;

    // setting headers
    header('Content-Description: File Transfer');
    header('Cache-Control: public'); # needed for IE
    header('Content-Type: '.$r['snptFiletype'].'');
    header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']);
    header('Content-Length: '.$r['snptSize'].'');
    readfile($fullPath)or die('error!');
} else {
    die('File does not exist');
}

$ r是我的数据库的结果,文件上传时我存储了大小,类型,路径等.

$r is the result from my database, where I've stored size, type, path etc. when the file is uploaded.

更新

当我上载和下载* .pdf文件时,它运行成功.但是,当我尝试下载* .zip和text/rtf时,text/plain表现得很奇怪.

When I'm uploading and downloading *.pdf files it's working with success. But when I'm trying to download *.zip and text/rtf, text/plain it's acting weird.

很奇怪,我的意思是:它会下载完整的index.php文件,其中包含下载的文件内容.

By weird I mean: It downloads the full index.php file, with the downloaded file contents inside of it.

答案

我从 http://php.net/manual/en/function复制了此文件. readfile.php ,并且现在可以正常工作.看来:ob_clean();做到了!谢谢大家的帮助.

I copied this from http://php.net/manual/en/function.readfile.php and it's working now. It seems that : ob_clean(); did the trick! Thanks for the help everyone.

#setting headers
    header('Content-Description: File Transfer');
    header('Content-Type: '.$type);
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;

推荐答案

我从 http://php.net/manual/zh-CN/function.readfile.php ,现在可以使用. ob_clean();做到了.

I copied this from http://php.net/manual/en/function.readfile.php and it works now. ob_clean(); did the trick..

    #setting headers
    header('Content-Description: File Transfer');
    header('Cache-Control: public');
    header('Content-Type: '.$type);
    header("Content-Transfer-Encoding: binary");
    header('Content-Disposition: attachment; filename='. basename($file));
    header('Content-Length: '.filesize($file));
    ob_clean(); #THIS!
    flush();
    readfile($file);

这篇关于PHP-简单的下载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆