Delete single file

	//Create S3 connection
	$sdk = new Aws\Sdk([
			'version' => 'latest',
			'region'  => 'eu-west-1',				//<<<<< REGION
			'credentials' => [
					'key'    => $AwsS3AccessKeyId,				//<<<<< S3 ACCESS KEY ID
					'secret' => $AwsS3AccessSecretKey,		//<<<<< S3 SECRET ACCESS KEY
			],
	]);
	$s3Client = $sdk->createS3();

	try
	{
		$result = $s3Client->deleteObject([
				'Bucket' => $AwsS3BucketName,
				'Key' => $S3Filename
		]);
	}
	catch (S3Exception $e)
	{
		echo $e->getMessage();
	}
	catch (Exception $e)
	{
		echo $e->getMessage();
	}

Delete files based on date

  //----- DELETE OLD S3 FILES -----
  try
  {
    
    //----- SETUP AWS SDK FOR S3 ACCESS -----
    $sdk = new Aws\Sdk([
        'version' => 'latest',
        'region'  => 'us-west-2',
        'credentials' => [
            'key'    => AWS_S3_ACCESS_KEY_ID,				//<<<<< S3 ACCESS KEY ID
            'secret' => AWS_S3_ACCESS_SECRET_KEY,		//<<<<< S3 SECRET ACCESS KEY
        ],
    ]);
    $s3Client = $sdk->createS3();
    
    //----------------------------------------------
    //----- DELETE ANY OLD FILES IN THE BUCKET -----
    //----------------------------------------------
    //If a file hasn't been imported then it didn't get added to the database properly so should be cleaned up at some point
    $objects = $s3Client->getIterator('ListObjects', array(
        "Bucket" => AWS_S3_BUCKET_NAME		//<<<<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.
      }

      if ($FileDaysOld > 30)			//<<<< DELETE FILES OLDER THAN
      {
        //----- DELETE FILE -----
        $result = $s3Client->deleteObject([
            'Bucket' => AWS_S3_BUCKET_NAME,
            'Key' => $filename
        ]);		
      }
    }	//foreach ($objects as $object)

    }
    catch (Exception $e)
    {
        	
    }
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 *