使用php进行文件备份

发布于 2024-10-30 20:53:17 字数 193 浏览 0 评论 0原文

我想使用 php 创建给定文件夹中所有文件的快照,然后将其压缩。

我该怎么办呢。正在将内置函数压缩到 php.ini。还有压缩的替代方法吗?

您的代码采用哪种类型的文件备份系统?我正在为一个开源应用程序执行此操作,因此它不会备份我的特定系统,因此它必须纯粹使用 PHP,因为人们并不总是知道如何安装某些应用程序。

谢谢你们。

I want to use php to create a snapshot of all the files in a given folder and then zip it.

How can I do that. Is zipping a built in function to php. Also are there any alternatives to compressing.

What sort of file backup system do you have in place for your code. I am doing this for an open source application, so it is not backing up my particular system, so it has to be purely in PHP as people won't always know how to install certain applications.

Thanks guys.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

‖放下 2024-11-06 20:53:17

已经回答 - PHP 递归备份脚本

编辑

添加到旧的且极其糟糕的原始答案。 ..

这是一个基本使用的简单类,

用法:您只需将项目路径作为构造参数传递即可。它将递归地压缩项目并将其存储在名为 ./project_backups/ 的文件夹中,您可以选择设置第二个构造参数以仅将文件作为下载发送。与其他答案有点不同。

<?php
//Example Usage/s
$backup = new BackupMyProject('./path/to/project/yada');

print_r($backup);
/*
Then your have the object properties to determine the backup

$backup = BackupMyProject Object
(
    [project_path] => ./path/to/project/yada
    [backup_file] => ./project_backups/yada.zip
)

Alternatively set the second parameter and just send the project as a download.
BackupMyProject('./path/to/project/yada', true);
*/


/**
 * Zip a directory into a backups folder, 
 *  optional send the zip as a download
 * 
 * @author Lawrence Cherone
 * @version 0.1
 */
class BackupMyProject{
    // project files working directory - automatically created
    const PWD = "./project_backups/";

    /**
     * Class construct.
     *
     * @param string $path
     * @param bool $download
     */
    function __construct($path=null, $download=false){
        // check construct argument
        if(!$path) die(__CLASS__.' Error: Missing construct param: $path');
        if(!file_exists($path)) die(__CLASS__.' Error: Path not found: '.htmlentities($path));
        if(!is_readable($path)) die(__CLASS__.' Error: Path not readable: '.htmlentities($path));

        // set working vars
        $this->project_path = rtrim($path, '/');
        $this->backup_file  = self::PWD.basename($this->project_path).'.zip';

        // make project backup folder
        if(!file_exists(self::PWD)){
            mkdir(self::PWD, 0775, true);
        }

        // zip project files
        try{
            $this->zipcreate($this->project_path, $this->backup_file);
        }catch(Exception $e){
            die($e->getMessage());
        }

        if($download !== false){
            // send zip to user
            header('Content-Description: File Transfer');
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="'.basename($this->backup_file).'"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: '.sprintf("%u", filesize($this->backup_file)));
            readfile($this->backup_file);
            // cleanup
            unlink($this->backup_file);
        }
    }

    /**
     * Create zip from extracted/fixed project.
     *
     * @uses ZipArchive
     * @uses RecursiveIteratorIterator
     * @param string $source
     * @param string $destination
     * @return bool
     */
    function zipcreate($source, $destination) {
        if (!extension_loaded('zip') || !file_exists($source)) {
            throw new Exception(__CLASS__.' Fatal error: ZipArchive required to use BackupMyProject class');
        }
        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            throw new Exception(__CLASS__. ' Error: ZipArchive::open() failed to open path');
        }
        $source = str_replace('\\', '/', realpath($source));
        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));
                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source.'/', '', $file.'/'));
                } else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source.'/', '', $file), file_get_contents($file));
                }
            }
        }
        return $zip->close();
    }

}

Already answered - PHP Recursive Backup Script

Edit

To add to an old, and extremely poor original answer...

Here is a simple class which basically uses,

Usage: You simply pass the project path as a construct parameter. It will recursively zip and store the project in a folder called ./project_backups/, you can optionally set a second construct parameter to just send the file as a download. Something a little different from the other answers.

<?php
//Example Usage/s
$backup = new BackupMyProject('./path/to/project/yada');

print_r($backup);
/*
Then your have the object properties to determine the backup

$backup = BackupMyProject Object
(
    [project_path] => ./path/to/project/yada
    [backup_file] => ./project_backups/yada.zip
)

Alternatively set the second parameter and just send the project as a download.
BackupMyProject('./path/to/project/yada', true);
*/


/**
 * Zip a directory into a backups folder, 
 *  optional send the zip as a download
 * 
 * @author Lawrence Cherone
 * @version 0.1
 */
class BackupMyProject{
    // project files working directory - automatically created
    const PWD = "./project_backups/";

    /**
     * Class construct.
     *
     * @param string $path
     * @param bool $download
     */
    function __construct($path=null, $download=false){
        // check construct argument
        if(!$path) die(__CLASS__.' Error: Missing construct param: $path');
        if(!file_exists($path)) die(__CLASS__.' Error: Path not found: '.htmlentities($path));
        if(!is_readable($path)) die(__CLASS__.' Error: Path not readable: '.htmlentities($path));

        // set working vars
        $this->project_path = rtrim($path, '/');
        $this->backup_file  = self::PWD.basename($this->project_path).'.zip';

        // make project backup folder
        if(!file_exists(self::PWD)){
            mkdir(self::PWD, 0775, true);
        }

        // zip project files
        try{
            $this->zipcreate($this->project_path, $this->backup_file);
        }catch(Exception $e){
            die($e->getMessage());
        }

        if($download !== false){
            // send zip to user
            header('Content-Description: File Transfer');
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="'.basename($this->backup_file).'"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: '.sprintf("%u", filesize($this->backup_file)));
            readfile($this->backup_file);
            // cleanup
            unlink($this->backup_file);
        }
    }

    /**
     * Create zip from extracted/fixed project.
     *
     * @uses ZipArchive
     * @uses RecursiveIteratorIterator
     * @param string $source
     * @param string $destination
     * @return bool
     */
    function zipcreate($source, $destination) {
        if (!extension_loaded('zip') || !file_exists($source)) {
            throw new Exception(__CLASS__.' Fatal error: ZipArchive required to use BackupMyProject class');
        }
        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            throw new Exception(__CLASS__. ' Error: ZipArchive::open() failed to open path');
        }
        $source = str_replace('\\', '/', realpath($source));
        if (is_dir($source) === true) {
            $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
            foreach ($files as $file) {
                $file = str_replace('\\', '/', realpath($file));
                if (is_dir($file) === true) {
                    $zip->addEmptyDir(str_replace($source.'/', '', $file.'/'));
                } else if (is_file($file) === true) {
                    $zip->addFromString(str_replace($source.'/', '', $file), file_get_contents($file));
                }
            }
        }
        return $zip->close();
    }

}
哀由 2024-11-06 20:53:17

如果您有执行命令的权限。您可以使用 exec 函数创建 tar.gz 文件。例如:

<?php 
   exec("tar -czf folder.tar.gz folder");
?>

If you have the privileges to execute commands. You can create a tar.gz files using the exec function. For example:

<?php 
   exec("tar -czf folder.tar.gz folder");
?>
孤单情人 2024-11-06 20:53:17

一个简单的方法:

<?php
$old1 = 'file.php';
$new1 = 'backup.php';
copy($old1, $new1) or die("Unable to backup");

echo 'Backup Complete. <a href="./index.php">Return to the Editor</a>';
?>

an easy way:

<?php
$old1 = 'file.php';
$new1 = 'backup.php';
copy($old1, $new1) or die("Unable to backup");

echo 'Backup Complete. <a href="./index.php">Return to the Editor</a>';
?>
可遇━不可求 2024-11-06 20:53:17

这是一个具有 ftp、mysqldump 和文件系统功能的备份脚本 https://github.com/skywebro/php-backup

Here is a backup script with ftp, mysqldump and filesystem capabilities https://github.com/skywebro/php-backup

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文