Seeing if object exists in S3 using PHP Seeing if object exists in S3 using PHP php php

Seeing if object exists in S3 using PHP


Gets whether or not the specified Amazon S3 object exists in the specified bucket.

AmazonS3 doesObjectExist

$s3 = new AmazonS3();$bucket = 'my-bucket' . strtolower($s3->key);$response = $s3->doesObjectExist($bucket, 'test1.txt');// Success? (Boolean, not a CFResponse object)var_dump($response);


try to use code below:

$s3 = new S3();$info = $s3->getObjectInfo($bucket, $filename);if ($info){    echo 'File exists';}else{    echo 'File does not exists';}

download the S3 SDK from amazon for php. There is a class called S3; create an object of S3. The object will allow to call the getObjectInfo() method. Pass your S3 bucket name and the file name (often the file name is referred as key). The getObjectInfo() method will return some information if the file exists, otherwise the method will return FALSE.


Please note that the other suggestions are based on version 1 of the AWS SDK for PHP. For version 2, you'll want to be familiar with the latest guide found here:

http://docs.aws.amazon.com/aws-sdk-php/guide/latest/index.html

The "Getting Started" section in the link above will help you get the SDK installed and setup, so be sure to take your time reading through those docs if you haven't done so already. When you're done with the setup, you'll want to be familiar with the stream wrapper method found here:

http://docs.aws.amazon.com/aws-sdk-php/guide/latest/feature-s3-stream-wrapper.html

Finally, below is a brief, real-life example of how you could use it in the flow of your code.

require('vendor/autoload.php');// your filename$filename = 'my_file_01.jpg';// this will use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY from env vars$s3 = Aws\S3\S3Client::factory();// S3_BUCKET must also be defined in env vars$bucket = getenv('S3_BUCKET')?: die('No "S3_BUCKET" config var in found in env!');// register stream wrapper method$s3->registerStreamWrapper();// does file exist$keyExists = file_exists("s3://".$bucket."/".$filename);if ($keyExists) {    echo 'File exists!';}