【问题标题】:PHP Backup & DownloadPHP 备份和下载
【发布时间】:2012-09-11 17:54:44
【问题描述】:

我想为我的服务器上的文件和文件夹创建一个备份脚本,我发现了这个:

# Name of the buckup file
$filename = 'BACKUP_' . date('Y.m.d') . '.tar.gz';
# Target path where to save the file
$targetPath = '/path/to/backup/';
# Directory to backup
$dir = "/path/to/files/";  


# Execute the tar command and save file
system( "tar -pczf ".$targetPath ."".$filename." ".$dir );

效果很好,然后我可以将 URL 传递给脚本和正确的标题并下载文件。

我的问题是我会经常运行它并且不想将备份保留在服务器上。所以我试图找到一种创造性的方式来创建一个被删除的临时文件。问题是某些文件可能相当大,我无法知道文件何时已完全下载。

【问题讨论】:

    标签: php backup temp


    【解决方案1】:

    您可以在 /tmp 中创建备份文件,然后使用:

    # Name of the buckup file
    $filename = 'BACKUP_' . date('Y.m.d') . '.tar.gz';
    # Target path where to save the file
    $targetPath = '/path/to/backup/';
    # Directory to backup
    $dir = "/path/to/files/";  
    # Execute the tar command and save file
    system( "tar -pczf ".$targetPath ."".$filename." ".$dir );
    
    readfile("{$targetPath}{$filename}"); // outputs file contents to a browser
    unlink("{$targetPath}{$filename}"); // removes file from disk
    

    阅读http://php.net/manual/ru/function.readfile.php了解更多信息。

    PS 您也可以使用 ZipArchive 类(内置)更灵活地创建自己的存档。

    【讨论】:

      【解决方案2】:

      在数据库中添加文件名/路径和创建的时间戳,编写一个 cron 作业来删除任何大于您想要保留它的时间的内容。让它每小时运行一次,30 分钟。不管你觉得多么频繁是必要的。

      至于是否已下载,请创建下载管理器。 /download/file/id,其中 id 可以是该表中的 PK,并且仅在尚未下载时才删除,除非它已经 48 小时,或者类似的东西。

      【讨论】:

      • 或者没有数据库,只需在文件名中包含时间戳即可。
      • 可能,那么您将不得不扫描目录,如果它是一个高流量站点,那么与数据库相比,这将使用大量 I/O。此外,将无法跟踪下载。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2016-11-07
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2020-10-19
      相关资源
      最近更新 更多