用户下载文件后将其删除 [英] deleting a file after user download it

查看:69
本文介绍了用户下载文件后将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它向用户发送文件

I am using this for sending file to user

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

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

I want to delete this file after user downloads it, how can i do this?

我的情况是这样的,当用户按下下载按钮时,我的脚本将创建一个临时zip文件,然后用户下载该文件,然后将删除该临时zip文件.

My scenario is like that, when user hits download button, my script will create a temporary zip file and user download it then that temp zip file will be deleted.

最好的最佳方法似乎是运行一个cron作业,该作业每小时将清理一次临时文件.

OK best way seems running a cron job that will be cleaning temp files once an hour.

我用unlink测试了我的脚本,除非用户取消下载,否则它将起作用.如果用户取消下载,则zip文件将保留在服务器上.这样就足够了. :)

I tested my script with unlink, it works unless user cancel the download. If user cancel the download, zip file stays on the server. So that is enough for now. :)

哇! connection_aborted()骗了我!

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

即使用户取消下载,此文件也将删除文件.

This one will delete the file even if user cancel the download.

推荐答案

unlink($filename);

这将删除文件.

它需要与 ignore_user_abort() Docs 结合使用,这样即使用户取消了下载,仍会执行unlink.

It needs to be combined with ignore_user_abort()Docs so that the unlink is still executed even the user canceled the download.

ignore_user_abort(true);

...

unlink($f);

这篇关于用户下载文件后将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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