Automatic cPanel backup (domain & MySQL) with cron & PHP

tastaram

Registered
Mar 19, 2009
1
0
51
OK, so I posed the question, and I found the answer. (Of course I had to find it myself, I just don't have people who regularly read my posts and do research for me!)

The situation is this: I use cPanel on my web hosting server. I use the cPanel backup tool to regularly backup my home directory (includes my web files, mail, etc), and my MySQL databases. I love the fact that you can use it to backup to a remote FTP server, and I do that on a fairly regular basis.

The major drawback is that you have to remember/schedule to perform this backup manually. This becomes especially difficult if you have multiple cPanel accounts. It would be amazing if you could just schedule the cPanel backup to run at regular intervals, perhaps with cron. Well, although there's no option for that in cPanel, the script below will allow you to do exactly that!

This backup script includes SSL support. This isn't necessary if you run the script on the server for which you're generating the backup; but the SSL support is very important if you're running the script somewhere else to connect to your cPanel hosting account.
<?php

// PHP script to allow periodic cPanel backups automatically, optionally to a remote FTP server.
// This script contains passwords. KEEP ACCESS TO THIS FILE SECURE! (place it in your home dir, not /www/)

// ********* THE FOLLOWING ITEMS NEED TO BE CONFIGURED *********

// Info required for cPanel access
$cpuser = "username"; // Username used to login to CPanel
$cppass = "password"; // Password used to login to CPanel
$domain = "example.com"; // Domain name where CPanel is run
$skin = "x"; // Set to cPanel skin you use (script won't work if it doesn't match). Most people run the default x theme

// Info required for FTP host
$ftpuser = "ftpusername"; // Username for FTP account
$ftppass = "ftppassword"; // Password for FTP account
$ftphost = "ftp.example.com"; // Full hostname or IP address for FTP host
$ftpmode = "ftp"; // FTP mode ("ftp" for active, "passiveftp" for passive)

// Notification information
$notifyemail = "[email protected]"; // Email address to send results

// Secure or non-secure mode
$secure = 0; // Set to 1 for SSL (requires SSL support), otherwise will use standard HTTP

// Set to 1 to have web page result appear in your cron log
$debug = 0;

// *********** NO CONFIGURATION ITEMS BELOW THIS LINE *********

if ($secure) {
$url = "ssl://".$domain;
$port = 2083;
} else {
$url = $domain;
$port = 2082;
}

$socket = fsockopen($url,$port);
if (!$socket) { echo "Failed to open socket connection… Bailing out!\n"; exit; }

// Encode authentication string
$authstr = $cpuser.":".$cppass;
$pass = base64_encode($authstr);

$params = "dest=$ftpmode&email=$notifyemail&server=$ftphost&user=$ftpuser&pass=$ftppass&submit=Generate Backup";

// Make POST to cPanel
fputs($socket,"POST /frontend/".$skin."/backup/dofullbackup.html?".$params." HTTP/1.0\r\n");
fputs($socket,"Host: $domain\r\n");
fputs($socket,"Authorization: Basic $pass\r\n");
fputs($socket,"Connection: Close\r\n");
fputs($socket,"\r\n");

// Grab response even if we don't do anything with it.
while (!feof($socket)) {
$response = fgets($socket,4096);
if ($debug) echo $response;
}

fclose($socket);

?>
source:http://deepdictionary.com/
 

cPanelDavidG

Technical Product Specialist
Nov 29, 2006
11,216
11
313
Houston, TX
cPanel Access Level
Root Administrator
If you're looking to improve this script, you can connect to the XML API using the cPanel user credentials over port 2082 or port 2083. Then call the following API1 function:

HTML:
<cpanel Fileman="fullbackup($FORM{'dest'},$FORM{'server'},$FORM{'user'},$FORM{'pass'},$FORM{'email'},$FORM{'port'},$FORM{'rdir'})">
If you need help with this API function, let me know. The XML API itself is documented at:

http://www.cPanel.net/plugins/xmlapi
 

Dellow

Member
Feb 27, 2003
5
0
151
If you're looking to improve this script, you can connect to the XML API using the cPanel user credentials over port 2082 or port 2083. Then call the following API1 function:

HTML:
<cpanel Fileman="fullbackup($FORM{'dest'},$FORM{'server'},$FORM{'user'},$FORM{'pass'},$FORM{'email'},$FORM{'port'},$FORM{'rdir'})">
If you need help with this API function, let me know. The XML API itself is documented at:

XML and JSON APIs

i really need it to save the files on remote server in same files name. (fixed name) or delete yesterday's file.

any idea?

Regards,
 

jrianto

Active Member
Jun 9, 2008
44
0
56
You can delete yesterday's file through a script that connects to your FTP server. So add a function on the backup script and run it on cron, when it detects there is two backup files residing on the FTP server, simply remove the older one.
 

tyankee

Registered
Apr 9, 2010
1
0
51
i've looked everywhere for this answer but can't find it.. btw i love this script.. i've been using it for about a year i think and it works great backing up to another server BUT i can't seem to get it to work backing up a domain to it's own server.. the job runs fine, completes with no errors, even lists the file name that it created but i can't find that filename anywhere on the server – not in the home or www directory – not anywhere.. i've tried this now on 4 different websites and i get the same results.. any ideas? or does it just not work if you try to backup on the same server.
 
Jun 13, 2011
6
0
51
It turns out a few things have changed since the initial script was written to solve this problem. I've written up a fixed version of the script together with a couple of changes to make it easier to use it to backup multiple sites through cPanel and a brief synopsis of how to get the backups to feed through into a local FTP server. The write up is /http://mikehigginbottom.com/content/automatic-cpanel-backups.
 
Jun 13, 2011
6
0
51
Implemented this updated version. Whats the 2nd site for? will it back up two websites??
Correct. The code as written will backup two sites. You can add more sites by adding extra entries to the array like so:

$sites['2']['domaintobackup'] = "example.com";
$sites['2']['cpaneluser'] = "user2";
$sites['2']['cpanelpass'] = "pass2";
$sites['2']['cpanelskin'] = "x3Bronze";

and so on.
 

rahuldas14

Member
Nov 24, 2009
7
0
51
doesnt work...I got a mail which said:

Could not open input file: /home/youraccount/fullbackup.php

Can u help me?
 

tomdchi

Well-Known Member
Feb 24, 2008
138
2
68
Atlanta, GA
cPanel Access Level
DataCenter Provider
This is the script I use to backup accounts to another server.
Requires xmlapi-php available at https://github.com/CpanelInc/xmlapi-php
This will:
Backup ALL accounts on the server.
Use API to get list of accounts.

Note that the argument in the code below "\\" is the destination ftp directory.


PHP:
<?php
require ('xmlapi.php');

class cpbackup
{
	public function backup($source_server_ip, $server_password, $ftp_domain, $ftp_acct, $ftp_pass, $notify_email)
	{
		$xmlapi = new xmlapi($source_server_ip);
		$xmlapi->password_auth("root", $server_password);
		$xmlapi->set_port('2087');
		//$xmlapi->set_debug(1);//this setting will put output into the error log in the directory that you are calling script from 
		$xmlapi->set_output('array');
		$userlist = $xmlapi->listaccts();
		foreach ($userlist as $v => $field)
		{
			foreach ($field as $cpuser)
			{
				if (!empty($cpuser['user']))
				{
					$cpanel_account = $cpuser['user'];
					$api_args = array('ftp', $ftp_domain, $ftp_acct, $ftp_pass, $notify_email, 21, "\\");
					$response = $xmlapi->api1_query($cpanel_account, 'Fileman', 'fullbackup', $api_args);
					foreach ($response as $v2)
					{
						$result = $v2['result'];
					}
					if ($result == 1)
					{
						sleep(60);
					}
				}
			}
		}
		return true;
	}
}

$backup = new cpbackup();
$result = $backup->backup('server ip', 'server root password', 'ftp domain', 'ftp acct', 'ftp pass', 'notify email address');


?>

Tom
 

garrettp

Well-Known Member
PartnerNOC
Jun 18, 2004
312
0
166
cPanel Access Level
DataCenter Provider
Not sure why this script is needed when cPanel has a fully-functional full backup via FTP right in the WHM interface?
 

cPanelTristan

Quality Assurance Analyst
Staff member
Oct 2, 2010
7,607
38
248
somewhere over the rainbow
cPanel Access Level
Root Administrator
I do understand the purpose of the original thread, since the original poster only had cPanel access to the machine where automatic backups aren't possible for the end-user to perform. Not certain for the newer script that uses the API and backs up all the accounts on the machine, though.
 

tomdchi

Well-Known Member
Feb 24, 2008
138
2
68
Atlanta, GA
cPanel Access Level
DataCenter Provider
You cannot use the incremental backup option in conjunction with ftp backups through WHM. That is the point of the script-you can have normal incremental backups in WHM and use the script to backup all accounts to another server.
Also in our setup we want to have backups local and remote.
 
Last edited:

garrettp

Well-Known Member
PartnerNOC
Jun 18, 2004
312
0
166
cPanel Access Level
DataCenter Provider
I suppose the script would make sense for incremental and full backs in conjunction, but for local and remote it would be significantly more efficient to just have a postcpbackup hook to copy a local backup via FTP/SCP to the remote storage point.
 

FlexiHost

Member
Aug 10, 2010
11
0
51
Christchurch, New Zealand
cPanel Access Level
Root Administrator
One thing that would be nice, is for hosts that use whmcs for their billing systems, to be able to offer some kind of backup solution through there, I have been hunting high and low for one.

Quite a few users are not that technically up to being able to log into cPanel and create a full backup from there.

Any thoughts as to how that could be done maybe? Some kind of simple click here to generate Backup and email them a download link to get the files perhaps?