我使用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脚本下载"zip"文件时遇到的问题.似乎当我使用以下代码下载文件时,下载的文件在文件的开头附加了额外的0A09,导致winzip抛出损坏错误.
<?php
$pagePermissions = 7;
require_once ('util/check.php');
require_once ('util/file_manager.php');
$file_manager = new FileManager();
if ($_SERVER['REQUEST_METHOD'] == "GET") {
if (isset($_GET['q']) && $_GET['q'] == 'logout') {
//require_once ('util/users.php');
//$userdata = new Userdata();
$userdata -> kill_session();
header("Location: download.php");
exit ;
}
if (isset($_GET['q']) && $_GET['q'] == 'fetch') {
if (isset($_GET['name'])) {
@apache_setenv('no-gzip', 1);
header("Content-length: " . filesize('upload/' . $_GET['name']));
header('Content-type: application/zip');
//header("Content-Disposition: attachment; filename=\"{$_GET['name']}\" ");
header("Content-Disposition: attachment; filename={$_GET['name']}");
header('Content-Transfer-Encoding: binary');
readfile('upload/' . $_GET['name']);
exit();
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激,文件通过直接链接下载正常,文件的开头附加的2个字节只发生在这个代码.提前致谢
php ×2