Upload a file using OSS SDK for PHP 2.0
This topic describes how to upload a file to a versioned Object Storage Service (OSS) bucket by using OSS SDK for PHP V2.
Notes
-
The sample code in this topic uses the region ID
cn-hangzhouof 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 by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints. -
To upload a file, you must have the
oss:PutObjectpermission. For more information, see Grant a custom policy.
Sample code
Simple upload
-
If you upload an object to a versioning-enabled bucket, OSS generates a unique version ID for the object and includes the version ID in the x-oss-version-id response header.
-
If you upload an object to a versioning-suspended bucket, the version ID generated for the object is null. If you upload an object with the same name as an existing object to a versioning-suspended bucket, the existing object is overwritten. This way, each object has only a single version whose version ID is null.
The following sample code performs a simple upload:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Generate a list of long options to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the data that you want to upload.
$data = 'Hello OSS';
// Create a simple upload request.
$request = new Oss\Models\PutObjectRequest(
bucket: $bucket,
key: $key,
);
// Set the request body to the data stream.
$request->body = Oss\Utils::streamFor($data);
// Use the putObject method to upload the data.
$result = $client->putObject($request);
// Display the returned result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId . PHP_EOL . // The request ID.
'etag:' . $result->etag . PHP_EOL // The ETag of the object.
);
Append upload
In a versioned bucket, the AppendObject operation can be performed only on the current version of an appendable object.
-
When you perform the AppendObject operation on the current version of an appendable object, OSS does not generate a previous version for the object.
-
When you perform the PutObject or DeleteObject operation on the current version of an appendable object, OSS saves the appendable object as a previous version that cannot be appended anymore.
-
The AppendObject operation cannot be performed on the current version of a non-appendable object such as a normal object or a delete marker.
The following sample code performs an append upload:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the OSS endpoint.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Generate a list of long options to parse the command-line parameters.
$longopts = \array_map(function ($key) {
return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help"; // Display the required but missing parameters.
exit(1);
}
}
// Obtain the values of the command-line parameters and assign the values to variables.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Load the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);
// Specify the region.
$cfg->setRegion($region);
// If an endpoint is provided, specify the endpoint.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Specify the content that you want to append.
$data = 'Hello Append Object';
// Create an append upload request.
$request = new Oss\Models\AppendObjectRequest(bucket: $bucket, key: $key);
// Set the request body to the data stream.
$request->body = Oss\Utils::streamFor($data);
// Set the append position to 0 to indicate that the append starts from the beginning of the object.
$request->position = 0;
// Call the appendObject method to append the content.
$result = $client->appendObject($request);
// Display the result.
printf(
'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code.
'request id:' . $result->requestId // The request ID.
);
Multipart upload
If you call the CompleteMultipartUpload operation to combine the parts into a complete object in a versioned bucket, OSS generates a unique version ID for the object and returns the version ID as the value of the x-oss-version-id header in the response.
The following sample code performs a multipart upload:
<?php
// Include the autoload file to load dependencies.
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
// Define and describe command-line parameters.
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // (Optional) Specify the endpoint for accessing OSS.
"bucket" => ['help' => 'The name of the bucket', 'required' => True], // (Required) Specify the name of the bucket.
"key" => ['help' => 'The name of the object', 'required' => True], // (Required) Specify the name of the object.
];
// Convert the parameter descriptions into the long options format required by getopt.
// Add a colon (:) to the end of each parameter to indicate that a value is required.
$longopts = \array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command-line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
$help = $value['help']; // Obtain help information for the parameters.
echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
exit(1); // Exit the program if a required parameter is missing.
}
}
// Obtain values from the parsed parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.
$key = $options["key"]; // The name of the object.
// Obtain access credentials from environment variables.
// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Use the default configuration of the SDK.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Specify the credential provider.
$cfg->setRegion($region); // Specify the region in which the bucket is located.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]); // Specify the endpoint if one is provided.
}
// Create an OSSClient instance.
$client = new Oss\Client($cfg);
// Create a request to initiate the multipart upload task.
$request = new Oss\Models\InitiateMultipartUploadRequest(bucket: $bucket, key: $key);
$result = $client->initiateMultipartUpload($request);
// Obtain the upload ID of the multipart upload task.
$uploadId = $result->uploadId;
// Create an UploadPartRequest object to upload the object.
$request = new Oss\Models\UploadPartRequest(bucket: $bucket, key: $key);
// Specify the path of the local file and the part size.
$bigFileName = "/Users/localpath/yourfilename"; // Specify the path of the local file.
$partSize = 1 * 1024 * 1024; // Specify the size of the parts. Unit: bytes. In this example, this parameter is set to 1 MB.
// Open the local file and prepare for the multipart upload task.
$file = fopen($bigFileName, 'r');
$parts = []; // Create a container for holding parts.
if ($file) {
$i = 1; // Specify the part number starting from 1.
while (!feof($file)) {
$chunk = fread($file, $partSize); // Read a chunk of the specified part size.
// Perform the multipart upload operation.
$partResult = $client->uploadPart(
new Oss\Models\UploadPartRequest(
bucket: $bucket,
key: $key,
partNumber: $i, // Specify the number of the part.
uploadId: $uploadId, // Specify the upload ID of the multipart upload task.
contentLength: null,
contentMd5: null,
trafficLimit: null,
requestPayer: null,
body: Oss\Utils::streamFor(resource: $chunk) // Convert data chunks into streams.
)
);
// Create an UploadPart object to record the part number and ETag.
$part = new Oss\Models\UploadPart(
partNumber: $i,
etag: $partResult->etag,
);
array_push($parts, $part); // Add the part information to the array.
$i++; // Increment the part number.
}
fclose($file); // Close the file handle.
}
// Complete the multipart upload task.
$comResult = $client->completeMultipartUpload(
new Oss\Models\CompleteMultipartUploadRequest(
bucket: $bucket,
key: $key,
uploadId: $uploadId, // Specify the upload ID of the multipart upload task.
acl: null,
completeMultipartUpload: new Oss\Models\CompleteMultipartUpload(
parts: $parts // Provide all parts.
),
)
);
// Display the result of the multipart upload task.
printf(
'status code:' . $comResult->statusCode . PHP_EOL . // The HTTP status code. For example, HTTP status code 200 indicates that the request is successful.
'request id:' . $comResult->requestId . PHP_EOL . // The request ID, which is used to debug or trace the request.
'complete multipart upload result:' . var_export($comResult, true) // The details of the multipart upload result.
);
Related topics
-
For more information about the API operation for a simple upload, see PutObject.
-
For more information about the API operation for an append upload, see AppendObject.
-
For more information about the API operation for a multipart upload, see CompleteMultipartUpload.