Backup Website and Database using PHP exec()

PHP exec() function is usually disabled in most shared web hosting servers because of security reasons, but if your host allows this or you are on VPS or dedicated server, you should be able to use exec commands to backup your website or mysql database. Before you start, using code below check whether exec is enabled, if it fails you should ask your host to make sure it is even allowed!
PHP
  • 1
  • 2
  • 3
if(function_exists('exec')) { echo "enabled"; }

Back-up folder

The following exec command should back-up your website folder.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
$folder_to_backup = "/path/to/folder"; $backup_folder = "/path/to/backup/folder"; exec("tar -cvf $backup_folder/backupfile.gz $folder_to_backup/* --exclude='$folder_to_backup/*.gz'", $results, $result_value); if ($result_value == 0){ echo "The archive has been successfully created!"; } else { echo "Archive creation failed!"; }

Back-up MySql database

To back-up your MySql database, simply copy/paste this code in a PHP file, change to your MySql credentials and run.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
$mysql_host = "localhost"; $mysql_user = "username"; $mysql_pass = "password"; $mysql_database = "my_database"; $backup_folder = "/path/to/backup/folder"; exec("mysqldump -h $mysql_host -u $mysql_user -p$mysql_pass $mysql_database > $backup_folder/my-sql-backup.sql", $results, $result_value); if ($result_value == 0){ echo "The MySql backup successfully created!"; } else { echo "MySql backup creation failed!"; }
    New question is currently disabled!