PHP で Native API を使って Backblaze からファイルをインポート
PHP で非公開の Backblaze B2 オブジェクトを一つインポートするには、Native API で認証し、ダウンロードデータを一時ファイルにストリーミングします。PHP のオープンソースの cURL 拡張機能が HTTP リクエストを処理するため、SDK に依存しません。以下のコマンドは、転送とディスクへの書き込みが成功した後にのみ、指定した保存先を置き換えます。
前提条件
- PHP CLI 8.5.10 またはそれ以降の 8.5 パッチ版と
ext-curlを備えた Linux コマンドライン。この例は PHP 8.5.10 でテスト済みです。メンテナンス対象のブランチの最新パッチ版を使用してください。 - 既存の非公開 B2 バケットと、SSE-C ヘッダーなしで読み取れるオブジェクトの正確な名前
- 対象のバケットとオブジェクトのプレフィックスへの
readFilesアクセス権を持つアプリケーションキー。キー ID とアプリケーションキーは別々の値で、両方が必要です。 - ローカルファイルシステム上の、既存の書き込み可能な保存先ディレクトリ。同じ保存先に対して同時に実行するインポーターは一つだけにしてください。
プログラムを保存する前に、インストール済みの CLI を確認してください。
php -r 'exit(PHP_MAJOR_VERSION === 8 && PHP_MINOR_VERSION === 5 && version_compare(PHP_VERSION, "8.5.10", ">=") && extension_loaded("curl") ? 0 : 1);'
終了コードが 0 なら、この CLI は前提条件を満たしています。失敗した場合は、PHP CLI 用の cURL をインストールまたは有効化するか、サポート対象の PHP バージョンを選び、再確認してください。Composer によるインストールは不要です。
B2 Native API の使用
v4 の認証レスポンスでは、downloadUrl が apiInfo.storageApi 内に格納されます。認証トークンは引き続きトップレベルにあります。最初のリクエストでは、キー ID とアプリケーションキーを使って HTTP Basic Auth で認証します。その後のダウンロードでは、返されたトークンを Authorization ヘッダーに指定します。
以下の完全なプログラムを import-b2.php として保存してください。HTTPS エンドポイントと、ローカルテスト用のループバック HTTP エンドポイントを受け付け、両方のリクエストでリダイレクトを拒否します。
単一オブジェクトのインポート
<?php
declare(strict_types=1);
final class CurlTransport
{
private const MAX_AUTH_BYTES = 1_048_576;
public function __construct(private readonly int $timeoutSeconds = 60) {}
/** @return array<string, mixed> */
public function authorize(string $url, string $keyId, string $applicationKey): array
{
$this->assertSafeUrl($url);
$body = '';
$curl = curl_init($url);
if ($curl === false) {
throw new RuntimeException('Could not initialize cURL');
}
try {
if (!curl_setopt_array($curl, [
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_TIMEOUT => $this->timeoutSeconds,
CURLOPT_USERPWD => $keyId . ':' . $applicationKey,
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (&$body): int {
if (strlen($body) + strlen($chunk) > self::MAX_AUTH_BYTES) {
return 0;
}
$body .= $chunk;
return strlen($chunk);
},
])) {
throw new RuntimeException('Could not configure cURL');
}
$ok = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($ok !== true || $status !== 200) {
throw new RuntimeException("B2 authorization failed with HTTP {$status}");
}
} finally {
unset($curl);
}
$decoded = json_decode($body, true, flags: JSON_THROW_ON_ERROR);
if (!is_array($decoded)) {
throw new RuntimeException('B2 returned an invalid authorization response');
}
return $decoded;
}
/** @param resource $output */
public function download(string $url, string $token, $output, int $maxBytes): void
{
$this->assertSafeUrl($url);
$written = 0;
$curl = curl_init($url);
if ($curl === false) {
throw new RuntimeException('Could not initialize cURL');
}
try {
if (!curl_setopt_array($curl, [
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTPHEADER => ['Authorization: ' . $token],
CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
CURLOPT_TIMEOUT => $this->timeoutSeconds,
CURLOPT_WRITEFUNCTION => static function ($handle, string $chunk) use (
$output,
$maxBytes,
&$written,
): int {
$length = strlen($chunk);
if ($written + $length > $maxBytes) {
return 0;
}
$result = fwrite($output, $chunk);
if ($result !== $length) {
return 0;
}
$written += $result;
return $result;
},
])) {
throw new RuntimeException('Could not configure cURL');
}
$ok = curl_exec($curl);
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($ok !== true || $status !== 200) {
throw new RuntimeException("B2 download failed with HTTP {$status}");
}
} finally {
unset($curl);
}
}
private function assertSafeUrl(string $url): void
{
$scheme = parse_url($url, PHP_URL_SCHEME);
$host = parse_url($url, PHP_URL_HOST);
$loopback = $scheme === 'http' && in_array($host, ['127.0.0.1', '::1'], true);
if ($scheme !== 'https' && !$loopback) {
throw new RuntimeException('B2 endpoints must use HTTPS');
}
}
}
/** @param array<string, mixed> $authorization */
function requiredString(array $authorization, string $key): string
{
$value = $authorization[$key] ?? null;
if (!is_string($value) || $value === '') {
throw new RuntimeException("B2 authorization response is missing {$key}");
}
return $value;
}
function encodeObjectName(string $objectName): string
{
$segments = explode('/', $objectName);
if (in_array('.', $segments, true) || in_array('..', $segments, true)) {
throw new InvalidArgumentException('Object names cannot contain dot path segments');
}
return implode('/', array_map('rawurlencode', $segments));
}
function importB2Object(
CurlTransport $transport,
string $authorizeUrl,
string $keyId,
string $applicationKey,
string $bucket,
string $objectName,
string $destination,
int $maxBytes,
): void {
if ($maxBytes < 1 || $bucket === '' || $objectName === '') {
throw new InvalidArgumentException('Bucket, object name, and a positive limit are required');
}
$authorization = $transport->authorize($authorizeUrl, $keyId, $applicationKey);
$apiInfo = $authorization['apiInfo'] ?? null;
$storageApi = is_array($apiInfo) ? ($apiInfo['storageApi'] ?? null) : null;
if (!is_array($storageApi)) {
throw new RuntimeException('B2 authorization response is missing storageApi');
}
$downloadUrl = requiredString($storageApi, 'downloadUrl');
$token = requiredString($authorization, 'authorizationToken');
$url = rtrim($downloadUrl, '/') . '/file/' . rawurlencode($bucket) . '/'
. encodeObjectName($objectName);
$directory = dirname($destination);
$realDirectory = realpath($directory);
if ($realDirectory === false || !is_dir($realDirectory) || !is_writable($realDirectory)) {
throw new RuntimeException('Destination directory must exist and be writable');
}
$temporary = tempnam($realDirectory, '.b2-');
if ($temporary === false) {
throw new RuntimeException('Could not create a temporary destination');
}
if (dirname($temporary) !== $realDirectory) {
@unlink($temporary);
throw new RuntimeException('Temporary file was not created beside the destination');
}
$output = fopen($temporary, 'wb');
if ($output === false) {
@unlink($temporary);
throw new RuntimeException('Could not open the temporary destination');
}
try {
$transport->download($url, $token, $output, $maxBytes);
$flushed = fflush($output);
$closed = fclose($output);
$output = null;
if (!$flushed || !$closed) {
throw new RuntimeException('Could not finish writing the downloaded object');
}
if (!rename($temporary, $destination)) {
throw new RuntimeException('Could not publish the downloaded object');
}
} finally {
if (is_resource($output)) {
fclose($output);
}
if (file_exists($temporary)) {
unlink($temporary);
}
}
}
function main(array $arguments): void
{
if (count($arguments) !== 2) {
throw new InvalidArgumentException('Usage: php import-b2.php DESTINATION');
}
foreach (['B2_KEY_ID', 'B2_APPLICATION_KEY', 'B2_BUCKET', 'B2_OBJECT'] as $name) {
if (getenv($name) === false || getenv($name) === '') {
throw new RuntimeException("Missing environment variable: {$name}");
}
}
$configuredMaxBytes = getenv('B2_MAX_BYTES');
$maxBytes = filter_var(
$configuredMaxBytes === false ? 100 * 1024 * 1024 : $configuredMaxBytes,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]],
);
if ($maxBytes === false) {
throw new RuntimeException('B2_MAX_BYTES must be a positive integer');
}
$configuredTimeout = getenv('B2_TIMEOUT_SECONDS');
$timeoutSeconds = filter_var(
$configuredTimeout === false ? 60 : $configuredTimeout,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 3600]],
);
if ($timeoutSeconds === false) {
throw new RuntimeException('B2_TIMEOUT_SECONDS must be an integer from 1 to 3600');
}
importB2Object(
new CurlTransport($timeoutSeconds),
getenv('B2_AUTHORIZE_URL') ?: 'https://api.backblazeb2.com/b2api/v4/b2_authorize_account',
(string) getenv('B2_KEY_ID'),
(string) getenv('B2_APPLICATION_KEY'),
(string) getenv('B2_BUCKET'),
(string) getenv('B2_OBJECT'),
$arguments[1],
$maxBytes,
);
}
try {
main($argv);
} catch (Throwable) {
error_log('B2 import failed');
exit(1);
}
そのディレクトリで、以下のコマンドの認証情報、バケット、オブジェクト名を置き換えて実行してください。アプリケーションでは、認証情報をソースやシェル履歴に保存せず、シークレットマネージャーから渡してください。相対パスの保存先には、- で始まる名前も含め、先頭に ./ を付けてください。
B2_KEY_ID='your-key-id' \
B2_APPLICATION_KEY='your-application-key' \
B2_BUCKET='my-bucket' \
B2_OBJECT='exports/report.bin' \
php import-b2.php ./report.bin
成功すると何も出力せずに終了コード 0 で終了し、./report.bin にダウンロードしたバイト列が保存されます。再実行が成功すると、そのファイルを置き換えます。コードは保存先と同じディレクトリにある一意の .b2- ファイルにバイト列を一時保存し、閉じてから、rename()
で保存先として確定します。ローカルの Linux ファイルシステムでは、置き換えはアトミックです。そのため、読み取り側には古いファイルか、置き換えが完了したファイルのいずれかが見えます。これはクラッシュ時の永続性を保証するものではなく、同時実行するインポーター間の調整も行いません。
デフォルトの上限は 100 MiB で、上限値を含みます。必要に応じて、B2_MAX_BYTES に別の正の整数をバイト単位で設定してください。認証レスポンスには、別途 1 MiB の上限があります。各リクエストには、接続の確立を含めて転送全体で 60 秒の制限時間があります。B2_TIMEOUT_SECONDS は 1 から 3,600 までの整数を受け付けます。認証とダウンロードには別々の制限時間が適用されるため、低速な接続では小さなファイルでも失敗することがあります。どちらのリクエストも再試行しません。
失敗すると終了コード 1 で終了し、レスポンス本文や認証情報を含まない汎用的なエラーを記録します。認証失敗、オブジェクトへのアクセス拒否やオブジェクトの不在、HTTP 転送のサイズ超過や中断、ディスク書き込みの失敗が発生しても、既存の保存先はそのまま保持され、今回の実行で作成した一時ファイルは削除されます。保存先が存在しなかった場合は、何も残りません。プロセスの強制終了やマシンのクラッシュでは、.b2- ファイルが残ることがあります。そのインポーターが停止したことを確認してから削除してください。
インポーターのカスタマイズ
B2_OBJECT には、事前に URL エンコードせず、UTF-8 のオブジェクト名をそのまま設定してください。B2 のエンコード規則に従い、コードは各パスセグメントをエンコードし、/ 区切り文字と、リテラルのスペース、+、%、#、? の各文字を保持します。. と .. のパスセグメントは拒否します。名前でダウンロードすると、現在の可視バージョンが選択されます。このコマンドはバケットの一覧表示や過去のファイル ID の選択は行いません。
安全で効率的なファイル処理
キーの権限は、必要なバケットとプレフィックスに限定してください。TLS 検証を有効にしたまま、B2 のデフォルトの認証エンドポイントを使用してください。B2_AUTHORIZE_URL は管理下にあるローカルテストサービスを検証するためのもので、信頼できない呼び出し元からエンドポイントを受け取るためのものではありません。
インポーターは HTTP 転送の完了とバイト数の上限を確認します。公開元が提供するチェックサムとの比較や、顧客管理の暗号化キーでアップロードされたファイルの復号は行いません。ワークフローでコンテンツの真正性の検証や SSE-C が必要な場合は、ファイルを保存先として確定する前に、その検証やキー処理を追加してください。
インポート後のサーバー側処理については、Backblaze インポート Robotを参照してください。
