在php中下载后从服务器删除文件
我正在使用php下载一个文件,我希望该文件应该得到删除后,从服务器自动下载成功完成。我正在php中使用这段代码在php中下载后从服务器删除文件,php,Php,我正在使用php下载一个文件,我希望该文件应该得到删除后,从服务器自动下载成功完成。我正在php中使用这段代码 $fullPath = 'folder_name/download.txt'; if ($fd = fopen ($fullPath, "r")) { $fsize = filesize($fullPath); $path_parts = pathinfo($fullPath); $ext = strtolower($path_parts["extension
$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);
您可以在下载后的代码中看到我正在解除文件链接。但如果我这么做,损坏的文件将被下载。因为有时候文件在完全下载之前就被删除了。在php中是否有人知道客户端成功下载了文件,然后我就可以删除它?任何想法都将受到高度赞赏 检查服务器端和客户端文件的哈希代码。。。
您可以使用javascript()检查哈希代码并将其发送到服务器,然后检查它是否与服务器上的al相同…据我所知,您无法使用服务器端PHP来检测客户端的下载是否已完成。这似乎是您问题的答案(见下文),否则您可以在设定的时间后删除该文件
ignore_user_abort(true);
if (connection_aborted()) {
unlink($f);
}
Stackoverflow上的相关/重复:
不确定它在几乎所有情况下都能起作用,但尝试一下睡眠(10);将文件删除延迟一段特定时间的操作。对于大文件来说,这可能有点问题,但是对于快速连接的小文件,我使用它没有问题
<?php
### Check the CREATE FILE has been set and the file exists
if(isset($_POST['create_file']) && file_exists($file_name)):
### Download Speed (in KB)
$dls = 50;
### Delay time (in seconds) added to download time
$delay = 5;
## calculates estimated download time
$timer = round(filesize($file_name) / 1024 / $dls + $delay);
###Calculates file size in kb divides by download speed + 5 ?>
<iframe width="0" height="0" frameborder="0" src="<?php echo $file_name;?>"></iframe>
<h2>Please Wait, Your Download will complete in: <span id="logout-timer"></span></h2>
没有什么好方法可以告诉你下载已经完成。如果你打算下载的文件不是大文件,那么你能做的最好的事情就是通过电子邮件发送它们并立即删除它们。你能做一个文件大小检查并比较大小是否相同吗?完成了吗?文件删除比文件下载要快真的很简单,因为他可以同时打开两个文件-然后使用stream_copy_to_stream-删除旧文件并只读取tmp文件-但这将中断部分下载:)这似乎不是真的。为什么PHP不能读取服务器日志并记录文件传输的时间。只需将所有2xx请求传输大小相加,如果等于或大于(HTTP头开销),则文件已下载。
<script>setTimeout(function(){ window.location = "<?php echo $_SERVER['PHP_SELF']?>?f=<?php echo $file_name;?>";},<?php echo $timer;?>000);</script>
<?php
endif;
if (isset($_GET['f'])):
unlink($_GET['f']);
### removes GET value and returns to page's original url
echo "<script> location.replace('".$_SERVER['PHP_SELF']."')</script>";
endif;?>
<script>
var seconds=<?php echo $timer;?>;function secondPassed(){var a=Math.round((seconds-30)/60);var b=seconds%60;if(b<10){b="0"+b}document.getElementById('logout-timer').innerHTML=a+":"+b;if(seconds==0){clearInterval(countdownTimer);document.getElementById('logout-timer').innerHTML="Timer"}else{seconds--}}var countdownTimer=setInterval('secondPassed()',1000);
</script>