如何在PHP中备份MySQL数据库?

时间:2022-04-08 11:14:48

I got this tutorial from the Internet. But I don't even have a basic understanding on how backup of a MySQL database through PHP would work.

我从网上得到了这个教程。但是我甚至不知道如何通过PHP备份MySQL数据库。

Using PHP to Backup MySQL Databases

使用PHP备份MySQL数据库

Can you recommend some sites that I can use as a reference so that I can study it?

你能推荐一些我可以参考的网站吗?

12 个解决方案

#1


47  

While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.

虽然您可以执行来自PHP的备份命令,但它们实际上与PHP没有任何关系。这是关于MySQL。

I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.

我建议使用mysqldump实用程序来备份数据库。文档可以在这里找到:http://dev.sqmyl.com/doc/refman/5.1 /en/mysqldump.html。

The basic usage of mysqldump is

mysqldump的基本用法是

mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like

然后,您可以使用类似的命令来恢复备份

mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like

你能接触到克伦吗?我建议编写一个PHP脚本,将mysqldump作为cron作业运行。就像这样

<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if($output==''){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.

如果mysqldump不可用,本文将使用SELECT INTO OUTFILE和LOAD DATA INFILE命令描述另一种方法。与PHP的唯一连接是使用PHP连接数据库并执行SQL命令。你也可以从命令行MySQL程序,MySQL监视器。

It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.

这非常简单,您正在编写一个SQL文件,其中只有一个命令,并在恢复时加载/执行它。

You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

您可以在这里找到select into outfile的文档(只需在页面中搜索outfile)。加载数据文件本质上是相反的。看这里的文档。

#2


19  

Backup DB using PHP

example:

例子:

EXPORT_TABLES("localhost","user","pass","db_name" );

code:

代码:

<?php
// https://github.com/tazotodua/useful-php-scripts 
                //optional: 5th parameter - backup specific tables only: array("mytable1","mytable2",...)   
                //optional: 6th parameter - backup filename
                // NOTE! to adequatelly replace strings in DB, MUST READ:   goo.gl/nCwWsS

function EXPORT_TABLES($host,$user,$pass,$name,       $tables=false, $backup_name=false){ 
    set_time_limit(3000); $mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; }   if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); } 
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
    foreach($target_tables as $table){
        if (empty($table)){ continue; } 
        $result = $mysqli->query('SELECT * FROM `'.$table.'`');     $fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;     $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row(); 
        $content .= "\n\n".$TableMLine[1].";\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) {
            while($row = $result->fetch_row())  { //when started (and every after 100 command cycle):
                if ($st_counter%100 == 0 || $st_counter == 0 )  {$content .= "\nINSERT INTO ".$table." VALUES";}
                    $content .= "\n(";    for($j=0; $j<$fields_amount; $j++){ $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ;}  else{$content .= '""';}     if ($j<($fields_amount-1)){$content.= ',';}   }        $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;
            }
        } $content .="\n\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
    ob_get_clean(); header('Content-Type: application/octet-stream');   header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\"");
    echo $content; exit;
}      //see import.php too
?>

//updated per @Mohammad's advise.

/ /更新/ @Mohammad的建议。

#3


11  

Here is a pure PHP class to perform backups on MySQL databases not using mysqldump or mysql commands: Backing up MySQL databases with pure PHP

这里有一个纯PHP类,可以在不使用mysqldump或MySQL命令的MySQL数据库上执行备份:使用纯PHP备份MySQL数据库

#4


5  

Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect has deprecated and not supported in new php version. I've used mysqli_connect instead and increased the performance of inserting values to the database:

基于tazo todua提供的良好解决方案,我已经做了一些更改,因为mysql_connect已经被弃用,并且在新的php版本中不受支持。我使用了sqmyli_connect,并提高了向数据库插入值的性能:

<?php

/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/


//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';

//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);

//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
    $link = mysqli_connect($host,$user,$pass, $dbname);

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    }

    mysqli_query($link, "SET NAMES 'utf8'");

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;

        //Over tables
        for ($i = 0; $i < $num_fields; $i++) 
        {   //Over rows
            while($row = mysqli_fetch_row($result))
            {   
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }

                //Over fields
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }

                if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }
                ++$counter;
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
    $handle = fopen($fileName,'w+');
    fwrite($handle,$return);
    if(fclose($handle)){
        echo "Done, the file name is: ".$fileName;
        exit; 
    }
}

#5


5  

If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:

如果你想从php脚本中备份一个数据库,你可以使用一个类,比如我们叫它MySQL。这个类将使用PDO(在php类中构建,用于处理与数据库的连接)。这个类可以是这样的:

<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>

<?php /*defined in examplemyclass.php*/
    class MySql{
        private $dbc;
        private $user;
        private $pass;
        private $dbname;
        private $host;

        function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
            $this->user = $user;
            $this->pass = $pass;
            $this->dbname = $dbname;
            $this->host = $host;
            $opt = array(
               PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
               PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );
            try{
                $this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
            }
            catch(PDOException $e){
                 echo $e->getMessage();
                 echo "There was a problem with connection to db check credenctials";
            }
        } /*end function*/


        public function backup_tables($tables = '*'){  /* backup the db OR just a table */
            $host=$this->host;
            $user=$this->user;
            $pass=$this->pass;
            $dbname=$this->dbname;
            $data = "";
            //get all of the tables
            if($tables == '*')
            {
                $tables = array();
                $result = $this->dbc->prepare('SHOW TABLES'); 
                $result->execute();                         
                while($row = $result->fetch(PDO::FETCH_NUM)) 
                { 
                    $tables[] = $row[0]; 
                }
            }
            else
            {
                $tables = is_array($tables) ? $tables : explode(',',$tables);
            }
            //cycle through
            foreach($tables as $table)
            {
                $resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
                $resultcount->execute();
                $num_fields = $resultcount->fetch(PDO::FETCH_NUM);
                $num_fields = $num_fields[0];

                $result = $this->dbc->prepare('SELECT * FROM '.$table);
                $result->execute();
                $data.= 'DROP TABLE '.$table.';';

                $result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);    
                $result2->execute();                            
                $row2 = $result2->fetch(PDO::FETCH_NUM);
                $data.= "\n\n".$row2[1].";\n\n";

                for ($i = 0; $i < $num_fields; $i++) 
                {
                    while($row = $result->fetch(PDO::FETCH_NUM))
                    { 
                        $data.= 'INSERT INTO '.$table.' VALUES(';
                        for($j=0; $j<$num_fields; $j++) 
                        {
                            $row[$j] = addslashes($row[$j]); 
                            $row[$j] = str_replace("\n","\\n",$row[$j]);
                            if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
                            if ($j<($num_fields-1)) { $data.= ','; }
                        }
                        $data.= ");\n";
                    }
                }
                $data.="\n\n\n";
            }
            //save filename
            $filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
            $this->writeUTF8filename($filename,$data);
        /*USE EXAMPLE
           $connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
           $connection->backup_tables(); //OR backup_tables("posts");
           $connection->closeConnection();
        */
        } /*end function*/


        private function writeUTF8filename($filenamename,$content){  /* save as utf8 encoding */
            $f=fopen($filenamename,"w+"); 
            # Now UTF-8 - Add byte order mark 
            fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
            fwrite($f,$content); 
            fclose($f); 
        /*USE EXAMPLE this is only used by public function above...
            $this->writeUTF8filename($filename,$data);
        */
        } /*end function*/


        public function recoverDB($file_to_load){
            echo "write some code to load and proccedd .sql file in here ...";
        /*USE EXAMPLE this is only used by public function above...
            recoverDB("some_buck_up_file.sql");
        */
        } /*end function*/


        public function closeConnection(){
            $this->dbc = null;
        //EXAMPLE OF USE 
        /*$connection->closeConnection();*/
        }/*end function*/


    } /*END OF CLASS*/
    ?>

Now you could simply use this in your backup.php:

现在你可以在你的备份中使用这个:

include ('config.php');
include ('myclass.php');
    $connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
    $connection->backup_tables(); /*Save all tables and it values in selected database*/
    $connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
    $connection->closeConnection();

Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would recommend to write it to one file at all the time instead of creating new files with time()... as it is above.

这意味着访问这个页面将导致备份您的文件……当然,这并不一定是这样的:)你可以在你的数据库上的每一个帖子上都调用这个方法,一直到现在为止,但是,我建议你一直把它写到一个文件,而不是用时间()来创建新的文件……因为它是。

Hope it helps and good luck ! :>

祝你好运!:>

#6


1  

I would recommend using mysqldump and from php use the system command as suggested in the article you found.

我建议使用mysqldump,从php使用system命令,如您找到的文章中所建议的那样。

#7


1  

Here is php file which will let you create/download your database backup in efficient manner This single file with on page security functionality. only you have to download that file place in your public folder or project folder and call it through browser.

这里是php文件,它将允许您以高效的方式创建/下载您的数据库备份,并在页面安全功能上使用该文件。只需要下载公共文件夹或项目文件夹中的文件位置并通过浏览器调用即可。

Download URL- https://github.com/vkt005/php-mysql-db-backup

下载URL https://github.com/vkt005/php-mysql-db-backup

#8


1  

I also had a situation and i could'nt find a tool to satisfy me. So for the sake of backup/restore mysql data from PHP i have made a program that can compress the data into a zip file that you can download. Later you can upload and restore full database. You can find it in my Github page https://github.com/JoshyFrancis/mysql_backup_restore_php

我也有过这样的情况,我找不到让我满意的工具。为了从PHP中备份/恢复mysql数据,我做了一个程序,可以将数据压缩到一个zip文件中,您可以下载。稍后您可以上传和恢复完整的数据库。您可以在我的Github页面https://github.com/JoshyFrancis/mysql_backup_restore_php中找到它。

#9


1  

Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.

看一看这里!它是用php编写的本地解决方案。您不需要执行mysqldump,或者处理不完整的脚本。这是一个完整的mysqldump克隆,没有依赖项、输出压缩和健全的默认值。

Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.

在开箱即用的情况下,mysqldump-php支持备份表结构、数据本身、视图、触发器和事件。

MySQLDump-PHP is the only library that supports:

MySQLDump-PHP是唯一支持的库:

  • output binary blobs as hex.
  • 输出二进制blobs为十六进制。
  • resolves view dependencies (using Stand-In tables).
  • 解析视图依赖项(使用替代表)。
  • output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
  • 输出与原始mysqldump的比较。连接到travi -ci测试系统(从php 5.3到7.1和hhvm测试)
  • dumps stored procedures.
  • 转储文件存储过程。
  • dumps events.
  • 转储事件。
  • does extended-insert and/or complete-insert.
  • extended-insert和/或complete-insert。
  • supports virtual columns from MySQL 5.7.
  • 支持来自MySQL 5.7的虚拟列。

You can install it using composer, or just download the php file, and it is as easy as doing:

您可以使用composer安装它,也可以下载php文件,操作简单:

use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:

所有选项都在github页面上进行了解释,但或多或少都是自动解释的:

$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

#10


0  

@tazo todua's answer above

@tazo todua上面的回答

Although I've up-voted the answer above, since it was the only one working solution with 'pure' PHP implementation that did not produce 0 length files, and the files look fine at first look, however, note that it failed at some FOREIGN KEYS when I tried to import back my database from the backup file.

尽管我up-voted上面的答案,因为它是唯一一个与“纯”PHP实现解决方案合作没有产生0长度文件,和这些文件看起来好乍一看,然而,请注意,它失败的一些外键当我试图导入数据库的备份文件。

Solutions based on mysqldump in PHP are much safer to use.

在PHP中使用基于mysqldump的解决方案要安全得多。

#11


0  

Solution to take backup of your Database in "dbBackup" Folder / Directory

在“dbBackup”文件夹/目录中备份数据库的解决方案

<?php
error_reporting(E_ALL);

/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", '');
define("DB_NAME", 'YOUR_DATABASE _NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder / Directory Name
define("TABLES", '*');

/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status . " - By Irshad Khan";

/* The Backup_Database class */

class Backup_Database {
/* Host where database is located  */

  var $host = 'localhost';
  var $username = 'root';
  var $passwd = '';
  var $dbName = 'YOUR_DATABASE _NAME';
  var $charset = '';

  /* Constructor initializes database */

  function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8') {
    $this->host = $host;
    $this->username = $username;
    $this->passwd = $passwd;
    $this->dbName = $dbName;
    $this->charset = $charset;
    $this->initializeDatabase();
  }

  protected function initializeDatabase() {
    $conn = @mysql_connect($this->host, $this->username, $this->passwd); // Ik Added @ to Hide PDO Error Message
    mysql_select_db($this->dbName, $conn);
    if (!mysql_set_charset($this->charset, $conn)) {
      mysql_query('SET NAMES ' . $this->charset);
    }
  }

  /* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables  */

  public function backupTables($tables = '*', $outputDir = '.') {
    try {
      /* Tables to export  */
      if ($tables == '*') {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while ($row = mysql_fetch_row($result)) {
          $tables[] = $row[0];
        }
      } else {
        $tables = is_array($tables) ? $tables : explode(',', $tables);
      }

      $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
      $sql .= 'USE ' . $this->dbName . ";\n\n";

  /* Iterate tables */
  foreach ($tables as $table) {
    echo "Backing up " . $table . " table...";

    $result = mysql_query('SELECT * FROM ' . $table);
    $numFields = mysql_num_fields($result);

    $sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
    $sql.= "\n\n" . $row2[1] . ";\n\n";

    for ($i = 0; $i < $numFields; $i++) {
      while ($row = mysql_fetch_row($result)) {
        $sql .= 'INSERT INTO ' . $table . ' VALUES(';
        for ($j = 0; $j < $numFields; $j++) {
          $row[$j] = addslashes($row[$j]);
          // $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
          if (isset($row[$j])) {
            $sql .= '"' . $row[$j] . '"';
          } else {
            $sql.= '""';
          }
          if ($j < ($numFields - 1)) {
            $sql .= ',';
          }
        }
        $sql.= ");\n";
      }
    }
    $sql.="\n\n\n";
    echo " OK <br/><br/>" . "";
  }
} catch (Exception $e) {
  var_dump($e->getMessage());
  return false;
 }

    return $this->saveFile($sql, $outputDir);
  }

  /* Save SQL to file @param string $sql */

  protected function saveFile(&$sql, $outputDir = '.') {
    if (!$sql)
      return false;

    try {
      $handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
      fwrite($handle, $sql);
      fclose($handle);
    } catch (Exception $e) {
      var_dump($e->getMessage());
      return false;
    }
    return true;
  }

}
?>

#12


0  

for using Cron Job, below is the php function

对于使用Cron作业,下面是php函数

public function runback() {

    $filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';

    /*
     *  db backup
     */

    $command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass charls_gwh > $filename";
    system($command);
    if ($command == '') {
        /* no output is good */
        echo 'not done';
    } else {
       /* we have something to log the output here */
        echo 'done';
    }
}

There should not be any space between -u and username also no space between -p and password. CRON JOB command to run this script every sunday 8.30 am:

在-u和用户名之间不应该有空格,在-p和密码之间也不应该有空格。CRON作业命令在每周日早上8:30运行此脚本:

>> crontab -e

30 8 * * 7 curl -k https://www.websitename.com/takebackup

#1


47  

While you can execute backup commands from PHP, they don't really have anything to do with PHP. It's all about MySQL.

虽然您可以执行来自PHP的备份命令,但它们实际上与PHP没有任何关系。这是关于MySQL。

I'd suggest using the mysqldump utility to back up your database. The documentation can be found here : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html.

我建议使用mysqldump实用程序来备份数据库。文档可以在这里找到:http://dev.sqmyl.com/doc/refman/5.1 /en/mysqldump.html。

The basic usage of mysqldump is

mysqldump的基本用法是

mysqldump -u user_name -p name-of-database >file_to_write_to.sql

You can then restore the backup with a command like

然后,您可以使用类似的命令来恢复备份

mysql -u user_name -p <file_to_read_from.sql

Do you have access to cron? I'd suggest making a PHP script that runs mysqldump as a cron job. That would be something like

你能接触到克伦吗?我建议编写一个PHP脚本,将mysqldump作为cron作业运行。就像这样

<?php

$filename='database_backup_'.date('G_a_m_d_y').'.sql';

$result=exec('mysqldump database_name --password=your_pass --user=root --single-transaction >/var/backups/'.$filename,$output);

if($output==''){/* no output is good */}
else {/* we have something to log the output here*/}

If mysqldump is not available, the article describes another method, using the SELECT INTO OUTFILE and LOAD DATA INFILE commands. The only connection to PHP is that you're using PHP to connect to the database and execute the SQL commands. You could also do this from the command line MySQL program, the MySQL monitor.

如果mysqldump不可用,本文将使用SELECT INTO OUTFILE和LOAD DATA INFILE命令描述另一种方法。与PHP的唯一连接是使用PHP连接数据库并执行SQL命令。你也可以从命令行MySQL程序,MySQL监视器。

It's pretty simple, you're writing an SQL file with one command, and loading/executing it when it's time to restore.

这非常简单,您正在编写一个SQL文件,其中只有一个命令,并在恢复时加载/执行它。

You can find the docs for select into outfile here (just search the page for outfile). LOAD DATA INFILE is essentially the reverse of this. See here for the docs.

您可以在这里找到select into outfile的文档(只需在页面中搜索outfile)。加载数据文件本质上是相反的。看这里的文档。

#2


19  

Backup DB using PHP

example:

例子:

EXPORT_TABLES("localhost","user","pass","db_name" );

code:

代码:

<?php
// https://github.com/tazotodua/useful-php-scripts 
                //optional: 5th parameter - backup specific tables only: array("mytable1","mytable2",...)   
                //optional: 6th parameter - backup filename
                // NOTE! to adequatelly replace strings in DB, MUST READ:   goo.gl/nCwWsS

function EXPORT_TABLES($host,$user,$pass,$name,       $tables=false, $backup_name=false){ 
    set_time_limit(3000); $mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES'); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; }   if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); } 
    $content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8 */;\r\n--\r\n-- Database: `".$name."`\r\n--\r\n\r\n\r\n";
    foreach($target_tables as $table){
        if (empty($table)){ continue; } 
        $result = $mysqli->query('SELECT * FROM `'.$table.'`');     $fields_amount=$result->field_count;  $rows_num=$mysqli->affected_rows;     $res = $mysqli->query('SHOW CREATE TABLE '.$table); $TableMLine=$res->fetch_row(); 
        $content .= "\n\n".$TableMLine[1].";\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) {
            while($row = $result->fetch_row())  { //when started (and every after 100 command cycle):
                if ($st_counter%100 == 0 || $st_counter == 0 )  {$content .= "\nINSERT INTO ".$table." VALUES";}
                    $content .= "\n(";    for($j=0; $j<$fields_amount; $j++){ $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); if (isset($row[$j])){$content .= '"'.$row[$j].'"' ;}  else{$content .= '""';}     if ($j<($fields_amount-1)){$content.= ',';}   }        $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {$content .= ";";} else {$content .= ",";} $st_counter=$st_counter+1;
            }
        } $content .="\n\n\n";
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    $backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
    ob_get_clean(); header('Content-Type: application/octet-stream');   header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"".$backup_name."\"");
    echo $content; exit;
}      //see import.php too
?>

//updated per @Mohammad's advise.

/ /更新/ @Mohammad的建议。

#3


11  

Here is a pure PHP class to perform backups on MySQL databases not using mysqldump or mysql commands: Backing up MySQL databases with pure PHP

这里有一个纯PHP类,可以在不使用mysqldump或MySQL命令的MySQL数据库上执行备份:使用纯PHP备份MySQL数据库

#4


5  

Based on the good solution that provided by tazo todua, I've made some of changes since mysql_connect has deprecated and not supported in new php version. I've used mysqli_connect instead and increased the performance of inserting values to the database:

基于tazo todua提供的良好解决方案,我已经做了一些更改,因为mysql_connect已经被弃用,并且在新的php版本中不受支持。我使用了sqmyli_connect,并提高了向数据库插入值的性能:

<?php

/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/


//MySQL server and database
$dbhost = 'localhost';
$dbuser = 'my_user';
$dbpass = 'my_pwd';
$dbname = 'database_name';
$tables = '*';

//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);

//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
    $link = mysqli_connect($host,$user,$pass, $dbname);

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    }

    mysqli_query($link, "SET NAMES 'utf8'");

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($link, 'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($link, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;

        //Over tables
        for ($i = 0; $i < $num_fields; $i++) 
        {   //Over rows
            while($row = mysqli_fetch_row($result))
            {   
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }

                //Over fields
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }

                if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }
                ++$counter;
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
    $handle = fopen($fileName,'w+');
    fwrite($handle,$return);
    if(fclose($handle)){
        echo "Done, the file name is: ".$fileName;
        exit; 
    }
}

#5


5  

If you want to backup a database from php script you could use a class for example lets call it MySQL. This class will use PDO (build in php class which will handle the connection to the database). This class could look like this:

如果你想从php脚本中备份一个数据库,你可以使用一个类,比如我们叫它MySQL。这个类将使用PDO(在php类中构建,用于处理与数据库的连接)。这个类可以是这样的:

<?php /*defined in your exampleconfig.php*/
define('DBUSER','root');
define('DBPASS','');
define('SERVERHOST','localhost');
?>

<?php /*defined in examplemyclass.php*/
    class MySql{
        private $dbc;
        private $user;
        private $pass;
        private $dbname;
        private $host;

        function __construct($host="localhost", $dbname="your_databse_name_here", $user="your_username", $pass="your_password"){
            $this->user = $user;
            $this->pass = $pass;
            $this->dbname = $dbname;
            $this->host = $host;
            $opt = array(
               PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
               PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
            );
            try{
                $this->dbc = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $user, $pass, $opt);
            }
            catch(PDOException $e){
                 echo $e->getMessage();
                 echo "There was a problem with connection to db check credenctials";
            }
        } /*end function*/


        public function backup_tables($tables = '*'){  /* backup the db OR just a table */
            $host=$this->host;
            $user=$this->user;
            $pass=$this->pass;
            $dbname=$this->dbname;
            $data = "";
            //get all of the tables
            if($tables == '*')
            {
                $tables = array();
                $result = $this->dbc->prepare('SHOW TABLES'); 
                $result->execute();                         
                while($row = $result->fetch(PDO::FETCH_NUM)) 
                { 
                    $tables[] = $row[0]; 
                }
            }
            else
            {
                $tables = is_array($tables) ? $tables : explode(',',$tables);
            }
            //cycle through
            foreach($tables as $table)
            {
                $resultcount = $this->dbc->prepare('SELECT count(*) FROM '.$table);
                $resultcount->execute();
                $num_fields = $resultcount->fetch(PDO::FETCH_NUM);
                $num_fields = $num_fields[0];

                $result = $this->dbc->prepare('SELECT * FROM '.$table);
                $result->execute();
                $data.= 'DROP TABLE '.$table.';';

                $result2 = $this->dbc->prepare('SHOW CREATE TABLE '.$table);    
                $result2->execute();                            
                $row2 = $result2->fetch(PDO::FETCH_NUM);
                $data.= "\n\n".$row2[1].";\n\n";

                for ($i = 0; $i < $num_fields; $i++) 
                {
                    while($row = $result->fetch(PDO::FETCH_NUM))
                    { 
                        $data.= 'INSERT INTO '.$table.' VALUES(';
                        for($j=0; $j<$num_fields; $j++) 
                        {
                            $row[$j] = addslashes($row[$j]); 
                            $row[$j] = str_replace("\n","\\n",$row[$j]);
                            if (isset($row[$j])) { $data.= '"'.$row[$j].'"' ; } else { $data.= '""'; }
                            if ($j<($num_fields-1)) { $data.= ','; }
                        }
                        $data.= ");\n";
                    }
                }
                $data.="\n\n\n";
            }
            //save filename
            $filename = 'db-backup-'.time().'-'.(implode(",",$tables)).'.sql';
            $this->writeUTF8filename($filename,$data);
        /*USE EXAMPLE
           $connection = new MySql(SERVERHOST,"your_db_name",DBUSER, DBPASS);
           $connection->backup_tables(); //OR backup_tables("posts");
           $connection->closeConnection();
        */
        } /*end function*/


        private function writeUTF8filename($filenamename,$content){  /* save as utf8 encoding */
            $f=fopen($filenamename,"w+"); 
            # Now UTF-8 - Add byte order mark 
            fwrite($f, pack("CCC",0xef,0xbb,0xbf)); 
            fwrite($f,$content); 
            fclose($f); 
        /*USE EXAMPLE this is only used by public function above...
            $this->writeUTF8filename($filename,$data);
        */
        } /*end function*/


        public function recoverDB($file_to_load){
            echo "write some code to load and proccedd .sql file in here ...";
        /*USE EXAMPLE this is only used by public function above...
            recoverDB("some_buck_up_file.sql");
        */
        } /*end function*/


        public function closeConnection(){
            $this->dbc = null;
        //EXAMPLE OF USE 
        /*$connection->closeConnection();*/
        }/*end function*/


    } /*END OF CLASS*/
    ?>

Now you could simply use this in your backup.php:

现在你可以在你的备份中使用这个:

include ('config.php');
include ('myclass.php');
    $connection = new MySql(SERVERHOST,"your_databse_name_here",DBUSER, DBPASS);
    $connection->backup_tables(); /*Save all tables and it values in selected database*/
    $connection->backup_tables("post_table"); /*Saves only table name posts_table from selected database*/
    $connection->closeConnection();

Which means that visiting this page will result in backing up your file... of course it doesn't have to be that way :) you can call this method on every post to your database to be up to date all the time, however, I would recommend to write it to one file at all the time instead of creating new files with time()... as it is above.

这意味着访问这个页面将导致备份您的文件……当然,这并不一定是这样的:)你可以在你的数据库上的每一个帖子上都调用这个方法,一直到现在为止,但是,我建议你一直把它写到一个文件,而不是用时间()来创建新的文件……因为它是。

Hope it helps and good luck ! :>

祝你好运!:>

#6


1  

I would recommend using mysqldump and from php use the system command as suggested in the article you found.

我建议使用mysqldump,从php使用system命令,如您找到的文章中所建议的那样。

#7


1  

Here is php file which will let you create/download your database backup in efficient manner This single file with on page security functionality. only you have to download that file place in your public folder or project folder and call it through browser.

这里是php文件,它将允许您以高效的方式创建/下载您的数据库备份,并在页面安全功能上使用该文件。只需要下载公共文件夹或项目文件夹中的文件位置并通过浏览器调用即可。

Download URL- https://github.com/vkt005/php-mysql-db-backup

下载URL https://github.com/vkt005/php-mysql-db-backup

#8


1  

I also had a situation and i could'nt find a tool to satisfy me. So for the sake of backup/restore mysql data from PHP i have made a program that can compress the data into a zip file that you can download. Later you can upload and restore full database. You can find it in my Github page https://github.com/JoshyFrancis/mysql_backup_restore_php

我也有过这样的情况,我找不到让我满意的工具。为了从PHP中备份/恢复mysql数据,我做了一个程序,可以将数据压缩到一个zip文件中,您可以下载。稍后您可以上传和恢复完整的数据库。您可以在我的Github页面https://github.com/JoshyFrancis/mysql_backup_restore_php中找到它。

#9


1  

Take a look here! It is a native solution written in php. You won't need to exec mysqldump, or cope with incomplete scripts. This is a full mysqldump clone, without dependencies, output compression and sane defaults.

看一看这里!它是用php编写的本地解决方案。您不需要执行mysqldump,或者处理不完整的脚本。这是一个完整的mysqldump克隆,没有依赖项、输出压缩和健全的默认值。

Out of the box, mysqldump-php supports backing up table structures, the data itself, views, triggers and events.

在开箱即用的情况下,mysqldump-php支持备份表结构、数据本身、视图、触发器和事件。

MySQLDump-PHP is the only library that supports:

MySQLDump-PHP是唯一支持的库:

  • output binary blobs as hex.
  • 输出二进制blobs为十六进制。
  • resolves view dependencies (using Stand-In tables).
  • 解析视图依赖项(使用替代表)。
  • output compared against original mysqldump. Linked to travis-ci testing system (testing from php 5.3 to 7.1 & hhvm)
  • 输出与原始mysqldump的比较。连接到travi -ci测试系统(从php 5.3到7.1和hhvm测试)
  • dumps stored procedures.
  • 转储文件存储过程。
  • dumps events.
  • 转储事件。
  • does extended-insert and/or complete-insert.
  • extended-insert和/或complete-insert。
  • supports virtual columns from MySQL 5.7.
  • 支持来自MySQL 5.7的虚拟列。

You can install it using composer, or just download the php file, and it is as easy as doing:

您可以使用composer安装它,也可以下载php文件,操作简单:

use Ifsnop\Mysqldump as IMysqldump;

try {
    $dump = new IMysqldump\Mysqldump('database', 'username', 'password');
    $dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
    echo 'mysqldump-php error: ' . $e->getMessage();
}

All the options are explained at the github page, but more or less are auto-explicative:

所有选项都在github页面上进行了解释,但或多或少都是自动解释的:

$dumpSettingsDefault = array(
    'include-tables' => array(),
    'exclude-tables' => array(),
    'compress' => Mysqldump::NONE,
    'init_commands' => array(),
    'no-data' => array(),
    'reset-auto-increment' => false,
    'add-drop-database' => false,
    'add-drop-table' => false,
    'add-drop-trigger' => true,
    'add-locks' => true,
    'complete-insert' => false,
    'databases' => false,
    'default-character-set' => Mysqldump::UTF8,
    'disable-keys' => true,
    'extended-insert' => true,
    'events' => false,
    'hex-blob' => true, /* faster than escaped content */
    'net_buffer_length' => self::MAXLINESIZE,
    'no-autocommit' => true,
    'no-create-info' => false,
    'lock-tables' => true,
    'routines' => false,
    'single-transaction' => true,
    'skip-triggers' => false,
    'skip-tz-utc' => false,
    'skip-comments' => false,
    'skip-dump-date' => false,
    'skip-definer' => false,
    'where' => '',
    /* deprecated */
    'disable-foreign-keys-check' => true
);

#10


0  

@tazo todua's answer above

@tazo todua上面的回答

Although I've up-voted the answer above, since it was the only one working solution with 'pure' PHP implementation that did not produce 0 length files, and the files look fine at first look, however, note that it failed at some FOREIGN KEYS when I tried to import back my database from the backup file.

尽管我up-voted上面的答案,因为它是唯一一个与“纯”PHP实现解决方案合作没有产生0长度文件,和这些文件看起来好乍一看,然而,请注意,它失败的一些外键当我试图导入数据库的备份文件。

Solutions based on mysqldump in PHP are much safer to use.

在PHP中使用基于mysqldump的解决方案要安全得多。

#11


0  

Solution to take backup of your Database in "dbBackup" Folder / Directory

在“dbBackup”文件夹/目录中备份数据库的解决方案

<?php
error_reporting(E_ALL);

/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", '');
define("DB_NAME", 'YOUR_DATABASE _NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder / Directory Name
define("TABLES", '*');

/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status . " - By Irshad Khan";

/* The Backup_Database class */

class Backup_Database {
/* Host where database is located  */

  var $host = 'localhost';
  var $username = 'root';
  var $passwd = '';
  var $dbName = 'YOUR_DATABASE _NAME';
  var $charset = '';

  /* Constructor initializes database */

  function Backup_Database($host, $username, $passwd, $dbName, $charset = 'utf8') {
    $this->host = $host;
    $this->username = $username;
    $this->passwd = $passwd;
    $this->dbName = $dbName;
    $this->charset = $charset;
    $this->initializeDatabase();
  }

  protected function initializeDatabase() {
    $conn = @mysql_connect($this->host, $this->username, $this->passwd); // Ik Added @ to Hide PDO Error Message
    mysql_select_db($this->dbName, $conn);
    if (!mysql_set_charset($this->charset, $conn)) {
      mysql_query('SET NAMES ' . $this->charset);
    }
  }

  /* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables  */

  public function backupTables($tables = '*', $outputDir = '.') {
    try {
      /* Tables to export  */
      if ($tables == '*') {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while ($row = mysql_fetch_row($result)) {
          $tables[] = $row[0];
        }
      } else {
        $tables = is_array($tables) ? $tables : explode(',', $tables);
      }

      $sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
      $sql .= 'USE ' . $this->dbName . ";\n\n";

  /* Iterate tables */
  foreach ($tables as $table) {
    echo "Backing up " . $table . " table...";

    $result = mysql_query('SELECT * FROM ' . $table);
    $numFields = mysql_num_fields($result);

    $sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
    $sql.= "\n\n" . $row2[1] . ";\n\n";

    for ($i = 0; $i < $numFields; $i++) {
      while ($row = mysql_fetch_row($result)) {
        $sql .= 'INSERT INTO ' . $table . ' VALUES(';
        for ($j = 0; $j < $numFields; $j++) {
          $row[$j] = addslashes($row[$j]);
          // $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
          if (isset($row[$j])) {
            $sql .= '"' . $row[$j] . '"';
          } else {
            $sql.= '""';
          }
          if ($j < ($numFields - 1)) {
            $sql .= ',';
          }
        }
        $sql.= ");\n";
      }
    }
    $sql.="\n\n\n";
    echo " OK <br/><br/>" . "";
  }
} catch (Exception $e) {
  var_dump($e->getMessage());
  return false;
 }

    return $this->saveFile($sql, $outputDir);
  }

  /* Save SQL to file @param string $sql */

  protected function saveFile(&$sql, $outputDir = '.') {
    if (!$sql)
      return false;

    try {
      $handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
      fwrite($handle, $sql);
      fclose($handle);
    } catch (Exception $e) {
      var_dump($e->getMessage());
      return false;
    }
    return true;
  }

}
?>

#12


0  

for using Cron Job, below is the php function

对于使用Cron作业,下面是php函数

public function runback() {

    $filename = '/var/www/html/local/storage/stores/database_backup_' . date("Y-m-d-H-i-s") . '.sql';

    /*
     *  db backup
     */

    $command = "mysqldump --single-transaction -h $dbhost -u$dbuser -p$dbpass charls_gwh > $filename";
    system($command);
    if ($command == '') {
        /* no output is good */
        echo 'not done';
    } else {
       /* we have something to log the output here */
        echo 'done';
    }
}

There should not be any space between -u and username also no space between -p and password. CRON JOB command to run this script every sunday 8.30 am:

在-u和用户名之间不应该有空格,在-p和密码之间也不应该有空格。CRON作业命令在每周日早上8:30运行此脚本:

>> crontab -e

30 8 * * 7 curl -k https://www.websitename.com/takebackup