All Products
Search
Document Center

Object Storage Service:Range download (PHP SDK V2)

Last Updated:Aug 05, 2025

This topic describes how to use the range download method to efficiently retrieve a specific part of a file.

Prerequisites

  • The sample code in this topic uses the public endpoint for the China (Hangzhou) (cn-hangzhou) region as an example. If you access OSS from another Alibaba Cloud service in the same region, use an internal endpoint. For more information about the mappings between OSS-supported regions and endpoints, see OSS regions and endpoints.

  • To use range download, you must have the oss:GetObject permission. For more information, see Grant custom access policies to RAM users.

Important
  • Assume that you have an object that is 1,000 bytes in size. The valid download range is 0 to 999. If you specify an invalid range, the Range header does not take effect. A 200 OK status code is returned, and the entire object is transferred. The following are examples of invalid requests and their responses:

    • If you specify `Range: bytes=500-2000`, the end of the range is invalid. The entire file is returned, and the HTTP status code is 200.

    • If you specify `Range: bytes=1000-2000`, the start of the range is invalid. The entire file is returned, and the HTTP status code is 200.

  • You can add the x-oss-range-behavior:standard request header to change the download behavior of OSS when an invalid range is specified. Assume that you have an object that is 1,000 bytes in size:

    • If you specify `Range: bytes=500-2000`, the end of the range is invalid. The content in the range of 500 to 999 bytes is returned, and the HTTP status code is 206.

    • If you specify `Range: bytes=1000-2000`, the start of the range is invalid. An HTTP status code of 416 is returned, and the error code is InvalidRange.

Sample code

The following sample code shows how to download data from a specified range of a file by adding the RangeBehavior:standard request header.

<?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 arguments.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region where the bucket is located. This parameter is required.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint. This parameter is optional.
    "bucket" => ['help' => 'The name of the bucket', 'required' => True], // The bucket name. This parameter is required.
    "key" => ['help' => 'The name of the object', 'required' => True], // The object name. This parameter is required.
];

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

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

// Verify that all required arguments are specified.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Obtain the help information for the argument.
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // If a required argument is missing, exit the program.
    }
}

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

// Load the credentials 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 credentials 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);

// Specify the standard download behavior. In this example, the value is set to 'standard'.
$rangeBehavior = 'standard';

// Specify the Range request header to retrieve a part of the object.
$rangeHeader = 'bytes=0-10';

// Create a GetObjectRequest object to retrieve the content of the specified object.
$request = new Oss\Models\GetObjectRequest(
            bucket: $bucket,
            key: $key,
            rangeBehavior: $rangeBehavior,
            rangeHeader: $rangeHeader);

// Execute the GetObject 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 request tracking.
    'object content:' . $result->body->getContents() . PHP_EOL // The object content.
);