执行php tar 命令动态备份网站

Exec php tar command to backup website dynamically

我想使用 tar 命令和 Php 中的 exec 备份我的网站,我写了一个小脚本来执行此操作,但没有任何反应...我错在哪里?我有 php 5.6.5 和托管 linux,它启用了 exec 并且 tar 命令可用。这是我想做的 Php 示例。

<?php
  $root = $_SERVER['DOCUMENT_ROOT'];
  # root is /web/htdocs/www.example.com/home/
  $name = "backup_" . date("[d-m-Y][H-i]") . ".tar.gz";
  # name is backup_[25-02-2015][18-57].tar.gz
  $skip = "*.gz";
  # skip is the file I want to exclude (example: skip backup_[25-02-2015][18-57].tar.gz)
  if ((substr($_SERVER['DOCUMENT_ROOT'],-1,1) == "/") && (substr($_SERVER['PHP_SELF'],0,1) =="/")) {
    $sdir = $_SERVER['DOCUMENT_ROOT'] . substr(dirname($_SERVER['PHP_SELF']),1);
  } else {
    $sdir = $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']);
  }
  # sdir is /web/htdocs/www.example.com/home/bak/ and is the path where the script lives
  # out is the output
  # oky is the success o failed exec command
  function backup()  {
    exec("tar -cvf $sdir/$name $root/* --exclude='$sdir/$skip' ", $out, $oky);
  }
  backup();
  if (!$oky) {
    echo "$out: Backup Completed!";
  } else {
    echo "$out: Backup Not Completed!";
  }
?>

感谢任何帮助!

$oky$out 是局部变量。它们不在函数外设置。 $sdir$name$root 未在函数内定义。

方法 1 - 参数:

function backup($sdir,$name,$root,$salt)  {
    exec("tar -cvf $sdir/$name $root/* --exclude='$sdir/$salt' ", $out, $oky);
    return array("oky"=>$oky, "out"=>$out);
}

$result = backup($sdir, $name, $root, $salt);

if (!$result["oky"]) {
    echo $result["out"].": Backup Completed!";
} else {
    echo $result["out"].": Backup Not Completed!";
}

方法 2 - 不要使用函数:

exec("tar -cvf $sdir/$name $root/* --exclude='$sdir/$salt' ", $out, $oky);

if (!$oky) {
    echo "$out: Backup Completed!";
} else {
    echo "$out: Backup Not Completed!";
}

方法三——全局变量:

function backup()  {
    global $sdir,$name,$root,$salt,$oky,$out;
    exec("tar -cvf $sdir/$name $root/* --exclude='$sdir/$salt' ", $out, $oky);
}

backup();

if (!$oky) {
    echo "$out: Backup Completed!";
} else {
    echo "$out: Backup Not Completed!";
}