Linux环境下备份ThinkPHP的可执行方案
一 备份策略与准备
二 方案一 快速命令行备份(适合临时或手动)
cd /var/www
sudo tar -czvf your_project_$(date +%F_%H-%M-%S).tar.gz your_project_directory
mysqldump -h 127.0.0.1 -u dbuser -p dbname > db_backup_$(date +%F_%H-%M-%S).sql
三 方案二 ThinkPHP自定义命令备份(可集成与自动化)
<?php
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
class Backup extends Command
{
protected function configure()
{
$this->setName('backup')->setDescription('Database backup command');
}
protected function execute(Input $input, Output $output)
{
$cfg = Db::getConfig();
$host = $cfg['hostname'] ?? '127.0.0.1';
$port = $cfg['hostport'] ?? 3306;
$user = $cfg['username'];
$pass = $cfg['password'];
$db = $cfg['database'];
$backupDir = runtime_path() . 'backup/';
if (!is_dir($backupDir)) mkdir($backupDir, 0755, true);
$file = $backupDir . 'backup_' . date('Y-m-d_H-i-s') . '.sql';
// 注意:-p后不要有空格,出于安全建议从环境变量读取密码
$cmd = sprintf(
'mysqldump -h%s -P%s -u%s -p%s %s > %s',
escapeshellarg($host),
escapeshellarg($port),
escapeshellarg($user),
escapeshellarg($pass),
escapeshellarg($db),
escapeshellarg($file)
);
$output->writeln("Starting backup: {$file}");
exec($cmd, $lines, $ret);
if ($ret === 0) {
$output->writeln("Backup succeeded: {$file}");
} else {
$output->error("Backup failed, exit code: {$ret}");
foreach ($lines as $l) $output->writeln($l);
}
}
}
return [
'commands' => [
'app\command\Backup',
],
];
php think backup
ls -lh runtime/backup/
四 自动化与恢复
# 每天 02:00 备份数据库到 runtime/backup/
0 2 * * * /usr/bin/php /var/www/your_project backup >> /var/log/backup.log 2>&1
# 每周日 03:00 打包整个项目目录到 /data/backup/
0 3 * * 0 cd /var/www && tar -czf /data/backup/your_project_$(date +\%F).tar.gz your_project_directory
mysql -h 127.0.0.1 -u dbuser -p dbname < /path/to/backup_2025-11-18_10-00-00.sql