search

Home  >  Q&A  >  body text

Using AWS SDK for PHP 3.x: Get the latest objects in an S3 bucket by last modification time.

<p>I'm trying to get the latest object in a bucket by last modification time using AWS SDK for PHP 3.x. </p> <p>I've seen how to use the AWS CLI to achieve this functionality. Here: </p> <ul> <li>Get the latest object in the S3 bucket by last modification time</li> <li>Get the last modified object from S3 using the AWS CLI</li> </ul> <p>But I don't know how to use PHP SDK to implement this function. </p> <pre class="brush:php;toolbar:false;">$S3Client = new AwsS3S3Client([ 'version' => 'latest', 'region' => 'eu-west-3', 'credentials' => [ 'key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx', ] ]); $startTime = strtotime('-5 minutes'); $res = $S3Client->ListObjectsV2([ 'Bucket' => 'my-bucket', 'Prefix' => 'objects/', 'StartAfter' => $startTime ]) </pre> <p>I am using the recommended ListObjectsV2 method. </p><p>I have three questions. </p><p><br /></p> <ol> <li><p>How should I sort the results by LastModified? (Just like you can do in the CLI)</p> </li> <li><p>I have some lifecycle policies that affect my searches because I get some results that are moved to GLACIER stored objects, which I don't want. </p> </li> <li><p>I want to get the tags and metadata of an object. How should I get it? Do you want to use x-amz-optional-object-attributes? how to use? </p> </li> </ol> <p>By the way, using the StartAfter parameter doesn't seem to change anything. </p>
P粉262113569P粉262113569493 days ago525

reply all(1)I'll reply

  • P粉068486220

    P粉0684862202023-07-29 09:09:26

    • You need to implement this sorting logic in your code, S3Client/AWS does not support this feature by default. This also means you need to list all objects (not just the first 1000) before you can sort them to find the newest object.
    • The StorageClass property is included in the results and you can/need to filter them before sorting or further processing the results.
    • This is not possible by just listing the operations. You need to submit a separate GetObject request for each object you are interested in. If you want to get metadata for thousands of objects simultaneously, you'll need to rethink your approach, and probably store such data in a proper queryable/searchable database.

    reply
    0
  • Cancelreply