Home / backup dữ liệu lên google drive Backup dữ liệu lên google drive 27/11/2021 Msống đầuXin hỏi chúng ta trong một website thì máy gì quan trọng đặc biệt nhất? Chắc chắn 96.69% các bạn vấn đáp là tài liệu yêu cầu không. Đúng vậy tài liệu vô cùng quan trọng đặc biệt. Mình lập ra trang web là để tích lũy cùng lưu lại tài liệu mà lại Các các bạn ấn nút ít Continue để chế tác một project. Nếu bạn đã sở hữu project rồi thì chọn project kia rồi ấn Continue. Chờ một ít nó đang hiển thị trang nhỏng sau.Bạn đang xem: Backup dữ liệu lên google driveB2: Tạo giấy chứng nhậnẤn nút Go to credentials để truy nhtràn vào trang chế tác giấy ghi nhận. Màn hình Add credentials to lớn your project xuất hiện thêm. Mình chưa sinh sản credential gấp. Cài đặt một số trong những biết tin trước sẽ. Ấn Cancel nhằm hủy bỏ.Tiếp theo lựa chọn tab OAuth consent screen và điền các công bố cần thiết vào chỗ này.Chỉ đề xuất chọn email với điền Product name shown to users là được.Sau đó ấn Save nhằm giữ gìn.Chuyển lịch sự tab Credentials ấn nút ít Create credentials. Nó đang sổ ra một danh sách chọn. Chọn OAuth client ID.Tiếp cho chọn Other cùng nhập thương hiệu OAuth client đề nghị chế tạo ra.Rồi ấn Create. Màn hình đã hiện tại client ID với client secret. Ấn OK nhằm tắt nó đi.B3: Tải file json của giấy hội chứng nhậnTrên screen Credentials, ta vẫn tải file json của credential vừa chế tạo về bằng phương pháp ấn nút ít bao gồm hình mũi thương hiệu cài đặt xuống mặt yêu cầu của credential đó.Đổi thương hiệu file json kia thành drive-secret.json cho dễ dàng ghi nhớ. Rồi chxay tệp tin đó vào thỏng mục /storage/drive sầu của project.Cài đặt thỏng viện cần thiếtĐể hoàn toàn có thể thao tác làm việc cùng với Google Api dễ ợt. Ta sở hữu thỏng viện google/apiclient vào project laravel.Xem thêm: Top Game Chiến Thuật Offline Hay Cho Pc Cấu Hình Yếu, Game Chiến Thuật Offline Pccomposer require google/apiclientLập trìnhVới phương châm đưa ra là tạo nên tệp tin database backup tiếp nối upload lên google driver họ đã rất cần phải tạo thành 2 command:Một comm& dùng làm tạo ra tệp tin database backupMột command upload tệp tin database backup lên Google Drive sầu. Command này vẫn điện thoại tư vấn commvà đầu tê để chế tạo ra file database backup trước.Bởi vậy phương châm đã cụ thể, các bước sẽ tách biệt cùng code thôi.Tạo comm& export database fileTạo commvà bằng lệnh artisan:php artisan make:commvà ExportDatabaseThêm config path giữ tệp tin export ra ở file config/filesystems.php:// config/filesystems.php "path" => < "backup_database" => "backup/database", >,Nhập thương hiệu command: protected $signature = "db:export";Ta đã sử dụng Process của Symfony để Điện thoại tư vấn shell commvà chế tạo file export database.Nói qua về Process một chút ít. Process là một thư viện cung ứng câu hỏi thao tác với shell command. Nó sẽ giống như với hàm exec, passthru, shell_exec, system trong PHPhường vậy. Lúc áp dụng Process thì ta vẫn dễ dàng viết demo mang đến commvà của khách hàng. Và bao gồm Laravel đang dần áp dụng Process phải ta trọn vẹn tin cậy và tất nhiên đã chưa hẳn cài đặt thêm thỏng viện rồi bởi nó vẫn gồm sẵn vào project laravel.Bây giờ đồng hồ ta use tlỗi 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() Mình vẫn ghi chú các đoạn code rồi phải sẽ không còn giải thích gì thêm nữa đó.quý khách hàng đừng quên đăng kí comm& class vào tệp tin app/Console/Kernel.php nhé.// app/Console/Kernel.php protected $commands = < CommandsExportDatabase::class, >;Chú ý: Đối cùng với phiên phiên bản laravel 5.5 trở lên thì trong hàm commands() của file app/Console/Kernel.php đã làm được auto load các class vào thư mục Commands rồi đề xuất chúng ta không phải tiến hành đăng kí commvà thủ công nữa.Chạy demo lệnh:php artisan db:exportKết trái tạo được file database vào thỏng mục storageTạo tính năng upload lên driveConfigThêm những đổi mới config tại file 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 vào tệp tin config/filesystems.php để hoàn toàn có thể truy cập được thỏng mục "backup-database"dễ ợt hơn.// config/filesystems.php`"disks" => < "database" => < "driver" => "local", "root" => storage_path("backup/database"), >, /*..................*/>,Tạo Google Drive sầu serviceLuồng buổi giao lưu của google driver service như sau:Tạo 1 client với file drive-secret.json vừa mua vềLấy AccessToken nhằm xác nhận tiện ích rất có thể truy vấn vào Drive. Giai đoạn này họ bắt buộc cấp quyền truy vấn bằng tay thủ công lần đầu tiên. AccessToken sẽ được lưu lại vào file access-token.json. Sau đó thì lúc AccessToken quá hạn sử dụng nó sẽ tiến hành tự động gia hạn bằng key gia hạn AccessToken cũng được lưu vào tệp tin access-token.json.Sau Khi chứng thực quyền truy vấn API thành công thì bạn có thể upload, download, thống trị tệp tin trên drive tùy ý.Bây tiếng họ sẽ tạo tệp tin app/Services/GoogleDriveService.php tiến hành các quá trình 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 và construct the service object. $client = $this->getClient(); $this->driveService = new Google_Service_Drive($client); public function listFiles() // Print the names & IDs for up lớn 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("phầm mềm.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 sầu.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 comm& line."); // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("xuất hiện 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 lớn disk. if(!file_exists(dirname($credentialsPath))) mkdir(dirname($credentialsPath), 0700, true); file_put_contents($credentialsPath, json_encode($accessToken)); printf("Credentials saved to %s ", $credentialsPath); return $accessToken; public function uploadLatest() $files = Storage::disk("database")->files(); $tệp tin = array_pop($files); if ($tệp tin == ".gitignore") throw new Exception("Database tệp tin not exist", 1); $fileMetadata = new Google_Service_Drive_DriveFile(< "name" => $file, >); $nội dung = Storage::disk("database")->get($file); $this->driveService->files->create($fileMetadata, < "data" => $nội dung, "mimeType" => "application/gzip", "uploadType" => "multipart", "fields" => "id", >); return $file; Tạo commandTạo comm& bằng lệnh artisan:php artisan make:comm& BackupDatabaseHàm handle sinh sản backup cùng upload lên Drivepublic function handle() $this->call("db:export"); $this->driveService = new GoogleDriveService; $file = $this->driveService->uploadLatest(); if ($file) $this->info("Upload tệp tin " . $file . " successful!"); Kết luậnBởi vậy mình đã ra mắt dứt phương pháp backup dữ liệu lên Drive sầu rồi. Bây giờ chúng ta cũng có thể yên ổn trung tâm là tài liệu của chính mình sẽ không còn khi nào bị mất một cách oan ức nữa.