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:GetObjectpermission. 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
References
For the complete sample code that is used to download an object to a local file, see the GitHub sample.