勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

PHPからDBX Platformを利用してDropbox内のファイルを削除する方法

  PHP

以前にPHPからDropboxのファイル一覧のデータ(ファイル名や更新日時等)を取得するという記事を書いたが、そのデータを利用しファイル名を指定した上で当該ファイルをDropbox内から削除したい。以下に実装方法をメモ。

 

Dropbox側の準備

Dropbox側の準備については以下過去記事を参考に「アプリの作成~リフレッシュトークンの取得」まで済ませておくこと。

https://taitan916.info/blog/archives/4694#Dropbox

 

実装方法

ソースコード

<?php
const APP_KEY = '【App key】';
const APP_SECRET = '【App secret】';
const REFRESH_TOKEN = '【リフレッシュトークン】';

//一時的なアクセストークンを取得
function getAccessToken() {
    $url = 'https://api.dropboxapi.com/oauth2/token';
    $data = [
        'grant_type'    => 'refresh_token',
        'refresh_token' => REFRESH_TOKEN,
        'client_id'     => APP_KEY,
        'client_secret' => APP_SECRET
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

    $res = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $access_token = '';
    if( !curl_errno($ch) && $http_code == "200" ){
        $res = json_decode($res, true);
        $access_token = $res['access_token'];
    } else {
        echo "ERROR: Failed to access Dropbox API : " . curl_error($ch) . "<br>";
    }

    curl_close($ch);

    return $access_token;
}

//ファイル削除
function deleteFile( $access_token, $file ){
    $url = 'https://api.dropboxapi.com/2/files/delete_v2';

    $headers = array(
        'Authorization: Bearer ' . $access_token,
        'Content-Type: application/json',
    );

    $param = array(
        "path" => $file,
    );

    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($param),
        CURLOPT_RETURNTRANSFER => true,
    );

    $ch = curl_init();
    curl_setopt_array($ch, $options);

    $res = curl_exec($ch);

    curl_close($ch);

    return $res;
}


//一時的なアクセストークンを取得
$access_token = getAccessToken();

//削除するファイルを指定
$file = '/002.jpg';
$flg = deleteFile($access_token, $file);

$file部分はアプリのルートディレクトリから見たパスで指定する。また、$fileの空チェックやAPIのステータスコードが200かのチェックも実運用では必要かと思われる。

削除時の戻り値

削除時の戻り値は以下の通り違いがあった。error_summaryもしくはerrorが返ってきている場合はエラー処理を行う、という形になりそう。

削除成功

{
    "metadata": {
        ".tag": "file",
        "name": "002.jpg",
        "path_lower": "/002.jpg",
        "path_display": "/002.jpg",
        "id": "id:xxxxxxxxxxxxxxxxxxx",
        "client_modified": "2024-03-29T07:43:13Z",
        "server_modified": "2024-03-29T07:43:13Z",
        "rev": "xxxxxxxxxxxxxxxxxxx",
        "size": 128914,
        "is_downloadable": true,
        "content_hash": "xxxxxxxxxxxxxxxxxxx"
    }
}

削除失敗(ファイルが見つからない場合)

{
    "error_summary": "path_lookup/not_found/.",
    "error": {
        ".tag": "path_lookup",
        "path_lookup": {
            ".tag": "not_found"
        }
    }
}

 

所感

バックアップシステムが作れそう

Dropboxへのアップロード、一覧取得、ファイル削除が可能になったので、何らかのバックアップ用ファイルを定期的にアップロードし、ディレクトリ内のファイル数が〇以上になったら一番古いものを削除とログローテーションみたいな機能も搭載したバックアップシステムが作れそう。

ライブラリも利用してみたい

DropboxとPHP連携の日本語情報が少ない上、APIの操作方法もそれなりに難易度が高く色々と難儀した。

公式サイトに以下ライブラリの紹介があったので試してみたいところ。

https://github.com/kunalvarma05/dropbox-php-sdk

https://github.com/spatie/dropbox-api

公式のライブラリではないようだけど、バニラPHPよりもっと簡単にAPIが操作できればいいなと思う。

 

参考サイト

https://pikopiko.blog/1059/

 - PHP

  関連記事

PHPからDBX Platformを利用してDropbox内にディレクトリ(フォルダ)を作成する方法

PHPからDBX Platformを利用してDropbox内にディレクトリ(フォ ...

PHPからDBX Platformを利用してサーバ内のファイルをアップロードする方法

PHPで何らかのファイルを保存するようなケースだと今まではローカルに保存する、も ...

PHPからDBX Platformを利用してDropbox内のファイル一覧を取得する方法

以前にPHPからDropboxにファイルをアップロードするという記事を書いたが、 ...