【问题标题】:Build Tar file from directory in PHP without exec/passthru在没有 exec/passthru 的 PHP 目录中构建 Tar 文件
【发布时间】:2010-09-24 21:22:51
【问题描述】:

所以我有一个客户,他的当前主机不允许我通过 exec()/passthru()/ect 使用 tar,我需要定期以编程方式备份​​站点,所以有解决方案吗?

这是一个 linux 服务器。

【问题讨论】:

  • 似乎是一个奇怪的限制。
  • 但并非完全通用,许多主机只是完全阻止使用而不是监禁用户。
  • 对,但考虑到 PHP 与文件系统交互的强大功能,这很愚蠢。
  • 我对此很好奇,因为我想要一个也适用于 Windows 的跨平台解决方案。

标签: php linux backup archive


【解决方案1】:

PHP 5.3 提供了一种更简单的方法来解决这个问题。

看这里:http://www.php.net/manual/en/phardata.buildfromdirectory.php

<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
?>

【讨论】:

  • 如果您有空目录(将被省略)、符号链接(省略)或损坏的符号链接(引发异常),这将不起作用,但将包括作为符号链接目标的空目录 - 看图。因此,在 98% 的情况下,这是一个很好的解决方案,而在其他情况下,这是一个很好的方法!
【解决方案2】:

http://pear.php.net/package/Archive_Tar,您可以下载 PEAR tar 包并像这样使用它来创建存档:

<?php
require 'Archive/Tar.php';
$obj = new Archive_Tar('archive.tar');
$path = '/path/to/folder/';
$handle=opendir($path); 
$files = array();
while(false!==($file = readdir($handle)))
 {
    $files[] = $path . $file;
 }

if ($obj->create($files))
 {
    //Sucess
 }
else
 {
    //Fail
 }
?>

【讨论】:

    【解决方案3】:

    Archive_Tar 库。如果由于某种原因不能使用,zip 扩展可能是另一种选择。

    【讨论】:

    • 你在我打字的时候发的,但我会留在这里,因为它有代码。
    【解决方案4】:

    我需要一个可以在 Azure 网站 (IIS) 上运行的解决方案,并且无法使用其他答案中的方法在服务器上创建新文件。对我有用的解决方案是使用小型 TbsZip 库进行压缩,它不需要在服务器的任何位置写入文件 - 它只是通过 HTTP 直接返回。

    这个线程很旧,但这种方法可能更通用和更完整的答案,所以我发布代码作为替代:

    // Compress all files in current directory and return via HTTP as a ZIP file
    // by buli, 2013 (http://buli.waw.pl)
    // requires TbsZip library from http://www.tinybutstrong.com
    
    include_once('tbszip.php'); // load the TbsZip library
    $zip = new clsTbsZip(); // instantiate the class
    $zip->CreateNew(); // create a virtual new zip archive
    
    // iterate through files, skipping directories
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));
    foreach($objects as $name => $object)
    { 
        $n = str_replace("/", "\\", substr($name, 2)); // path format
        $zip->FileAdd($n, $n, TBSZIP_FILE); // add fileto zip archive
    }
    
    $archiveName = "backup_".date('m-d-Y H:i:s').".zip"; // name of the returned file 
    $zip->Flush(TBSZIP_DOWNLOAD, $archiveName); // flush the result as an HTTP download
    

    这是整个article on my blog

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      相关资源
      最近更新 更多