PHP Code, SQL Code, Web

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

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 = "you@example.com"; // 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);

?>

To schedule the script to run regularly, save it as fullbackup.php in your top directory (not /public_html, which would be less secure), and enter a new cron job like the following:


15 2 * * * /usr/local/bin/php /home/youraccount/fullbackup.php 

(Runs every night at 2:15 a.m.)

or


15 2 * * 1 /usr/local/bin/php /home/youraccount/fullbackup.php 

(Runs every Sunday night at 2:15 a.m.)

Share

210 Comments

  1. #! /usr/bin/php -q

  2. Ben – thanks for the updated code, it works perfectly with cPanel 11.25.0.

  3. How to do this script work if my hoster closed fsockopen function?

  4. I could not found out the right location, for the fullbackup.php file.
    "/usr/local/bin/php /home/youraccount/fullbackup.php"
    My Cpanel username is viktor. After the ftp login I see this files:
    .cpanel
    .fantasticodata
    .htpasswds
    .trash
    etc
    mail
    public_ftp
    public_html
    tmp
    www

    Thank you.

  5. Hey , i needed some help. I have a WHM With 1000 domains under it. I want to write a script which can upload the same file to all the domains in one go.

    How do i write the script to access file manager of the CPANEL and upload file ?

    Please help 🙂

    Thanks

  6. Justin, I realize this is been around a while, but you have inspired me to publish a webstore process my team has created. Where did you find this template or did you create it.

  7. Hello,

    I have tried and tried to get this syntax working but to no avail. Here is the error message that is getting e-mail to me by my CRON:

    Warning: fsockopen(): unable to connect to smsn****.ca:2082 (Connection timed out) in /home/smsn****/fullbackup.php on line 39 Failed to open socket connection… Bailing out!

    I am hoping someone can help me out.

    Thanks for looking!
    Stephen

  8. Mathew Anderson

    is it possible to use curl ? for the below ? if so would curl be the better option ?

    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");

  9. Hi

    Is there a way to only download MySQL files rather than an entire backup?

    Where is the 'Generate Backup' API function documented please? I can't find it anywhere?

    Thanks

  10. Hello guys,

    I'm receiving a confirmation email "Full Backup Completed". There's an error "Login incorrect". There's a problem with remote FTP. I don't understand, the FTP info is correct, I've tried other FTP account too, but same error.

    Can you please advise something how to fix this issue?

    Thanks for your time.

  11. i've looked everywhere for this answer but can't find it.. btw i love your 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.

  12. um, so where do I download your script? there is no download link on this blog post.

  13. Hey

    Thanks for this! The only problem is… I can't see the script on this page?
    Have I missed something really obvious, like a "Click here to download the script" link? Or is it supposed to be inline with your blog post? Because I can't see it anywhere :-S

    Thanks

    Ollie

  14. This script has been fantastic! But suddenly it stopped working on ALL of my sites at once. Here's the output. Any ideas?

    /usr/local/bin/php ~/cpanelfullbackup.phpFailed loading /usr/local/Zend/lib/Optimizer-3.3.3/php-5.2.x/ZendOptimizer.so: /usr/local/Zend/lib/Optimizer-3.3.3/php-5.2.x/ZendOptimizer.so: failed to map segment from shared object: Cannot allocate memory

    Warning: fsockopen(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /home/isy/cpanelfullbackup.php on line 35

    Warning: fsockopen(): unable to connect to fakewebsitename.org:2082 (php_network_getaddresses: getaddrinfo failed: Name or service not known) in /home/isy/cpanelfullbackup.php on line 35
    ERROR Failed to open socket connection… Bailing out!

  15. hello sir,
    shall we run the automatic cpanel backup recovery php scripts on localhost.If its possible.

  16. Hello guys,
    Anyone try this script on localhost.i try but i didnot know whether it is working or not..pls give me a solution..

    Thanks in advance.

  17. Thank you for the script.

    Mansi

  18. where can i download this php script – the php code above keeps disappearing before i can copy it ???

  19. Thanks for the great script, one thing i want to ask is is there any method from which after the completion of the backup process we can run a custom script just as cron job.
    I want to initiate my other custom process once the backup is completed.Is it possible?

  20. In the backups section of cPanel you can download each database with a link such as: http://website.com:2082/getsqlbackup/database.sql.gz

    Is there any way to make a php script that will save these files to a particular location, local to the webserver or ftp?

    Cheers mate.

  21. You are really fantastic!
    Thank!

  22. It's useful script, Does it works well nowadays? any updated code available?

  23. @iTechRoom – Yes it does, although I had to edit the code to add FTP port and dir as this seems to be required by more recent versions of cPanel.

    Add the following after $ftpmode on line 18…

    $ftpport = "21";
    $ftpdir = "/";

    And then alter $params on line 48ish to be…

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

  24. Great script! I had problems with this to start with, then realised that the permissions weren't set correctly. I changed the php file to have 755. It then was allowed to execute…

    Works a treat from then on!

  25. Yes, does this script still work good? Or does it have an updated version?

  26. Como fazer backup automático de contas cPanel | Rui Cruz

    […] a este site fácilmente encontrado num motor de busca perto de si e copiar o […]

  27. Hi guys, why would the cron result be something like

    /home/mine/backup-site.php: line 1: ?php: No such file or directory
    /home/mine/backup-site.php: line 3: //: is a directory
    /home/mine/backup-site.php: line 5: //: is a directory
    /home/mine/backup-site.php: line 6: =: command not found
    /home/mine/backup-site.php: line 6: //: is a directory

    Do I need to chmod the file at all, and is that to 755 or something else? Help please.

    Thanks

    GW

  28. Thanks for the cron job help!

  29. I get the below error emailed to me and i have yet to work out why.

    Net::FTP>>> Net::FTP(2.77)
    Net::FTP>>> Exporter(5.58)
    Net::FTP>>> Net::Cmd(2.29)
    Net::FTP>>> IO::Socket::INET(1.31)
    Net::FTP>>> IO::Socket(1.31)
    Net::FTP>>> IO::Handle(1.28)
    Net::FTP: Unexpected EOF on command channel at /usr/local/cpanel/bin/ftpput line 24 Can't call method "login" on an undefined value at /usr/local/cpanel/bin/ftpput line 28.
    ——————————————————–

    Anyone ever solved this? running cPanel Version 11.28.64

  30. managed to fix. One the FTP port is not set and when i set it i put $port as the veriable which is already used in another part of the script.

    I changed to FTPport and then changed the $params to have port=FTPport and this seems to fix the above error and now working.

  31. hello,

    first thanks for the script is very usefull

    i just want to know if is it possible the call the script from another place.

  32. Newbie question: how do you use this? I only have a vague idea of what a script is and I DO NOT KNOW what to do with it.

    Where do I put it?
    How do I run it?

    I tried "how to run a script" in Google but so far got a lot of stuff that assumes a lot of knowledge. Anyone care to explain or can point to a simple guide?

    I'll keep looking in the meantime.

    Thanks

    Dr Paul

  33. After making the changes for FTPPort, FTP Directory, and theme (x3) I got this working. thanks!

  34. Hi Justin cook,

    you are great i was searching for this script finally i get your script its fantastic before i have so many problems i can't get sometimes backup sometimes forget this is the easy way to get backup thanks so much

  35. Thanks Justin, I modified this along with a few other snippets to create an automated way to load backups to the AMAZON S3 Account.

    Clever work, thanks!

    Jared

  36. Hi, plz help me… I am using dest=homedir to store my backups to homedir … can anydby tell me how can i store it in a particular folder…

    have used following but no luck

    dest=home/user/backups
    dest=/home/user/backups

  37. cpanel自动备份教程详解+正解(更正网络流传的错误版本) – CNWP news

    […] update, the well-known cPanel backup script (from Justin Cook or Max Hedroom – one source: Automatic cPanel backup (domain & MySQL) with cron & PHP ) I used for a number of years was no longer […]

  38. Automating your MyBB backup process | MyPureBB

    […] this guide, I'll be focusing on cPanel users. The script we'll be using was created by Justin Cook and I've found it supremely useful in the past.Start off by creating a PHP file titled […]

  39. Mike Higginbottom

    As R3L1C said, the parameters have changed for the automated cPanel backup API. There's an updated version here together with a bit more info about FTP Servers, Passive Mode ports and setting up cron on Windows. Hope it helps.

  40. Prevent Your Site from Being Hacked | HostGator Web Hosting Blog | Gator Crossing

    […] site. b. A clean (pre hack) backup of your site (hopefully, including the latest updates)Here is an easy DIY way to back up your whole site with cPanel.If you use Hostgator then you've already got weekly offsite backups and they will restore […]

  41. I tried this script, and there were a few things that didn't work, probably because it's 4 years old. I updated it and tested it to work with cPanel version 11.30.1 (build 1). Here is the changed script to get it to work:

  42. I tried this script, and there were a few things that didn't work, probably because it's 4 years old. I updated it and tested it to work with cPanel version 11.30.1 (build 1). Here is the changed script to get it to work:

    // 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 = "cpaneluser"; // Username used to login to CPanel
    $cppass = "cpanelpw"; // Password used to login to CPanel
    $domain = "mycpanel.website.com:port"; // Domain name where CPanel is run and the port. I had to put the port here to get it to work.
    $skin = "x3"; // Set to cPanel skin you use (script won't work if it doesn't match). Most people run the default x theme (I was running x3)

    // Info required for FTP host
    $ftpuser = "username"; // Username for FTP account
    $ftppass = "password"; // Password for FTP account
    $ftphost = "website.com"; // Full hostname or IP address for FTP host
    $ftpmode = "ftp"; // FTP mode ("ftp" for active, "passiveftp" for passive)
    $ftpport = "21"; // FTP Port (21 default)
    $ftprdir = "backupdir"; // Backup Directory

    // Notification information
    $notifyemail = "notifyme@website.com"; // Email address to send results

    // Secure or non-secure mode
    $secure = 1; // 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&port=$ftpport&rdir=$ftprdir&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);

  43. Would anyone be able to help me set up the backup on my servers?
    I am willing to create an ftp account and give you access for the scripts to work.

  44. CPanel - Script Backup Automatico 2011 - Blog Xlogic

    […] caso, effettuare dei backup completi automatici.Lo ScriptLo script originale è stato creato da Justin Cook, mentre questa versione è stata modificata opportunamente per lavorare con le versioni più […]

  45. hey guys,

    I created a script that uses the CPanel native API so it's not running based on the webpages and the theme you're using. This should work with every CPanel (assuming it's fairly recent) out there.

    I've also posted a video to show you how to implement it very easily. Let me know what you think:
    http://www.hostliketoast.com/2011/09/how-to-schedule-full-automatic-cpanel-backups-mysql-databases-files-cron/

  46. 用PHP程式自动登录CPANEL « LTcon!

    […] JOB(计划任务)功能定期执行PHP程式实现。PHP程式由Automatic cPanel backup (domain & MySQL) with cron & PHP一文中的PHP数据库备份代码删节得来,删节后代码 […]

  47. Well this script saved me time and money! Thanks man for posting the code!

    I have it on my reseller account in Hostgator and all accounts are backed up every week using this script.

    The only thing that bothers me is that a new client registered for a hosting package copied the script to his account (as I did in every other client) and when it tries to login to the client account it gets an access denied, and I don't know why… User and Pass are correct and everything works like a charm in every other account.

    Here's what I get from the script:

    HTTP/1.1 401 Access Denied Connection: close Set-Cookie: logintheme=cpanel; path=/; HttpOnly; port=2082 Set-Cookie: cprelogin=no; path=/; HttpOnly; port=2082 Set-Cookie: cpsession=j_s2aHJDFTDCYcww1cFyhXHd9nqyeRBhGcx1gVE9NgSnsQhxGdD1N1XpY4mFpY3D; path=/; HttpOnly; port=2082 Server: cpsrvd/11.30.3.5 Content-type: text/html

  48. Great! Thanks for the the script 🙂

  49. HostFeel Web Hosting Blog » Prevent Your Site fron Being Hacked

    […] Here is an easy DIY way to back up your whole site with cPanel. […]

  50. Dont seem to be working for me, Ive tried everything, Dont see no backups in any folders on main account or on my other cpanel account.
    I aint getting any emails or error messeges either.
    Ive tried numorus cron commands and just dont seem to be working. Help please?

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image