LoginSignup
17
20

More than 5 years have passed since last update.

PHP で Google Drive を活用

Posted at

$ composer require google/apiclient

からプロジェクトを選択して、APIを有効にする。

認証方法の追加で、認証用のクライアントを作成する。

使い方

google-api-php-client があるのでコレを使うと便利。

composer require google/apiclient:^2.0

基本的なコードは、認証関連の client 作成してソレを Google_Service_Drive に注入する感じ。

$service = new \Google_Service_Drive($client);

$service->files->get(...)

client の作成方法には、Oauthを使う方法と、サービスアカウントを作成する方法とがある。

そのへんは https://github.com/google/google-api-php-client#examples アタリを参考に

APIの発行

Google_Service_Drive 内のプロパティ構成は以下のAPI リファレンスと対になっている。

フォルダ内のファイルを取得

$result = $service->files->listFiles([
    "q" => "'xxxxxxxxxxx' in parents"
]);

foreach ( $result->getFiles() as $file) {
    assert($file instanceof \Google_Service_Drive_DriveFile);
    $file->getName();
    $file->getMime();
}

ファイルのダウンロード

リファレンスにはなぜか載っていないが、 alt=media を付けるとダウンロード出来る。

/** @var GuzzleHttp\Psr7\Response $response */
$response = $service->files->get($file->getId(),[
    "alt" => "media"
]);
$response->getBody()->getSize());

ファイルの作成

Request Body の file Resource は基本 Google_Service_Drive_DriveFile で作成する。

$body = new \Google_Service_Drive_DriveFile();
$body->setId($service->files->generateIds()->getIds());
....
$service->files->create($file);

ファイルのコピー

$body = new \Google_Service_Drive_DriveFile();
$body->setMimeType("application/vnd.google-apps.spreadsheet");
$body->setParents([$tarDir]);
$body->setName(Str::random());
$service->files->copy("xxxxxxxx",$body);
17
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
20