This topic describes how to use the simple upload method to upload local files to OSS. This method is a straightforward way to quickly upload files to cloud storage.
Precautions
The sample code in this topic uses the region ID
cn-hangzhoufor the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.To perform a simple upload, you must have the
oss:PutObjectpermission. For more information, see Attach a custom policy to a RAM user.The examples in this topic show how to read 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 upload a local file to a destination bucket.
<?php
// Import the autoloader file to ensure that dependency libraries can be loaded correctly.
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. (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)
"file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // The path of the local file. (Required)
];
// Convert the argument descriptions to the long option format required by getopt.
// A colon (:) is added to the end of each argument to indicate that the argument requires a value.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line arguments.
$options = getopt("", $longopts);
// Check whether required arguments exist.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain the help information of the argument.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // If a required argument is not specified, 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.
$file = $options["file"]; // The path of the local file.
// Load the access credential from the environment variable.
// 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);
// Check whether the file exists.
if (!file_exists($file)) {
echo "Error: The specified file does not exist." . PHP_EOL; // If the file does not exist, print an error message and exit.
exit(1);
}
// Open the file and prepare for upload.
// Use fopen to open the file in read-only mode and use Utils::streamFor to convert the file content to a stream.
$body = Oss\Utils::streamFor(fopen($file, 'r'));
// Create a PutObjectRequest object to upload the file.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = $body; // Set the request body to the file stream.
// Perform the upload operation.
$result = $client->putObject($request);
// Print the upload result.
// Print the HTTP status code, request ID, and ETag to verify that the upload is successful.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code. A status code of 200 indicates that the operation is successful.
'request id:' . $result->requestId . PHP_EOL . // The request ID, which is used to debug or trace the request.
'etag:' . $result->etag . PHP_EOL // The ETag of the object, which is used to identify the unique object.
);
Common scenarios
References
For the complete sample code for a simple upload, see GitHub example.