All Products
Search
Document Center

Object Storage Service:Simple upload (PHP SDK V2)

Last Updated:Aug 05, 2025

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-hangzhou for 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:PutObject permission. 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

Upload a string

You can use the following code to upload a string 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)
];

// Convert the argument descriptions to the long option format required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added to the end of each argument to indicate that the argument requires a value.
}, 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.

// 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);

// The data to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = Oss\Utils::streamFor($data); // Set the request body to the data stream.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL .  // The request ID.
    'etag: %s' . PHP_EOL,         // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Upload a byte array

You can use the following code to upload a byte array 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)
];

// Convert the argument descriptions to the long option format required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added to the end of each argument to indicate that the argument requires a value.
}, 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.

// 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);

// The byte data to upload.
$dataBytes = [72, 101, 108, 108, 111, 32, 79, 83, 83]; // The ASCII values of 'Hello OSS'.
$dataString = implode(array_map('chr', $dataBytes)); // Convert the byte array to a string.

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = Oss\Utils::streamFor($dataString); // Set the request body to the data stream.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL .  // The request ID.
    'etag: %s' . PHP_EOL,         // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Upload a network stream

You can use the following code to upload a network stream 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)
];

// Convert the argument descriptions to the long option format required by getopt.
$longopts = \array_map(function ($key) {
    return "$key:"; // A colon (:) is added to the end of each argument to indicate that the argument requires a value.
}, 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.

// 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);

// Obtain the content of the network file.
$url = 'https://www.aliyun.com/';
$response = file_get_contents($url);

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->body = Oss\Utils::streamFor($response); // Set the request body to the data stream.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL . // The HTTP status code.
    'request id: %s' . PHP_EOL .  // The request ID.
    'etag: %s' . PHP_EOL,         // The ETag of the object.
    $result->statusCode,
    $result->requestId,
    $result->etag
);

Display the upload progress when you upload a file

You can use the following code to display the upload progress when you upload a file.

<?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)
];

// 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";
        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.

// Use EnvironmentVariableCredentialsProvider to load the access credential from environment variables.
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly set.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load 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 the endpoint argument is provided in the command line, use the specified endpoint.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSS client instance.
$client = new Oss\Client($cfg);

// Define the data to upload.
$data = 'Hello OSS';

// Create a PutObjectRequest object and specify the bucket and object key.
$request = new Oss\Models\PutObjectRequest($bucket, $key);

// Convert the data to a stream object.
$request->body = Oss\Utils::streamFor($data);

// Set the upload progress callback function.
$request->progressFn = function (int $increment, int $transferred, int $total) {
    echo sprintf("Uploaded: %d" . PHP_EOL, $transferred); // The number of bytes that have been uploaded.
    echo sprintf("Uploaded in this operation: %d" . PHP_EOL, $increment);   // The number of bytes uploaded in this operation.
    echo sprintf("Total: %d" . PHP_EOL, $total);       // The total size of the data.
    echo '-------------------------------------------' . PHP_EOL; // The separator.
};

// Call the putObject method to upload the object.
$result = $client->putObject($request);

// Print the upload result.
printf(
    'status code: %s' . PHP_EOL, $result->statusCode . // The HTTP response status code.
    'request id: %s' . PHP_EOL, $result->requestId .   // The request ID.
    'etag: %s' . PHP_EOL, $result->etag                // The ETag of the object.
);

Set a callback function when you upload a file

OSS can send a callback to an application server after a simple upload is complete. To enable this feature, include the callback parameters in the request that you send to OSS.

You can use the following code to set a callback function when you upload a file.

<?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)
];

// 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.

// 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);

// Define the information about the callback server.
// callbackUrl: The URL of the server that receives callback requests.
// callbackHost: The hostname of the callback server.
// callbackBody: The template that is used to define the callback content. Dynamic placeholder replacement is supported.
// callbackBodyType: The format of the callback content.
$callback = base64_encode(json_encode(array(
    'callbackUrl' => 'yourCallbackServerUrl', // Replace the value with the actual URL of the callback server.
    'callbackHost' => 'yourCallbackServerHost', // Replace the value with the actual hostname of the callback server.
    'callbackBody' => 'bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}',
    'callbackBodyType' => "application/x-www-form-urlencoded", // The format of the callback content.
)));

// Define custom variables to pass additional information in the callback.
$callbackVar = base64_encode(json_encode(array(
    'x:var1' => "value1", // Custom variable 1.
    'x:var2' => 'value2', // Custom variable 2.
)));

// Create a PutObjectRequest object to upload the object.
$request = new Oss\Models\PutObjectRequest(bucket: $bucket, key: $key);
$request->callback = $callback; // Set the callback information.
$request->callbackVar = $callbackVar; // Set the custom variables.

// Perform the upload operation.
$result = $client->putObject($request);

// Print the upload result.
// Print the HTTP status code, request ID, and callback result 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.
    'callback result:' . var_export($result->callbackResult, true) . PHP_EOL // The details of the callback result.
);

References