BACKUP DỮ LIỆU LÊN GOOGLE DRIVE

  -  
Mở đầu

Xin hỏi các bạn trong một website thì trang bị gì quan trọng đặc biệt nhất? chắc chắn rằng 96.69% chúng ta trả lời là dữ liệu phải không. Đúng vậy dữ liệu rất là quan tiền trọng. Mình lập ra trang web là để thu thập và lưu tài liệu mà

*
. Do nó quan trọng như thế nên ta phải có biện pháp bảo vệ. Phải tất cả một phương án để giữ mang đến nó không xẩy ra mất. đưa sử như 1 ngày rất đẹp trời một admin hoặc một tin tặc nào đó đó vô tình xóa một bạn dạng ghi quan trọng hoặc tổng thể dữ liệu đi chẳng hạn. Điều đó thật kinh điển khiếp nếu như khách hàng không cấu hình thiết lập một chức năng backup dữ liệu. Trang của các bạn sẽ tự dưng vươn lên là một website trống rỗng như thời mới được chế tác ra. Và hôm nay mình sẽ phân tách sẻ cách để backup cơ sở tài liệu và upload file đang backup đó lên google driver.

Bạn đang xem: Backup dữ liệu lên google drive

Để triển khai việc này chúng ta cần phải chuẩn bị 2 thứ:

Một thông tin tài khoản googleMột project laravel áp dụng mysql

Và công tác sẽ phải tiến hành theo 2 bước:

Bước 1: chế tác file backup cơ sở dữ liệuBước 2: Upload file đã sản xuất lên google driveNội dung cần chuẩn chỉnh bị

Lệnh backup cửa hàng dữ liệu

Để sinh sản file backup cơ sở tài liệu ta có một lệnh rất dễ dàng và đơn giản dùng mysqldump như sau:

mysqldump database_name --password=your_pass --user=user_name --single-transaction | gzip >file_path_to_write_to.sql.gzVà lệnh để phục hồi lại cơ sở dữ liệu đã backup là:

gunzip

Bật Google Drive API

Muốn áp dụng được API Drive thì ta cần phải bật nó lên. Quá trình thực hiện tại như sau:

*

Các bạn ấn nút Continue để tạo một project. Nếu bạn đã có project rồi thì chọn project đó rồi ấn Continue. Chờ một chút ít nó sẽ hiện ra trang như sau.

*

B2: tạo thành giấy hội chứng nhậnẤn nút Go to lớn credentials để truy nhập vào trang chế tạo ra giấy triệu chứng nhận. Màn hình Add credentials khổng lồ your project xuất hiện. Bản thân chưa tạo ra credential vội. Setup một số tin tức trước đã. Ấn Cancel để hủy bỏ.

Tiếp theo chọn tab OAuth consent screen với điền các thông tin quan trọng vào đây.

*

Chỉ đề xuất chọn email với điền Product name shown to users là được.Sau đó ấn Save để lưu lại.

Chuyển sang tab Credentials ấn nút Create credentials. Nó sẽ sổ ra một list chọn. Lựa chọn OAuth client ID.

*

Tiếp cho chọn Other và nhập thương hiệu OAuth client nên tạo.

*

Rồi ấn Create. Màn hình sẽ hiện tại client ID và client secret. Ấn OK nhằm tắt nó đi.

B3: mua file json của giấy hội chứng nhậnTrên screen Credentials, ta sẽ sở hữu file json của credential vừa chế tạo ra về bằng cách ấn nút có hình mũi tên tải xuống bên đề xuất của credential đó.

*

Đổi tên file json kia thành drive-secret.json mang lại dễ nhớ. Rồi chép file đó vào folder /storage/drive của project.

*

Cài đặt thư viện bắt buộc thiết

Để có thể thao tác cùng với Google Api dễ dàng dàng. Ta sở hữu thư viện google/apiclient vào project laravel.

Xem thêm: Hướng Dẫn Cài Viber Cho Máy Tính Windows, Cách Cài Đặt Và Sử Dụng Viber Trên Máy Tính

composer require google/apiclientLập trìnhVới mục tiêu đề ra là tạo ra file database backup tiếp nối upload lên google driver chúng ta sẽ rất cần phải tạo 2 command:

Một command dùng làm tạo file database backupMột command upload file database backup lên Google Drive. Command này sẽ gọi command đầu tê để chế tạo file database backup trước.

Như vậy kim chỉ nam đã rõ ràng, các bước đã rành mạch cùng code thôi.

Tạo command export database file

Tạo command bằng lệnh artisan:

php artisan make:command ExportDatabaseThêm config path lưu file export ra ở tệp tin config/filesystems.php:

// config/filesystems.php "path" => < "backup_database" => "backup/database", >,Nhập thương hiệu command:

protected $signature = "db:export";Ta sẽ áp dụng Process của Symfony để hotline shell command tạo thành file export database.

Nói qua về Process một chút. Process là một thư viện hỗ trợ việc thao tác làm việc với shell command. Nó vẫn giống với hàm exec, passthru, shell_exec, system vào PHP vậy. Khi thực hiện Process thì ta sẽ dễ ợt viết test cho command của bạn. Và bao gồm Laravel cũng đang sử dụng Process phải ta trọn vẹn tin tưởng và tất nhiên sẽ không phải cài thêm tủ sách rồi vì chưng nó đã có sẵn vào project laravel.

Bây giờ ta use thư viện và triển thôi

// app/Console/Commands/ExportDatabase.phpuse SymfonyComponentProcessProcess;use SymfonyComponentProcessExceptionProcessFailedException;Hàm handle:

// app/Console/Commands/ExportDatabase.phppublic function handle() $dateTime = Carbon::now(); // Lấy thời gian hiện tại $dateTimeString = $dateTime->format("Y_m_d_H_i_s"); // tạo nên chuỗi thời gian /* Tạo đường truyền đến file database export. Lưu ý đường dẫn này yêu cầu là mặt đường dẫn hoàn hảo cho nó dĩ nhiên cú. */ $fileName = "database_" . $dateTimeString . ".sql.gz"; $filePath = storage_path(config("filesystems.path.backup_database")); /* Lấy các thông tin thông số kỹ thuật database từ file env */ $database = env("DB_DATABASE"); $userName = env("DB_USERNAME"); $password = env("DB_PASSWORD"); /*---------------------------------------------------Tạo shell command---------------------------------------------------* Mình sẽ chú thích những đoạn code rồi cần sẽ không lý giải gì mặt khác nhé.

Bạn hãy nhờ rằng đăng kí command class vào tệp tin app/Console/Kernel.php nhé.

// app/Console/Kernel.php protected $commands = < CommandsExportDatabase::class, >;Chú ý: Đối với phiên bạn dạng laravel 5.5 trở lên thì trong hàm commands() của file app/Console/Kernel.php đã được tự động load những class trong thư mục Commands rồi nên chúng ta không cần thực hiện đăng kí command thủ công nữa.

Chạy test lệnh:

php artisan db:exportKết quả tạo nên file database trong folder storage

*

Tạo công dụng upload lên drive

Config

Thêm những biến config tại tệp tin config/services.php

// config/services.php/*..............*/ "google_drive" => < "secret" => storage_path("drive/drive-secret.json"), "access_token" => storage_path("drive/access-token.json"), >,/*..............*/Thêm một disk database vào mảng disks trong file config/filesystems.php để hoàn toàn có thể truy cập được folder "backup-database"dễ dàng hơn.

// config/filesystems.php`"disks" => < "database" => < "driver" => "local", "root" => storage_path("backup/database"), >, /*..................*/>,

Tạo Google Drive service

Luồng buổi giao lưu của google driver service như sau:

Tạo 1 client với tệp tin drive-secret.json vừa tải vềLấy AccessToken để xác thực app hoàn toàn có thể truy cập vào Drive. Giai đoạn này bọn họ phải cấp quyền truy nã cập thủ công lần đầu tiên. AccessToken sẽ tiến hành lưu vào tệp tin access-token.json. Tiếp nối thì khi AccessToken quá hạn nó đã được tự động gia hạn bởi key gia hạn AccessToken cũng được lưu trong file access-token.json.Sau khi xác nhận quyền truy vấn API thành công xuất sắc thì chúng ta cũng có thể upload, download, làm chủ file bên trên drive tùy ý.

Xem thêm: Top 18 Cách Làm Gì Để Kiếm Tiền Bây Giờ ? Những Cách Kiếm Tiền Đơn Giản

Bây giờ họ sẽ tạo thành file app/Services/GoogleDriveService.php tiến hành các công việc trên:

namespace AppServices;use Google_Service_Drive;use Google_Service_Drive_DriveFile;use Google_Client;use Storage;use Exception;class GoogleDriveService protected $driveService; protected $scopes = < Google_Service_Drive::DRIVE_FILE, >; protected $accessType = "offline"; public function __construct() // Get the API client & construct the service object. $client = $this->getClient(); $this->driveService = new Google_Service_Drive($client); public function listFiles() // Print the names và IDs for up khổng lồ 10 files. $optParams = < "pageSize" => 10, "fields" => "nextPageToken, files(id, name)" >; $results = $this->driveService->files->listFiles($optParams); if (count($results->getFiles()) == 0) print "No files found. "; else print "Files: "; foreach ($results->getFiles() as $file) printf("%s (%s) ", $file->getName(), $file->getId()); protected function getClient() $client = new Google_Client(); $client->setApplicationName(config("app.name")); $client->setScopes(implode(" ", $this->scopes)); $client->setAuthConfig(config("services.google_drive.secret")); $client->setAccessType($this->accessType); $client->setAccessToken($this->getAccessToken($client)); // Refresh the token if it"s expired. If ($client->isAccessTokenExpired()) $this->refreshToken($client); return $client; protected function getAccessToken($client) // Load previously authorized credentials from a file. $credentialsPath = config("services.google_drive.access_token"); if (file_exists($credentialsPath)) $accessToken = json_decode(file_get_contents($credentialsPath), true); else $accessToken = $this->requestAccessToken($client, $credentialsPath); return $accessToken; protected function refreshToken($client) $credentialsPath = config("services.google_drive.access_token"); $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents($credentialsPath, json_encode($client->getAccessToken())); protected function requestAccessToken($client, $credentialsPath) if (php_sapi_name() != "cli") throw new Exception("Please run this application on the command line."); // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser: %s ", $authUrl); print "Enter verification code: "; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); // Store the credentials to disk. If(!file_exists(dirname($credentialsPath))) mkdir(dirname($credentialsPath), 0700, true); file_put_contents($credentialsPath, json_encode($accessToken)); printf("Credentials saved lớn %s ", $credentialsPath); return $accessToken; public function uploadLatest() $files = Storage::disk("database")->files(); $file = array_pop($files); if ($file == ".gitignore") throw new Exception("Database tệp tin not exist", 1); $fileMetadata = new Google_Service_Drive_DriveFile(< "name" => $file, >); $content = Storage::disk("database")->get($file); $this->driveService->files->create($fileMetadata, < "data" => $content, "mimeType" => "application/gzip", "uploadType" => "multipart", "fields" => "id", >); return $file;

Tạo command

Tạo command bằng lệnh artisan:

php artisan make:command BackupDatabaseHàm handle tạo nên backup cùng upload lên Drive

public function handle() $this->call("db:export"); $this->driveService = new GoogleDriveService; $file = $this->driveService->uploadLatest(); if ($file) $this->info("Upload file " . $file . " successful!"); Kết luậnNhư vậy mình đã giới thiệu xong xuôi cách backup dữ liệu lên Drive rồi. Bây giờ bạn có thể yên vai trung phong là dữ liệu của bản thân sẽ không bao giờ bị mất một giải pháp oan ức nữa.