從google drive 下載檔案範例
阿新 • • 發佈:2020-11-26
認證用token檔案生成範例
<?php //google driveへアクセス用のトークンファイルを作成 $autoloadPath = __DIR__ . '/../../../vendor/autoload.php'; require $autoloadPath; if (php_sapi_name() != 'cli') { throw new Exception('This application must be run on the command line.'); } $envArr = ["dev", "stg", "prd"]; if ($argc !== 2 || !in_array($argv[1], $envArr) ) { echo "以下のコマンドを実行してください。\n"; echo "ロカールの場合:php createAuthToken.php dev \n"; echo "STGの場合:php createAuthToken.php stg \n"; echo "本番の場合:php createAuthToken.php prd \n"; exit; }; $client = new Google_Client(); $client->setApplicationName('Google Drive API PHP Quickstart'); $client->setScopes(Google_Service_Drive::DRIVE); $client->setAuthConfig('credentials_'.$argv[1].'.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); $tokenPath = 'driveAuthToken.json'; // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken); // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } // Save the token to a file. if (!file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, true); } file_put_contents($tokenPath, json_encode($client->getAccessToken()));
從google drive下載檔案範例
<?php require __DIR__ . '/vendor/autoload.php'; if (php_sapi_name() != 'cli') { throw new Exception('This application must be run on the command line.'); } /** * Returns an authorized API client. * @return Google_Client the authorized client object */ function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Drive API PHP Quickstart'); $client->setScopes(Google_Service_Drive::DRIVE); $client->setAuthConfig('credentials3.json'); $client->setAccessType('offline'); $client->setPrompt('select_account consent'); // Load previously authorized token from a file, if it exists. // The file token.json stores the user's access and refresh tokens, and is // created automatically when the authorization flow completes for the first // time. $tokenPath = 'token.json'; if (file_exists($tokenPath)) { $accessToken = json_decode(file_get_contents($tokenPath), true); $client->setAccessToken($accessToken); } // If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); $client->setAccessToken($accessToken); // Check to see if there was an error. if (array_key_exists('error', $accessToken)) { throw new Exception(join(', ', $accessToken)); } } // Save the token to a file. if (!file_exists(dirname($tokenPath))) { mkdir(dirname($tokenPath), 0700, true); } file_put_contents($tokenPath, json_encode($client->getAccessToken())); } return $client; } function getFilesInParent($service, $parentId){ $optParams = array( //'pageSize' => 1000, 'fields' => 'nextPageToken, files(id, name, parents)' // ,'q' => "'1RORMSsy0qnC-XPS29a3vfwCB21l0jL_B' in parents" // ,'q' => "'root' in parents" ,'q' => "'".$parentId."' in parents" ); $results = $service->files->listFiles($optParams); return $results->getFiles(); }; //$pathはフォルダまで、指定したフォルダ內のファイルリストを取得 function getFileListFromPath($service, $path) { $folders = explode("/", $path); $files = getFilesInParent($service, "root"); $parentId = ""; for($i=0; $i<count($folders); $i++) { foreach($files as $file) { if($folders[$i] == $file->getName()) { $parentId = $file->getId(); break; } } $files = getFilesInParent($service, $parentId); } return $files; } //$pathはファイル名まで、指定したファイルをダウンロード function getFileFromPath($service, $path) { $folders = explode("/", $path); $files = getFilesInParent($service, "root"); $parentId = ""; for($i=0; $i<count($folders); $i++) { foreach($files as $file) { if($folders[$i] == $file->getName()) { $parentId = $file->getId(); break; } } if ($i < count($folders) - 1) { $files = getFilesInParent($service, $parentId); } } return $file; } // $results = $service->files->listFiles(); //ファイルリストの出力 function printfiels($files) { if (count($files) == 0) { print "No files found.\n"; } else { print "Files:\n"; foreach ($files as $file) { printf("%s %s \n", $file->getName(), $file->getId); } } } //ファイルリストのダウンロード function downloadFiles($service,$files){ foreach($files as $file) { download($service,$file); } } //ファイルのダウンロード function download($service,$file) { $response = $service->files->get($file->getId(), array( 'alt' => 'media')); $content = $response->getBody()->getContents(); $filename = $file->getName(); file_put_contents($filename, $content); } // Get the API client and construct the service object. $client = getClient(); $service = new Google_Service_Drive($client); //$files = getFileListFromPath($service, "testfile"); $files = getFileListFromPath($service, "root"); // $files = getFilesInParent($service, "share"); printfiels($files); // downloadFiles($service,$files); // $file = getFileFromPath($service, "testfile/excel2.xlsm"); // // download($service,$file); // // var_dump(stat("excel2.xlsm")); // chown("excel2.xlsm", "test"); // rename("#117_検討資料3.xlsx", "#117_検討資料4.xlsx"); // $file = fopen("./検討資料4.xlsx","r"); // print_r(stat("./検討資料4.xlsx")); // fclose($file);
從共享驅動(share drive)獲取檔案列表範例
public static function getFilesInParent($parentId, $containName=""){ $q = "'".$parentId."' in parents "; if (!empty($containName)) { $q .= " and name contains '".$containName."'"; } $optParams = array( 'fields' => 'nextPageToken, files(id, name, parents)' ,'includeItemsFromAllDrives' => true ,'corpora' => 'allDrives' ,"supportsAllDrives"=>true ,'q' => $q ); $results = self::$service->files->listFiles($optParams); return $results->getFiles(); }