All Products
Search
Document Center

Object Storage Service:Simple download (PHP SDK V2)

Last Updated:Mar 20, 2026

Download an object from a bucket to a local file using the OSS SDK for PHP V2.

Prerequisites

Before you begin, make sure that you have:

Usage notes

  • The sample code uses the China (Hangzhou) region (cn-hangzhou) with an Internet endpoint. To access OSS from another Alibaba Cloud service in the same region, use an internal endpoint instead. For supported regions and endpoints, see OSS regions and endpoints.

Download an object to a local file

Call GetObject to download an object and write its content to a local file.

<?php

require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Load access credentials from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion('<region>');           // e.g., cn-hangzhou
// $cfg->setEndpoint('<endpoint>');    // Optional: set a custom endpoint

$client = new Oss\Client($cfg);

$request = new Oss\Models\GetObjectRequest(
    bucket: '<bucket-name>',
    key: '<object-key>'
);

$result = $client->getObject($request);

// Write the object content to a local file.
$localFilePath = '<path/to/local/file.txt>';
file_put_contents($localFilePath, $result->body->getContents());

printf(
    'status code: %s' . PHP_EOL .
    'request ID: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId
);

Replace the following placeholders:

PlaceholderDescriptionExample
<region>Region ID of the bucketcn-hangzhou
<bucket-name>Name of the bucketmy-bucket
<object-key>Key of the object to downloadlogs/app.log
<path/to/local/file.txt>Local path to save the filedownloads/app.log

For the complete runnable sample, see the GitHub sample.

Use cases

Conditional download

Download an object only when it meets conditions based on its last modified time or ETag. If the condition is not met, OSS returns an error and skips the download. This avoids unnecessary network traffic.

The following table describes the supported conditions.

ParameterDownload triggered whenError when condition not met
ifModifiedSinceSpecified time is earlier than the object's last modified time304 Not Modified
ifUnmodifiedSinceSpecified time is the same as or later than the object's last modified time412 Precondition Failed
ifMatchSpecified ETag matches the object's ETag412 Precondition Failed
ifNoneMatchSpecified ETag does not match the object's ETag304 Not Modified
You can combine If-Modified-Since and If-Unmodified-Since in the same request, or combine If-Match and If-None-Match in the same request. To get an object's ETag, call ossClient.getObjectMeta.

The following example sets If-Modified-Since and If-Match conditions on the GetObjectRequest.

// Trigger the download if the object was modified after this time.
$ifModifiedSince = "Sun, 21 Oct 2024 18:43:02 GMT";

// Trigger the download if the object's ETag matches this value.
$etag = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

$request = new Oss\Models\GetObjectRequest(
    bucket: '<bucket-name>',
    key: '<object-key>',
    ifModifiedSince: $ifModifiedSince,
    ifMatch: $etag
);

$result = $client->getObject($request);

printf(
    'status code: %s' . PHP_EOL .
    'request ID: %s' . PHP_EOL .
    'object content: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId,
    $result->body->getContents()
);
The code above assumes the client is already initialized. See Download an object to a local file for client setup.

Streaming download

Enable streaming to process the object body in chunks instead of loading it entirely into memory. This is useful for large objects.

Set stream to true in request_options, then read the response body chunk by chunk using $stream->read().

$request = new Oss\Models\GetObjectRequest(
    bucket: '<bucket-name>',
    key: '<object-key>'
);

// Enable streaming to avoid loading the entire object into memory.
$result = $client->getObject(
    request: $request,
    args: ['request_options' => ['stream' => true]]
);

$stream = $result->body;

while (!$stream->eof()) {
    echo $stream->read(1024); // Read 1 KB at a time.
}
The code above assumes the client is already initialized. See Download an object to a local file for client setup.

Track download progress

Attach a progress callback to the request by setting $request->progressFn. The callback receives three arguments on each invocation:

ArgumentTypeDescription
$incrementintBytes downloaded in the current callback invocation
$transferredintTotal bytes downloaded so far
$totalintTotal size of the object in bytes
$request = new Oss\Models\GetObjectRequest(
    bucket: '<bucket-name>',
    key: '<object-key>'
);

$request->progressFn = static function (int $increment, int $transferred, int $total) {
    echo sprintf("Downloaded so far: %d bytes" . PHP_EOL, $transferred);
    echo sprintf("This chunk: %d bytes" . PHP_EOL, $increment);
    echo sprintf("Total size: %d bytes" . PHP_EOL, $total);
    echo '---' . PHP_EOL;
};

$result = $client->getObject($request);

printf(
    'status code: %s' . PHP_EOL .
    'request ID: %s' . PHP_EOL .
    'object content: %s' . PHP_EOL,
    $result->statusCode,
    $result->requestId,
    $result->body->getContents()
);
The code above assumes the client is already initialized. See Download an object to a local file for client setup.