Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Thiago Lenzi

Backup automatico para Google Drive com PHP

Recommended Posts

Bom dia pessoal.

 

Pensando em segurança para aplicações online.

Existe alguma forma enviar arquivos automaticamente para

nuvens do Google Drive. Isso automaticamente.

 

Caso no futuro tenha qualquer problema, possa recuperar os arquivos.

 

Se tiver algum exemplo de script, será de grande valor.

 

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Se você procurar no Google achará varias formas de usar isso.. dá para usar isso também em FTP

/*
    Backup MySQL Databases to Google Drive and FTP
    Copyright (C) 2008 Little Apps  (http://www.little-apps.com/)
	For more information on this script, please see http://www.little-apps.com/blog/2013/12/backup-mysql-databases-google-drive-ftp/

    The following code is public domain. The "Google API PHP Client" is licensed
	under the Apache 2.0 license. The "Simple MySQL Export Function" listed on
	CodeCanyon is licensed under the terms of CodeCanyon's regular or extended
	license (dependant on which was used with your purchase).
*/

if ( php_sapi_name(  ) != 'cli' || !empty( $_SERVER['REMOTE_ADDR'] ) ) die('Must be run from command line');

@ini_set( 'memory_limit', '5120M' );
@ini_set( 'max_execution_time', 0 );
@set_time_limit( 0 );

// Uncomment to enable debugging
//error_reporting(E_ALL);

// Google Drive info
define('GDRIVE', true); // Set to false to disable Google Drive
define('CLIENT_ID', '');
define('CLIENT_SECRET', '');
define('CLIENT_REFRESH_ACCESS_TOKEN', '');

// FTP info
define('FTP', false); // Set to false to disable FTP
define('FTP_HOST', '');
define('FTP_PORT', 21);
define('FTP_LOGIN', '');
define('FTP_PASS', '');
define('FTP_PASV', true); // Use FTP Passive mode?

// MySQL info
// Filenames are [DB NAME].sql
$mysqldbs = array();
$mysqldbs[] = array('host' => 'localhost', 'user' => 'username here', 'password' => 'password here', 'db' => 'database here', 'desc' => 'description');

// Misc
define('REPORT_EMAIL', 'joe.blow@gmail.com');
define('REPORT_EMAIL_SUBJECT', 'MySQL Backup');

function error_handler( $num, $str, $file, $line, $context = null ) {
    report( new ErrorException( $str, 0, $num, $file, $line ) );
}

function report($error) {
    if ( is_a( $error,'Exception' ) ) {
		$message = "The following exception was thrown while trying to backup MySQL database(s):\n";
		$message .= "Type: " . get_class( $error ) . "\nMessage: ".$error->getMessage()."\nFile: ".$error->getFile()."\nLine: ".$error->getLine()."\n";
    } else {
		$message = $error;
    }

    @mail(REPORT_EMAIL, REPORT_EMAIL_SUBJECT, $message);
    die();
}

set_error_handler('error_handler');
set_exception_handler('report');

// Get backup(s)
require_once(dirname(__FILE__).'/exportmysqlfunction.php');

foreach ($mysqldbs as $db) {
	$mysqlbackup = exportMySQL($db['host'], $db['user'], $db['password'], $db['db']);
	
	// Compress using GZIP (if possible)
	if (function_exists('gzopen')) {
		$mysqlbackupgz = gzencode($mysqlbackup, 6);
		$filename = $db['db'].'.sql.gz';
		
		unset($mysqlbackup);
	} else {
		$mysqlbackupgz = &$mysqlbackup;
		$filename = $db['db'].'.sql';
	}

	if (GDRIVE)
		upload_google_drive($mysqlbackupgz, $filename, $db['desc']);
		
	if (FTP)
		upload_ftp($mysqlbackupgz, $filename);

	unset($mysqlbackup, $mysqlbackupgz);
}

function upload_google_drive(&$sql, $filename, $desc) {
	global $service;
	
	if (!isset($service)) {
		set_include_path(dirname(__FILE__) . '/google-api-php-client/src/' . PATH_SEPARATOR . get_include_path());

		require_once 'Google/Client.php';
		require_once 'Google/Service/Drive.php';

		$client = new Google_Client();
		$service = new Google_Service_Drive($client);

		$client->setClientId(CLIENT_ID);
		$client->setClientSecret(CLIENT_SECRET);
		$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
		$client->addScope("https://www.googleapis.com/auth/drive");
		$client->setAccessType('offline');

		$client->refreshToken(CLIENT_REFRESH_ACCESS_TOKEN);
	}

	// See if file exists
	$file_id = '';

	try {
		$files = $service->files->listFiles(array('q' => 'title = \''.$filename.'\' and trashed = false'));

		if (isset($files->items[0]->id))
			$file_id = $files->items[0]->id;
	} catch (Exception $e) {
	}

	if ($file_id == '') {
		// Insert a file
		$file = new Google_Service_Drive_DriveFile();
		$file->setTitle($filename);
		$file->setDescription($desc);
		$file->setMimeType('application/octet-stream');

		$createdFile = $service->files->insert($file, array(
										'data' => &$sql,
										'mimeType' => 'application/octet-stream',
										'uploadType' => 'multipart'
								));
	} else {
		// First retrieve the file from the API.
		$file = $service->files->get($file_id);
		$file->setMimeType('application/octet-stream');
								
		$updatedFile = $service->files->update($file_id, $file, array(
                                          'newRevision' => false, // Don't store revision in order to save space
                                          'data' => &$sql,
                                          'mimeType' => 'application/octet-stream',
										  'uploadType' => 'multipart'
                                        ));
	}
}

function upload_ftp(&$sql, $filename) {
	if (!function_exists('ftp_connect')) {
		throw new Exception("FTP is not installed with PHP");
		return false;
	}

	$conn_id = ftp_connect(FTP_HOST, FTP_PORT);
	
	if (!$conn_id) {
		throw new Exception("Error connecting to FTP");
		return false;
	}
		
	$login_result = ftp_login($conn_id, FTP_LOGIN, FTP_PASS);
	
	if (!$login_result) {
		throw new Exception("Error logging into FTP");
		return false;
	}
	
	if (FTP_PASV) {
		// turn on passive mode transfers
		if (ftp_pasv($conn_id, true) == FALSE) {
			throw new Exception("Error enabling passive mode on FTP");
			return false;
		}
	}
	
	// Write string into memory
	$stream = fopen('php://memory','r+');
	fwrite($stream, $sql);
	rewind($stream);
	
	$uploaded = ftp_fput($conn_id, $filename, $stream, FTP_BINARY);
	
	if (!$uploaded) {
		throw new Exception("Error uploading ".$filename." to FTP");
		return false;
	}
	
	fclose($stream);
	ftp_close($conn_id);
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.