Thursday, 26 May 2011

PHP - Auto get Backup Database from Server Using ssh2


Hello,

This is function auto get backup database file from server using ssh2:

  1. Install ssh2 php module:
    • sudo apt-get update
    • sudo apt-get install php5-mcrypt libssh2-php
      • Check enable modules:
        • php -m | grep mcrypt
        • php -m | grep ssh2
      • Enable modules:
        • sudo php5enmod mcrypt
        • sudo php5enmod ssh2
      • Module ssh2 ini file doesn't exist:
        • echo "extension=ssh2.so" > /etc/php5/mods-available/ssh2.ini
      • service php5-fpm restart
  2. Create cron backup database from you server:
    • mysqldump -uroot -ppassword your-database | gzip -9 > /home/web/backup/`date +%y%m%d`-your-database.sql.gz
  3. Create cron get backup database file from your PC:
    • $host = 'your-ip-address'; //
      $port = 22; //default: 22
      $username = "root";
      $password = "your-password";

      //target want to get from Server
      $fileNameGet = '/home/web/backup/' . date('ymd', time()) . '-your-database.sql.gz';

      //target want to store backup file from your computer
      $fileNameSave = '/home/shin/Desktop/Data/Backup/' . date('ymd', time()) . '-your-database.sql.gz';

      $connection = ssh2_connect($host, $port);
      // use any of the ssh2_auth_* methods
      ssh2_auth_password($connection, $username, $password);
      $sftp = ssh2_sftp($connection);

      if (file_exists("ssh2.sftp://$sftp/" . $fileNameGet)) {
          ssh2_scp_recv($connection, $fileNameGet, $fileNameSave);
      }
  4. Done!

Good luck!

No comments:

Post a Comment