我使用php下载文件,我希望文件在成功完成下载后自动从服务器上删除.我在php中使用此代码.
$fullPath = 'folder_name/download.txt';
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
$fd = fopen ($fullPath, "r");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
fclose ($fd);
}
unlink($fullPath);
Run Code Online (Sandbox Code Playgroud)
您可以在下载后在代码中看到我取消链接文件.但如果我这样做了损坏的文件被下载.因为有时文件会在完全下载之前被删除.无论如何在php中知道客户端成功下载文件然后我可以删除它吗?任何想法都将受到高度赞赏.
据我所知,您无法使用服务器端PHP来检测客户端的下载是否已完成.这似乎ignore_user_abort()是您的问题的答案(见下文),否则您可能会在一段时间后删除该文件.
ignore_user_abort(true);
if (connection_aborted()) {
unlink($f);
}
Run Code Online (Sandbox Code Playgroud)
Stackoverflow上的相关/重复: