Download objects using OSS SDK for PHP 2.0

Updated at:

Use OSS SDK for PHP 2.0 to download objects from a versioned bucket.

Prerequisites

Before you begin, make sure you have:

How it works

When you call GetObject on a versioned bucket, the behavior depends on whether you specify a version ID and whether that version is a delete marker:

RequestResponse
No version ID specified, current version is a delete marker404 Not Found
Version ID specified, version is a regular objectReturns that specific version
Version ID is null, a null version existsReturns the null version
Version ID specified, version is a delete marker405 Method Not Allowed

Download an object

The following example downloads a specific version of an object by setting versionId in GetObjectRequest, then saves the object content to a local file.

Note

The sample code uses the region ID cn-hangzhou (China (Hangzhou)). By default, a public endpoint is used. To access OSS from another Alibaba Cloud service in the same region, set an internal endpoint. For endpoint details, see OSS regions and endpoints.

<?php

// Load dependency libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Define command-line arguments.
$optsdesc = [
    "region"   => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket"   => ['help' => 'The name of the bucket.', 'required' => True],
    "key"      => ['help' => 'The name of the object.', 'required' => True],
];

// Parse command-line arguments.
$longopts = \array_map(function ($key) { return "$key:"; }, array_keys($optsdesc));
$options  = getopt("", $longopts);

// Validate required arguments.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        echo "Error: the following arguments are required: --$key, " . $value['help'] . PHP_EOL;
        exit(1);
    }
}

$region = $options["region"];
$bucket = $options["bucket"];
$key    = $options["key"];

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

// Configure the client.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Build the request. Set versionId to download a specific version.
// To download the current version, omit versionId.
$request = new Oss\Models\GetObjectRequest(
    bucket:    $bucket,
    key:       $key,
    versionId: "yourVersionId",  // Replace with the actual version ID.
);

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

// Save the object content to a local file.
$localFilePath = './test/file.txt';  // Replace with the actual local file path.
file_put_contents($localFilePath, $result->body->getContents());

// Print the HTTP status code and request ID.
// HTTP 200 indicates the download succeeded.
printf(
    'status code: ' . $result->statusCode . PHP_EOL .
    'request ID: '  . $result->requestId  . PHP_EOL
);

Key parameters

ParameterRequiredDescription
regionYesThe region where the bucket is located, for example, cn-hangzhou
bucketYesThe name of the bucket
keyYesThe name of the object
endpointNoA custom endpoint. If not set, the SDK derives the endpoint from region
versionIdNoThe version ID of the object to download. Omit this parameter to download the current version