Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to take Backup of MYSQL Database file and upload it on Dropbox Account?

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 950
    Comment on it

    Hello,

    I am sharing here how we can take backup of our Project mysql database file and upload it in our Dropbox Account. Advantage using this feature is we can store our database backup in our Dropbox account daily. We can set our script as a cron job working in every suitable time.

    Here is the code to take backup of database and upload it in server and dropbox both.

    backupTables('localhost', 'root', 'password', 'database_name');
    
    /* backup the db OR just a table */
    
    function backupTables($host, $user, $pass, $name, $tables = '*') {
    
        $link = mysql_connect($host, $user, $pass);
        mysql_select_db($name, $link);
    
        //Get all of the tables
        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);
        }
    
        //cycle through
        foreach ($tables as $table) {
            $result = mysql_query('SELECT * FROM ' . $table);
            $num_fields = mysql_num_fields($result);
    
            $return.= 'DROP TABLE ' . $table . ';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
            $return.= "\n\n" . $row2[1] . ";\n\n";
    
            for ($i = 0; $i < $num_fields; $i++) {
                while ($row = mysql_fetch_row($result)) {
                    $return.= 'INSERT INTO ' . $table . ' VALUES(';
                    for ($j = 0; $j < $num_fields; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                        if (isset($row[$j])) {
                            $return.= '"' . $row[$j] . '"';
                        } else {
                            $return.= '""';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return.= ',';
                        }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }
    
        //save file
        $file = 'db_backups/Ongeza-' . date("d-m-Y") . '-' . '.sql'; // (md5(implode(',', $tables))) .
        $handle = fopen($file, 'w+');
        fwrite($handle, $return);
        fclose($handle);
        chmod($file, 0755);
        echo "SUCCESS of File uploading";
        echo "\r\n";
        importFileToDropBox($file);
    }
    
     // Import backedup sql file to Dropbox.
    function importFileToDropBox($file) {
        error_reporting(E_ALL);
        require_once("DropboxClient.php");
        // you have to create an app at https://www.dropbox.com/developers/apps and enter details below:
        $dropbox = new DropboxClient(array(
            'app_key' => "YOUR APP KEY",
            'app_secret' => "YOUR APP SECRET KEY",
            'app_full_access' => FALSE,
                ), 'en');
    
        handle_dropbox_auth($dropbox);
        echo "<pre>";
        echo "\r\n\r\n<b>Uploading $file:</b>\r\n";
    //    $meta = $dropbox->UploadFile($_FILES["the_upload"]["tmp_name"], $upload_name);
        $meta = $dropbox->UploadFile($file);
        print_r($meta);
        echo "\r\n done!";
        echo "</pre>";
    
        $todayDate = date("d-m-Y");
        $lastDate = date("t-m-Y");
        $split = explode('-', $lastDate);
        $lastDay = $split[0];
    
        // Delete files from Dropbox at the last date of month except the last day file
        if ($todayDate === $lastDate) {
            for ($day = $lastDay - 1; $day >= 1; $day--) {
                $fileName = "Ongeza-" . $day . "-" . date("m-Y") . "-.sql";
                $dropbox->Delete("/$fileName");
                unlink("db_backups/$fileName");
                //echo $fileName . " file is deleted<br />";
            }
        }
    }
    
    // store_token, load_token, delete_token are SAMPLE functions! please replace with your own!
    function store_token($token, $name) {
        file_put_contents("tokens/$name.token", serialize($token));
    }
    
    function load_token($name) {
        if (!file_exists("tokens/$name.token")) {
            return null;
        }
        return @unserialize(@file_get_contents("tokens/$name.token"));
    }
    
    function delete_token($name) {
        @unlink("tokens/$name.token");
    }
    
    // ================================================================================
    
    function handle_dropbox_auth($dropbox) {
        // first try to load existing access token
        $access_token = load_token("access");
        if (!empty($access_token)) {
            $dropbox->SetAccessToken($access_token);
        } elseif (!empty($_GET['auth_callback'])) {
            // Are we coming from dropbox's auth page?
            // if yes, then load our previosly created request token
            $request_token = load_token($_GET['oauth_token']);
            if (empty($request_token)) {
                die('Request token not found!');
            }
    
            // Get & store access token, the request token is not needed anymore
            $access_token = $dropbox->GetAccessToken($request_token);
            store_token($access_token, "access");
            delete_token($_GET['oauth_token']);
        }
    
        // checks if access token is required
        if (!$dropbox->IsAuthorized()) {
            // redirect user to dropbox auth page
            $return_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . "?auth_callback=1";
            $auth_url = $dropbox->BuildAuthorizeUrl($return_url);
            $request_token = $dropbox->GetRequestToken();
            echo "<pre>";
            print_r($request_token);
    
            store_token($request_token, $request_token['t']);
            die("Authentication required. <a href='$auth_url'>Click here.</a>");
        }
    }
    

    importFileToDropBox() is a function which connects with DropBox API and upload file in Dropbox with parameter $file

    To download Dropbox API Please visit https://www.dropbox.com/developers/core/sdks/php Here we can find Sdk for php, similarly we can download Sdk for Android, iOS, Python, Java and Ruby. To implement Dropbox API we first need to create our account in dropbox.com and then create App. After creating an App we can find Secret Key and APP Key.

    for developers guide Please take a look http://dropbox.github.io/dropbox-sdk-php/api-docs/v1.1.x/

    Enjoy the code.
    Thanks

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: