简体   繁体   中英

Exec php tar command to backup website dynamically

I'd like to make a backup of my website using tar command and exec in Php and I wrote a small script to does that but nothing happens... where I fault? I have php 5.6.5 and hosting linux that has exec enabled and tar command available. Here is a Php example what I'd like to do.

<?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!";
  }
?>

Any help is appreciated!

$oky and $out are local variables. They are not set outside the function. $sdir , $name and $root are not defined within the function.

Method 1 - Parameters:

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!";
}

Method 2 - Don't use a function:

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

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

Method 3 - Global variables:

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!";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM