用户下载后删除文件

时间:2010-04-14 23:08:19

标签: php

我使用它将文件发送给用户

header('Content-type:  application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);

我想在用户下载后删除此文件,我该怎么做?

编辑:我的情况是这样的,当用户点击下载按钮时,我的脚本将创建一个临时zip文件,然后用户下载它,然后该临时zip文件将被删除。

EDIT2:好的最佳方式似乎是运行一个cron作业,每小时清理一次临时文件。

EDIT3:我用unlink测试了我的脚本,除非用户取消下载,否则它会正常工作。如果用户取消下载,则zip文件将保留在服务器上。所以这就足够了。 :)

EDIT4:哇! connection_aborted()成功了!

ignore_user_abort(true);
if (connection_aborted()) {
    unlink($f);
}

即使用户取消下载,也会删除该文件。

7 个答案:

答案 0 :(得分:27)

unlink($filename);

这将删除该文件。

需要与ignore_user_abort()Docs结合使用,以便即使用户取消下载,unlink仍会执行。

ignore_user_abort(true);

...

unlink($f);

答案 1 :(得分:12)

我总是使用以下解决方案:

register_shutdown_function('unlink', $file);

答案 2 :(得分:8)

没有任何正确的方法来检测用户是否完全下载了文件 因此,最好的方法是在一段时间不活动后删除文件。

答案 3 :(得分:3)

我的网站也有非常相似的功能。这就像删除随机创建的文件夹& zip文件/取消下载后。我试着在这里解释一下,可能有人发现它很有用。

<强> skin.php:
此页面包含下载链接,例如&#34; http://mysite.com/downoload/bluetheme"

<强> htaccess的:
我在htaccess文件中有以下规则将下载请求重定向到php文件。 [的download.php]。

RewriteRule ^download/([A-Za-z0-9]+)$ download.php?file=$1 [L]

download.php:

include "class.snippets.php";
$sn=new snippets();
$theme=$_GET['file'];
$file=$sn->create_zip($theme);
$path="skins/tmp/$file/$file.zip";
$config_file="skins/tmp/$file/xconfig.php";
$dir="skins/tmp/$file";

$file.=".zip";
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$file");
header("Pragma: no-cache");
header("Expires: 0");
readfile($path);

//remove file after download  
unlink($path);
unlink($config_file);
rmdir($dir);

所以请求download.php将使用片段类创建一个随机名称的目录。在目录中,它将创建一个zip文件。下载/取消请求后,将删除所有文件和目录。

答案 4 :(得分:3)

我无法找到对我有用的东西,所以我想出了这个,这似乎对我很有用:

header('Content-type: application/zip'); //this could be a different header 
header('Content-Disposition: attachment; filename="'.$zipName.'"');

ignore_user_abort(true);

$context = stream_context_create();
$file = fopen($zipName, 'rb', FALSE, $context);
while(!feof($file))
{
    echo stream_get_contents($file, 2014);
}
fclose($file);
flush();
if (file_exists($zipName)) {
    unlink( $zipName );
}

我希望能帮到某人

答案 5 :(得分:1)

connection_aborted()从未对我有用。 但是ob_clean()完全按照预期工作。希望这也能帮助别人

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $file . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
ob_clean();
flush();
if (readfile($file))
{
  unlink($file);
}

答案 6 :(得分:0)

我能想到的最安全的方法是使用一些可以从客户端观察传输的客户端flash电影,然后在下载完成后对服务器进行XmlHttpRequest调用。

AFAIK,没有使用Flash(或类似的浏览器插件),没有办法可靠地做到这一点

相关问题