All Products
Search
Document Center

Object Storage Service:Simple upload

Last Updated:Jul 08, 2025

This topic describes how to quickly upload local files to Object Storage Service (OSS) using simple upload. This method is straightforward and suitable for scenarios where you need to quickly upload local files.

Considerations

  • In this topic, the region ID cn-hangzhou of China (Hangzhou) is used as an example. By default, the public endpoint is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use the internal endpoint. For more information about the mapping between regions and endpoints supported by OSS, see OSS regions and endpoints.

  • To perform simple upload, you must have the oss:PutObject permission. For more information, see Grant custom permissions to a Resource Access Management (RAM) user.

  • In this topic, access credentials obtained from environment variables are used. For more examples of how to configure access credentials, see Configure access credentials for PHP.

Sample code

The following sample code demonstrates how to upload a local file to a bucket:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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.
    "file" => ['help' => 'Local path to the file you want to upload.', 'required' => True], // (Required) Specify the path of the local file.
];

// Convert the parameter descriptions to a long options list 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 command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$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
$file = $options["file"];     // The path of the local file

// 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 configurations of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

// Create an OSSClient 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 local file and prepare for the upload
// Use fopen to open the local file in read-only mode and convert the file content into a stream by using Utils::streamFor
$body = Oss\Utils::streamFor(fopen($file, 'r'));

// Create a PutObjectRequest object to upload the local 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);

// Display the result of the simple upload request
// Display the HTTP status code, request ID, and ETag, to check whether the request is successful
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code, such as 200, which indicates that the request is successful
    'request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request
    'etag:' . $result->etag . PHP_EOL               // The ETag of the object, which is used to identify the uniqueness of the object
);

Scenarios

Upload a string

The following sample code demonstrates how to upload a string to a bucket:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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 to a long options list required by getopt
$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 command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$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 configurations of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

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

// Specify the data that you want to upload
$data = 'Hello OSS';

// Create a PutObjectRequest object to upload the data
$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);

// Display the result of the simple upload request
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

The following sample code demonstrates how to upload a byte array to a bucket:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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 to a long options list required by getopt
$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 command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$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 configurations of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

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

// Specify the byte array that you want 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

// Execute the simple upload request
$result = $client->putObject($request);

// Display the result of the object upload operation
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

The following sample code demonstrates how to upload a network stream to a bucket:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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 to a long options list required by getopt
$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 command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help" . PHP_EOL;
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$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 configurations of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

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

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

// Execute the simple upload request
$result = $client->putObject($request);

// Display the result of the simple upload request
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

The following sample code demonstrates how to query the upload progress of an object:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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 to a long options list 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 command line parameters
$options = getopt("", $longopts);

// Check whether the required parameters are configured
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help']; // Get the help information for the parameter
        echo "Error: the following arguments are required: --$key, $help";
        exit(1); // Exit the program if a required parameter is missing
    }
}

// Extract parsed arguments and use them
$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

// Use EnvironmentVariableCredentialsProvider to retrieve the AccessKey ID and AccessKey secret from environment variables
// Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are correctly configured
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configurations of the SDK
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located

// If the endpoint parameter is provided, specify a custom domain name
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

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

// Specify the data content that you want to upload
$data = 'Hello OSS';

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

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

// Specify 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 transfer: %d" . PHP_EOL, $increment);   // The increment of bytes in this upload
    echo sprintf("Total size: %d" . PHP_EOL, $total);       // The total size of the data
    echo '-------------------------------------------'. PHP_EOL; // The dotted line delimiter
};

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

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

Configure upload callback

OSS can send callbacks to the application server when simple upload tasks are completed. To implement callback, you only need to send a request that contains relevant callback parameters to OSS.

The following sample code demonstrates how to configure a callback when you upload a local file:

<?php

// Include the autoload file so that the required dependencies can be loaded
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.
    "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 to a long options list 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']; // Get the help information for the parameter
        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); // Set the credentials provider
$cfg->setRegion($region); // Set the region in which the bucket is located
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // If an endpoint is provided, set the endpoint
}

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

// Specify the information about the callback server
// Specify the callback URL, which is the address of the server that receives the callback request
// Specify the callback host, which is the hostname of the callback server
// Specify the callback body, which is the template that is used to specify the callback content. A dynamic placeholder is supported
// Specify the type of the callback body, which is the format of the callback content
$callback = base64_encode(json_encode(array(
    'callbackUrl' => yourCallbackServerUrl, // Replace yourCallbackServerUrl with the actual callback server URL
    'callbackHost' => 'CallbackHost', // Replace CallbackHost with the actual callback server hostname
    '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", // Specify the format of the callback content
)));

// Specify custom variables to pass additional information in the callback
$callbackVar = base64_encode(json_encode(array(
    'x:var1' => "value1", // Specify the first custom variable
    'x:var2' => 'value2', // Specify the second custom variable
)));

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

// Display the result of the object upload operation
// Display the HTTP status code, the request ID, and the callback result to check whether the request is successful
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The HTTP status code, such as 200, which indicates that the request is successful
    'request id:' . $result->requestId . PHP_EOL .   // The request ID, which is used to debug or track the request
    'callback result:' . var_export($result->callbackResult, true) . PHP_EOL // The detailed information about the callback result
);

References

  • For the complete sample code for simple upload, see GitHub.