Skip to content

Instantly share code, notes, and snippets.

@roelandmoors
Last active September 10, 2023 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roelandmoors/876418162fb1b72efff99ebb8df9ad74 to your computer and use it in GitHub Desktop.
Save roelandmoors/876418162fb1b72efff99ebb8df9ad74 to your computer and use it in GitHub Desktop.
Backup mysql databases to dropbox
<?php
# https://gist.github.com/phuze/755dd1f58fba6849fbf7478e77e2896a
# https://www.dropbox.com/developers/apps/info/i4uphx9x4x2lb3k#settings
$databases = ['db1', 'db2'];
$basepath = '/some/path/backup/';
$app_key = "1234";
$app_secret = '567';
echo "Visit this to get code:\n";
echo "https://www.dropbox.com/oauth2/authorize?token_access_type=offline&response_type=code&client_id=$app_key\n\n";
echo "Run this with the received code:\n";
echo "curl https://api.dropbox.com/oauth2/token -d code=<CODE> -d grant_type=authorization_code -u $app_key:$app_secret\n\n";
echo "Get the refresh token from the response\n\n";
# {
# "access_token": "sl.Blv...",
# "token_type": "bearer",
# "expires_in": 14399,
# "refresh_token": "5TKrf...",
# "scope": "account_info.read",
# "uid": "1234556",
# "account_id": "dbid:4wrwerw4w45wer"
# }
$refreshtoken = "5TKrf...";
$ch = curl_init ('https://api.dropbox.com/oauth2/token');
curl_setopt_array ( $ch, array (
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array (
'grant_type' => 'refresh_token',
'refresh_token' => $refreshtoken
),
CURLOPT_USERPWD => $app_key . ":" . $app_secret
) );
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
$token = $json['access_token'];
foreach ($databases as $dbname) {
$filename=$dbname.'_'.date('YmdHi').'.sql.gz';
$path=$basepath.$filename;
exec("mysqldump $dbname | gzip -c > $path");
$fp = fopen($path, 'rb');
$size = filesize($path);
$ch = curl_init('https://content.dropboxapi.com/2/files/upload');
$headr = array();
$headr[] = 'Authorization: Bearer '.$token;
$headr[] = 'Content-Type: application/octet-stream';
$headr[] = 'Dropbox-API-Arg: {"path":"/Uploads/'.$filename.'","mode":{".tag":"add"}}';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, $size);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$rest = curl_exec($ch);
curl_close($ch);
fclose($fp);
#print_r($rest);
exec("rm $path");
}
echo "\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment