0
0

More than 1 year has passed since last update.

【PHP】S3 ファイル(オブジェクト)の有無をチェックする方法

Last updated at Posted at 2023-02-04

概要

S3に保存したファイルの有無をチェックする方法がないかと思い調べたら、良い方法があったので、備忘録も含めてその方法を説明します。

設定方法

  1. 最初に、AWS SDKをインストールします。インストール方法は、開発している環境によって異なる為、下記の公式ドキュメントを確認して行って下さい。
    インストール:AWS SDK for PHPバージョン 3

  2. SDKとAWSを繋ぐ方法については、下記を参照して行って下さい
    AWS SDK for PHPバージョン 3 の基本的な使用パターン

3. 公式内にdoesObjectExistのメソッドがある為、そのメソッドを使用してS3に保存してあるファイルの有無を確認する

# S3にコネクトをする
$s3 = new S3Client($config);

# $bucket:バケット名
# $key:S3内のファイルパス
$resurt = $s3->doesObjectExistV2($bucket, $key, false, []) 
if ($resurt === true) {
    echo 'ファイルが存在します。';
} else {
    echo 'ファイルが存在しません。';
}

公式ドキュメントの内容

  • 説明
    オブジェクトの名前が存在するか判断します。このメソッドは、S3のHeadObjectの設定を使用する為、エラーにならないようにバケットとオブジェクトの許可設定を行う必要があります。

  • メソッド名

doesObjectExistV2( string $bucket, string $key, boolean $includeDeleteMarkers = false, array $options = [] )
  • 返り値
    boolean

  • パラメーター

変数 説明
string $bucket The name of the bucket
string $key The key of the object
boolean $includeDeleteMarkers = false Set to true to consider delete markers existing objects.
Using the default value of false will ignore delete markers and return false.t
array $options = [] Additional options available in the HeadObject operation
(e.g., VersionId).
  • 例外
Aws\S3\Exception\S3Exception|Exception
# もし、処理されない例外がある場合

参考資料

0
0
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
0
0