简体   繁体   English

下载后删除文件-PHP

[英]Delete file after downloading - PHP

I am working on Moodle 2.2.1 and have created dynamic.csv files using certain queries. 我正在使用Moodle 2.2.1,并使用某些查询创建了dynamic.csv文件。 I have created a /tmp/ directory with write permissions in my home directory and using file functions I have created a .csv file thru my code. 我已经在主目录中创建了一个具有写权限的/ tmp /目录,并使用文件功能通过代码创建了一个.csv文件。

Everything works fine with the normal fopen(), fwrite() functions and csv files get created every time dynamically. 正常的fopen(),fwrite()函数和每次动态创建的csv文件都可以正常工作。 I have kept these files for downloading for users with this piece of code. 我保留了这些文件,并通过这段代码供用户下载。

<a href='/moodle/tmp/'".$filename."'> Download </a>

N with this line in .htaccess, the files are downloadable to any one's machine. N .htaccess中带有此行,则文件可下载到任何人的计算机上。

 AddType application/octet-stream .csv

But the problem right now is, every time I load the page, same .csv files get created with different timestamps. 但是现在的问题是,每次我加载页面时,都会使用不同的时间戳创建相同的.csv文件。 Basically I get a lot many duplicate files with different timestamps in my /tmp/ directory. 基本上,我的/ tmp /目录中有很多带有不同时间戳的重复文件。

Is there a way that on every load of that page, all the existing instances of the files in that folder get deleted and a fresh batch of files are ready for download. 有没有一种方法可以在该页面的每次加载中删除该文件夹中文件的所有现有实例,并准备下载一批新文件。 So that I do not have duplicate files and just one instance of each file. 这样我就不会有重复的文件,而每个文件只有一个实例。

If any one can help me with this, I would really appreciate. 如果有人可以帮助我,我将不胜感激。

Thanks 谢谢

EDIT: If my code for creating and writing a .csv file is this, then where should I delete the old files with timestamp before an hour and how to retain newest files. 编辑:如果我的代码用于创建和写入.csv文件,那么我应该在哪里删除一个小时前带有时间戳的旧文件,以及如何保留最新文件。

 foreach($uniquenames as $uniquename)
 {
$data = "Header1,Header2,Header3,Header4,Header5\n";
$filename = $uniquename.'_'.time().'.csv';
$writepath = $filepath.$filename;
$fh       = fopen($writepath, 'w');
$result = $functions->getFiless();
foreach($result as $activity)
{
    if($uniquename == $activity->quiz)
    {
        $data .= .$somedata.",".$foreachheader."\n";        
    }
    else
    {

    }
}
fwrite($fh, $data);
fclose($fh);
echo "<p>".$uniquename . "<div class='assessment-reportlink'><a href='/moodle/tmp/".$filename."'> Download </a></p></div>";

} }

this is works for me: 这对我有用:

$file = $_GET['f'];

if ($file and file_exists($file)) 
{
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Disposition: attachment; filename='.basename($file));
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($file));
  ob_clean();
  flush();
  if (readfile($file)) 
  {
    unlink($file);
  }
}

What you basically need to do is: 您基本上需要做的是:

  • Scan the directory with scandir() 使用scandir()扫描目录
  • Loop over it and check file creation times with filemtime() to find the 'newest file' 循环遍历并使用filemtime()检查文件创建时间以查找“最新文件”
  • Delete all the files with unlink() that have older timestamps 使用unlink()删除所有带有较早时间戳记的文件

But do remember that sometimes it is a good idea to keep files with older timestamps. 但是请记住,有时保留带有旧时间戳的文件是个好主意。 What if a link exists to one of the older files by a user running in parallel session? 如果并行会话中运行的用户存在到较旧文件之一的链接怎么办? I suggest not deleting files based on what is 'newest', but based on time. 我建议不要基于“最新”删除文件,而是基于时间。

Perhaps delete every file that is older than one hour and that is not the newest file. 也许删除所有早于一个小时且不是最新文件的文件。

EXAMPLE OF DELETING ALL FILES EXCEPT ONE WITH THE NEWEST TIMESTAMP: 删除带有最新时间戳的一个以上的所有文件的示例:

// This is where I would scan the files from
$directory='./mycsv/';

// This scans the files
$files=scandir($directory);

// I will store the 'newest' timestamp here
$newestFileModifiedTime=0;

// Making sure that there are files
if(!empty($files)){
    foreach($files as $file){
        // This ignores all current and parent directory references
        if($file!='.' && $file!='..'){
            // This ignores a directory, if that folder has other folders in it
            if(!is_dir($directory.$f)){
                $fileModifiedTime=filemtime($directory.$file);
                if($fileModifiedTime>$newestFileModifiedTime){
                    $newestFileModifiedTime=$fileModifiedTime;
                }
            }
        }   
    }
    // We loop again since we found a file timestamp
    if($newestFileModifiedTime!=0){
        foreach($files as $file){
            // This ignores all current and parent directory references
            if($file!='.' && $file!='..'){
                // This ignores a directory, if that folder has other folders in it
                if(!is_dir($directory.$f)){
                    // This deletes all the files that are not with the newest timestamp
                    if(filemtime($directory.$file)!=$newestFileModifiedTime){
                        // Deleting the file
                        unlink($directory.$file);
                    }
                }
            }   
        }
    }
}

在创建文件之前,请遍历该目录中的现有文件并删除不需要的文件。

创建文件之前:

foreach (glob("*.csv") as $filename) {

unlink($filename);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM