-
Requirement lib
- google-api-php-client
- Hzip class.php (Built-in)
- google_drive_func.php (Built-in)
-
Setup Config
- main code in main.php
- Google console $client_email and $private_key
- Backup google drive folder id $parent_file_id
-
Author
- Ting Cheng (showsky)
- showsky@gmail.com
Created
October 26, 2015 09:28
-
-
Save showsky/06f597d5e259e8dd0e19 to your computer and use it in GitHub Desktop.
Backup file to google drive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) { | |
if ($mimeType === NULL) { | |
$mimeType = '*/*'; | |
} | |
$file = new Google_Service_Drive_DriveFile(); | |
$file->setTitle($title); | |
$file->setDescription($description); | |
$file->setMimeType($mimeType); | |
// Set the parent folder. | |
if ($parentId != null) { | |
$parent = new Google_Service_Drive_ParentReference(); | |
$parent->setId($parentId); | |
$file->setParents(array($parent)); | |
} | |
try { | |
$data = file_get_contents($filename); | |
$createdFile = $service->files->insert($file, array( | |
'data' => $data, | |
'mimeType' => $mimeType, | |
'uploadType' => 'multipart' | |
)); | |
// Uncomment the following line to print the File ID | |
// print 'File ID: %s' % $createdFile->getId(); | |
return $createdFile; | |
} catch (Exception $e) { | |
print "An error occurred: " . $e->getMessage() . PHP_EOL; | |
} | |
} | |
function deleteFile($service, $fileId) { | |
try { | |
$service->files->delete($fileId); | |
} catch (Exception $e) { | |
print "An error occurred: " . $e->getMessage(); | |
} | |
} | |
function retrieveAllFiles($service, $query = NULL) { | |
$result = array(); | |
$pageToken = NULL; | |
do { | |
try { | |
$parameters = array(); | |
if ($query != NULL) { | |
$parameters['q'] = $query; | |
} | |
if ($pageToken) { | |
$parameters['pageToken'] = $pageToken; | |
} | |
$files = $service->files->listFiles($parameters); | |
$result = array_merge($result, $files->getItems()); | |
$pageToken = $files->getNextPageToken(); | |
} catch (Exception $e) { | |
print "An error occurred: " . $e->getMessage(); | |
$pageToken = NULL; | |
} | |
} while ($pageToken); | |
return $result; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HZip { | |
/** | |
* Add files and sub-directories in a folder to zip file. | |
* @param string $folder | |
* @param ZipArchive $zipFile | |
* @param int $exclusiveLength Number of text to be exclusived from the file path. | |
*/ | |
private static function folderToZip($folder, &$zipFile, $exclusiveLength) { | |
$handle = opendir($folder); | |
while (false !== $f = readdir($handle)) { | |
if ($f != '.' && $f != '..') { | |
$filePath = "$folder/$f"; | |
// Remove prefix from file path before add to zip. | |
$localPath = substr($filePath, $exclusiveLength); | |
if (is_file($filePath)) { | |
$zipFile->addFile($filePath, $localPath); | |
} elseif (is_dir($filePath)) { | |
// Add sub-directory. | |
$zipFile->addEmptyDir($localPath); | |
self::folderToZip($filePath, $zipFile, $exclusiveLength); | |
} | |
} | |
} | |
closedir($handle); | |
} | |
/** | |
* Zip a folder (include itself). | |
* Usage: | |
* HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip'); | |
* | |
* @param string $sourcePath Path of directory to be zip. | |
* @param string $outZipPath Path of output zip file. | |
*/ | |
public static function zipDir($sourcePath, $outZipPath) | |
{ | |
$pathInfo = pathInfo($sourcePath); | |
$parentPath = $pathInfo['dirname']; | |
$dirName = $pathInfo['basename']; | |
$z = new ZipArchive(); | |
$z->open($outZipPath, ZIPARCHIVE::CREATE); | |
$z->addEmptyDir($dirName); | |
self::folderToZip($sourcePath, $z, strlen("$parentPath/")); | |
$z->close(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php date_default_timezone_set('Asia/Taipei'); | |
include_once 'Hzip.php'; | |
include_once 'google_drive_func.php'; | |
include_once '../third-party/google-api-php-client/src/Google/autoload.php'; | |
/**********************************************************************************************/ | |
$client_email = 'You client email'; | |
$private_key = file_get_contents('You p12 key file'); | |
$parent_file_id = 'You back folder id'; | |
$config = array( | |
array( | |
'source_folder' => '../www/images', | |
'out_filename' => 'images_' . date("Ymd") . '.zip', | |
'regString' => '/images_[0-9]+\.zip/', | |
'backup_time' => 3600 * 60 * 24 * 30,// 30day | |
), | |
array( | |
'source_folder' => (file_exists('/backup/mysql')) ? scandir('/backup/mysql', SCANDIR_SORT_DESCENDING)[0] : NULL, | |
'out_filename' => 'mysql_' . date("Ymd") . '.zip', | |
'regString' => '/mysql_[0-9]+\.zip/', | |
'backup_time' => 3600 * 60 * 24 * 30,// 30day | |
) | |
); | |
/**********************************************************************************************/ | |
function backup($source_folder, $out_filename, $regString, $backup_time) { | |
global $client_email, $private_key, $parent_file_id; | |
if ( ! file_exists($source_folder)) { | |
echo '[Error] File not found: ' . $source_folder . PHP_EOL; | |
return; | |
} | |
// generate image zip file | |
HZip::zipDir($source_folder, $out_filename); | |
echo '1. Generate zip file: ' . $out_filename . PHP_EOL; | |
// init google client | |
$scopes = array(Google_Service_Drive::DRIVE); | |
$credentials = new Google_Auth_AssertionCredentials( | |
$client_email, | |
$scopes, | |
$private_key | |
); | |
$client = new Google_Client(); | |
$client->setAssertionCredentials($credentials); | |
if ($client->getAuth()->isAccessTokenExpired()) { | |
$client->getAuth()->refreshTokenWithAssertion(); | |
} | |
echo '2. Init google client object' . PHP_EOL; | |
// init google drive | |
$service = new Google_Service_Drive($client); | |
// check file | |
$list_files = retrieveAllFiles($service, sprintf('\'%s\' in parents', $parent_file_id)); | |
foreach ($list_files as $value) { | |
if (preg_match($regString, $value->title) && (time() - strtotime($value->createdDate) > $backup_time)) { | |
deleteFile($service, $value->id); | |
echo ' Delete file: ' . $value->title . ' id: ' . $value->id . PHP_EOL; | |
} | |
} | |
echo '3. Check file' . PHP_EOL; | |
// upload file | |
$result = insertFile($service, pathinfo($out_filename)['basename'], NULL, $parent_file_id, NULL, $out_filename); | |
echo '4. Upload file to google drive' . PHP_EOL; | |
// delete local file | |
unlink($out_filename); | |
echo '5. Delete local temp zip file' . PHP_EOL; | |
} | |
/************************************ start ***************************************************/ | |
foreach ($config as $key => $value) { | |
echo 'Start: ' . $key . PHP_EOL; | |
backup( | |
$value['source_folder'], | |
$value['out_filename'], | |
$value['regString'], | |
$value['backup_time'] | |
); | |
echo PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment