Get AWS SDK

Simple include the SDK .phar method 

Download the "aws.phar" file and store it in a subdirectory called, says awssdk.  Then in your php files use:


require 'awssdk/aws.phar';

Define your S3 access values ready to use in your code


		$AwsS3BucketName = '';				//<<<<SET THIS
		$AwsS3AccessKeyId = '';				//<<<<SET THIS
		$AwsS3AccessSecretKey = '';		//<<<<SET THIS

(Remember if you define them globally then you need to define them as global variables in functions which use them)

These values are created here.

No you can create the S3 client:


		$sdk = new Aws\Sdk([
				'version' => 'latest',
				'region'  => 'us-west-2',
				'credentials' => [
						'key'    => $AwsS3AccessKeyId,				//<<<<< S3 ACCESS KEY ID
						'secret' => $AwsS3AccessSecretKey,		//<<<<< S3 SECRTET ACCESS KEY
				],
		]);

		$s3Client = $sdk->createS3();

Methods

http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html

List All Files In A bucket


		//----- LIST CONTENTS OF BUCKET -----
		$objects = $s3Client->getIterator('ListObjects', array(
				"Bucket" => $AwsS3BucketName		//<<<<S3 BUCKET NAME
		));
		foreach ($objects as $object)
		{
			$filename =  $object['Key'];
			$LastModified =  $object['LastModified'];
			
			//Work out how old the file is
			$end = strtotime(date("Y-m-d H:i:s"));		//Now
			$start = strtotime($LastModified);
			if ($start > $end)
			{
				$FileDaysOld = 0;
			}
			else
			{
				$FileDaysOld = floor(abs($end - $start) / 86400);   //ceil rounds the amount of days up to the next full day. Use floor if you want to get the amount of full days between the two dates.
			}

			echo "$filename | $LastModified | $FileDaysOld <br>";
		}

Delete File


	//----- DELETE FILE -----
	$result = $s3Client->deleteObject([
			'Bucket' => $AwsS3BucketName,
			'Key' => $filename
	]);

 

 

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *