All Products
Search
Document Center

Object Storage Service:Simple download (PHP SDK V2)

Last Updated:Aug 05, 2025

This topic describes how to use the simple download method to download an object from a bucket to a local file. This method is straightforward and suitable for quickly downloading objects from OSS to your local computer.

Precautions

  • The sample code in this topic uses the China (Hangzhou) region (Region ID: cn-hangzhou) as an example. By default, an Internet endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about the regions and endpoints that OSS supports, see OSS regions and endpoints.

  • To download an object to a local file, you must have the oss:GetObject permission. For more information, see Grant custom access policies to RAM users.

  • This topic provides an example of how to obtain access credentials from environment variables. For more information about how to configure access credentials, see Configure access credentials for PHP.

Sample code

You can use the following code to download an object from a bucket to a local file.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client 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);

// Execute the get object operation.
$result = $client->getObject($request);

// Define the path of the local file to be saved.
$localFilePath = 'path/to/local/file.txt'; // Replace it with the actual file path.

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

// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL  // The request ID, which is used for debugging or tracking requests.
);

Scenarios

Conditional download

When you download an object from a bucket, you can specify conditions based on the object's last modified time or ETag. An ETag is an identifier for the file content. The download operation is performed only if these conditions are met. If the conditions are not met, an error is returned and the download is not triggered. Conditional downloads can reduce unnecessary network traffic and resource consumption, and improve download efficiency.

The following table describes the conditions that OSS supports.

Note
  • You can specify If-Modified-Since and If-Unmodified-Since in the same request. You can also specify If-Match and If-None-Match in the same request.

  • You can call the ossClient.getObjectMeta method to obtain the ETag.

Parameter

Description

IfModifiedSince

If the specified time is earlier than the actual modification time of the object, the object is downloaded. Otherwise, the 304 Not Modified error is returned.

IfUnmodifiedSince

If the specified time is the same as or later than the actual modification time of the object, the object is downloaded. Otherwise, the 412 Precondition Failed error is returned.

IfMatch

If the specified ETag matches the ETag of the OSS object, the object is downloaded. Otherwise, the 412 Precondition Failed error is returned.

IfNoneMatch

If the specified ETag does not match the ETag of the OSS object, the object is downloaded. Otherwise, the 304 Not Modified error is returned.

The following sample code shows how to perform a conditional download.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

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

// Assume that the last modified time of the object is 18:43:02 on October 21, 2024. If the specified UTC time is earlier than this time, the IfModifiedSince condition is met and the download is triggered.
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";

// Assume that the ETag is e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855. If the specified ETag is the same as the ETag of the object, the IfMatch condition is met and the download is triggered.
$etag = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

// Create a GetObjectRequest object to obtain the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
            bucket: $bucket,
            key: $key,
            ifModifiedSince: $ifModifiedSince,
            ifMatch: $etag);

// Execute the get object operation.
$result = $client->getObject($request);

// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used for debugging or tracking requests.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);

Streaming download

The following code shows how to enable streaming download by setting the stream parameter when you call the GetObject operation.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

// Check whether the required parameters exist.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information of the parameter.
        echo "Error: the following arguments are required: --$key, $help";
        exit(1); // If a required parameter is missing, exit the program.
    }
}

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Use EnvironmentVariableCredentialsProvider to load access credentials from environment variables.
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly set.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.

// If the endpoint parameter is provided in the command line, use the specified endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Create a GetObjectRequest object and specify the bucket and object key.
$request = new Oss\Models\GetObjectRequest(bucket: $bucket, key: $key);

// Call the getObject method to download the object. Set the stream option to true to process large files in a stream.
$result = $client->getObject(request: $request, args: ['request_options' => ['stream' => true]]);

// Obtain the stream object.
$stream = $result->body;

// Read the stream content (in chunks).
while (!$stream->eof()) { // Check whether the stream has ended.
    echo $stream->read(1024); // Read 1 KB of data at a time and output the data.
}

Display the download progress

The following code shows how to display the download progress when you call the GetObject operation.

<?php

// Import the autoloader file to ensure that dependency libraries are correctly loaded.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

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

// Convert the parameter description to the long option format required by getopt.
// A colon ":" after each parameter indicates that the parameter requires a value.
$longopts = \array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Extract values from the parsed parameters.
$region = $options["region"]; // The region where the bucket is located.
$bucket = $options["bucket"]; // The bucket name.
$key = $options["key"];       // The object name.

// Load the credential information from environment variables.
// Use EnvironmentVariableCredentialsProvider to read the Access Key ID and Access Key Secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region where the bucket is located.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint.
}

// Create an OSS client 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,
);

# Set the progress callback function to display the download progress information.
$request->progressFn = static function (int $increment, int $transferred, int $total) {
    echo sprintf("Downloaded: %d" . PHP_EOL, $transferred);
    echo sprintf("Current download: %d" . PHP_EOL, $increment);
    echo sprintf("Total data: %d" . PHP_EOL, $total);
    echo '-------------------------------------------' . PHP_EOL;
};

// Execute the get object operation.
$result = $client->getObject($request);

// Print the result.
// Output the HTTP status code, request ID, and object content.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. For example, 200 indicates that the request is successful.
    'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used for debugging or tracking requests.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);

References

  • For the complete sample code that is used to download an object to a local file, see the GitHub sample.