Download objects using OSS SDK for PHP 2.0

Updated at:

This topic describes how to download objects from a versioned bucket by using OSS SDK for PHP 2.0.

Notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about supported regions and endpoints, see Regions and endpoints.

  • The oss:GetObject permission is required for downloading objects. For more information, see Grant a custom policy.

Note

When you call the GetObject operation to download an object in a bucket, the following three scenarios apply:

  • If the current version of the object is a delete marker, Object Storage Service (OSS) returns 404 Not Found.

  • If the version ID of the object is specified in the request, OSS returns the specified version of the object. If the version ID is set to null in the request, OSS returns the version whose ID is null.

  • If the version ID specified in the request is the version ID of a delete marker, OSS returns 405 Method Not Allowed.

Sample code

Below is the sample code for downloading objects.

<?php

// Introduce autoload files to load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint that can be used by other services for accessing OSS.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
    "key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];

// Convert the descriptions to a list of long options required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts);

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain help information for the parameters.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if the required parameters are not configured.
    }
}

// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of object.

// Load access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.    
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
                bucket: $bucket,
                key: $key,
                versionId:"yourVersionId",// Specify the version ID of the object.
);

// Query the object.
$result = $client->getObject($request);

// Specify the local path to save the object.
$localFilePath = './test/file.txt'; // Replace this parameter with the actual local file path.

// Write the content to the local file.
file_put_contents($localFilePath, $result->body->getContents());

// Display the result.
// Output the HTTP status code, request ID, and content of the object.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request succeeded.
    'request id:' . $result-> requestId. PHP_EOL // The request ID, which is used to debug or trace a request.
);