Use the OSS PHP SDK to download an object directly into memory as a string, without writing it to disk.
Prerequisites
Before you begin, make sure you have:
Set the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables with valid credentialsThe required permissions on the target object (see Permissions)
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users and RAM roles have no permissions by default. Grant the required permissions using a RAM Policy or Bucket Policy.
| API | Action | Required when |
|---|---|---|
| GetObject | oss:GetObject | Always required to download an object |
| GetObject | oss:GetObjectVersion | Downloading a specific version by versionId |
| GetObject | kms:Decrypt | Object metadata includes X-Oss-Server-Side-Encryption: KMS |
Download an object to memory
The following example downloads an object from OSS. getObject() returns the object body directly as a plain string — no additional unwrapping or stream reading is required.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
// Load credentials from environment variables.
// Set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET before running this example.
$provider = new EnvironmentVariableCredentialsProvider();
// Replace with your actual endpoint and region.
// This example uses the China (Hangzhou) public endpoint.
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$bucket = "yourBucketName";
$object = "yourObjectName";
try {
$config = [
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"region" => "cn-hangzhou",
];
$ossClient = new OssClient($config);
// Returns the object body as a string.
$content = $ossClient->getObject($bucket, $object);
} catch (OssException $e) {
printf("Download failed: %s\n", $e->getMessage());
return;
}
print($content);Replace the placeholder values before running the code:
| Placeholder | Description | Example |
|---|---|---|
yourBucketName | Name of the bucket that stores the object | my-bucket |
yourObjectName | Full key (path) of the object in the bucket | images/photo.jpg |
Data stored in memory is volatile and is lost if power is disconnected. To save the downloaded content to disk instead, see Download objects as files.
Endpoint and client configuration
This example uses the public endpoint for the China (Hangzhou) region (
oss-cn-hangzhou.aliyuncs.com). If your application runs inside Alibaba Cloud in the same region, use the internal endpoint. For a full list of regions and endpoints, see Regions and endpoints.To create an OSSClient instance using a custom domain or Security Token Service (STS), see Create an OSSClient instance.