All Products
Search
Document Center

ApsaraVideo VOD:Upload files using the PHP SDK

Last Updated:Aug 07, 2026

This topic provides detailed examples of how to use the server-side upload software development kit (SDK) for PHP to upload various media files to storage in ApsaraVideo VOD.

Overview

Note

A B/S (Browser/Server) architecture is recommended for PHP development.

The PHP upload SDK follows the general process of the ApsaraVideo VOD server-side SDK. For more information, see Upload process. The basic process of using the PHP upload SDK is as follows:

  1. Complete the prerequisites. For more information, see Prerequisites.

  2. Integrate the PHP upload SDK. For more information, see Integrate the PHP upload SDK.

  3. Implement the upload logic, which involves configuring upload information.

  4. The default endpoint for the PHP upload SDK is cn-shanghai (Shanghai). To upload media files to other regions, you can specify the region when you initialize AliyunVodUploader. For more information about the endpoints supported by ApsaraVideo VOD, see Endpoints.

    The following example shows how to set the upload region to cn-beijing (Beijing):

    $apiRegionId = 'cn-beijing';  // The destination region for the upload.
    $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret, $apiRegionId);

Prerequisites

  • ApsaraVideo VOD is activated. For more information, see Activate ApsaraVideo VOD.

  • The system settings required for the upload, including the storage path in the specified region and the callback settings, are configured. For more information, see Manage storage buckets and Configure callbacks.

  • A RAM user is created and used to access ApsaraVideo VOD. To prevent security risks caused by the leakage of the AccessKey pair of your Alibaba Cloud account, we recommend that you create a RAM user and grant the RAM user the permissions required to access ApsaraVideo VOD. Then, you can use the AccessKey pair of the RAM user to access ApsaraVideo VOD. For more information, see Create a RAM user and grant permissions.

  • Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables. For more information, see Configure environment variables in Linux, macOS, and Windows.

    Important
    • An Alibaba Cloud account AccessKey pair has permissions on all API operations. Use a RAM user's AccessKey pair to call API operations or perform routine O&M.

    • Do not hard-code your AccessKey ID and AccessKey secret in project code. If leaked, all resources in your account are compromised.

  • Optional. A role is created for the RAM user and the role is granted the permissions required to access ApsaraVideo VOD if you want to access ApsaraVideo VOD by using Security Token Service (STS). For more information, see Obtain an STS token.

Integrate the PHP upload SDK

  1. Download the SDK and demo.

  2. Unzip VodUploadSDK-PHP_1.0.3.zip and copy the voduploadsdk folder from the VodUploadSDK-PHP_1.0.3 directory to your project.

PHP upload SDK directory structure

Path: VodUploadSDK-PHP_1.0.3/voduploadsdk/uploader

  • UploadVideoRequest.php

    Directory

    Description

    UploadVideoRequest

    The request class for uploading videos. For more information about the fields, see CreateUploadVideo.

  • UploadImageRequest.php

    Directory

    Description

    UploadImageRequest

    The request class for uploading images. For more information about the fields, see CreateUploadImage.

  • UploadAttachedMediaRequest.php

    Directory

    Description

    UploadAttachedMediaRequest

    The request class for uploading auxiliary media assets. For more information about the fields, see CreateUploadAttachedMedia.

  • AliyunVodUploader.php

    Directory

    Description

    __construct

    Sets the AccessKey for uploads, the ApsaraVideo VOD center, and the endpoint. For more information, see AccessKey and ApsaraVideo VOD region IDs.

    uploadLocalVideo

    The interface for uploading local videos.

    uploadWebVideo

    The interface for uploading web videos.

    uploadLocalImage

    Uploads local images.

    uploadWebImage

    Uploads web images.

    uploadLocalAttachedMedia

    Uploads local auxiliary media assets.

    uploadWebAttachedMedia

    Uploads web auxiliary media assets.

    uploadLocalM3u8

    Uploads local M3U8 files.

    uploadWebM3u8

    Uploads web M3U8 files.

    parseM3u8File

    Parses an M3U8 manifest to get a list of shard addresses.

    setEcsRegionId

    Sets the region where the upload script is deployed on an ECS instance, if applicable. If the region is the same as the ApsaraVideo VOD storage region, internal network upload is automatically enabled.

    setEnableSSL

    Specifies whether to enable SSL (use HTTPS for network requests). It is disabled by default to prevent issues when related extensions are not installed or are configured incorrectly.

    uploadProgressCallback

    The callback function for upload progress. You can rewrite this function. For the method signature and an override example, see below.

    uploadProgressCallback method signature

    public function uploadProgressCallback($mediaId, $consumedBytes, $totalBytes)
    • $mediaId: The media ID.

    • $consumedBytes: The number of bytes uploaded so far.

    • $totalBytes: The total size of the file in bytes.

    To calculate the upload progress percentage, use 100 * ($consumedBytes / $totalBytes). Check that $totalBytes is greater than 0 before dividing to avoid division by zero.

    To display custom upload progress, extend AliyunVodUploader and override this method. The following example shows how:

    class MyAliyunVodUploader extends AliyunVodUploader {
        public function uploadProgressCallback($mediaId, $consumedBytes, $totalBytes) {
            if ($totalBytes > 0) {
                $rate = 100 * (floatval($consumedBytes) / floatval($totalBytes));
            } else {
                $rate = 0;
            }
            echo round($rate, 1) . "%\n";
            flush();
        }
    }
  • AliyunVodUtils.php

    Directory

    Description

    AliyunVodUtils

    A utility class that provides static functions, such as functions to truncate strings, get file extensions, and get file names.

    AliyunVodLog

    A log class for simple printing. `logSwitch` is the log switch.

    AliyunVodDownloader

    Downloads web files.

    AliyunVodReportUpload

    Reports upload progress.

    AliyunVodError

    Defines error codes.

Path: VodUploadSDK-PHP_1.0.3/voduploadsdk

  • aliyun-php-sdk-core: A dependency that provides the base class for the upload SDK. It encapsulates Alibaba Cloud API signing, HTTP requests, and other core functionalities.

  • aliyun-php-sdk-vod: The server-side API SDK for ApsaraVideo VOD. It encapsulates requests for ApsaraVideo VOD APIs.

  • aliyun-php-sdk-oss: A dependency that provides the OSS class for the upload SDK. It encapsulates OSS upload operations and other related functions.

Path: VodUploadSDK-PHP_1.0.3/samples

  • uploadVideo.php: Sample code for uploading videos.

  • uploadImage.php: Sample code for uploading images.

  • uploadAttachedMedia.php: Sample code for uploading auxiliary media assets.

Scenario 1: Upload audio and video files

Standard audio and video files

You can upload the following types of audio and video files:

  • You can upload local files using multipart upload. A single file can be up to 48.8 TB in size. Resumable upload is not supported. For more information, see the `testUploadLocalVideo` function.

  • You can upload web files by specifying a file URL. A single file can be up to 48.8 TB in size. This method requires the web file to be downloaded to a local disk before it is uploaded. Make sure that your local disk has sufficient space. For more information, see the `testUploadWebVideo` function.

Click to view sample code

<?php
/**
 * Created by Aliyun ApsaraVideo VOD.
 */
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';
date_default_timezone_set('PRC');
// Test uploading a local video.
function testUploadLocalVideo($accessKeyId, $accessKeySecret, $filePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
        // CateId is the media category ID. You can view it on the **Category Management** page under **Configuration Management** > **Media Management** in the ApsaraVideo VOD console, or create one by calling the AddCategory operation. For more information, see [Manage media categories](https://www.alibabacloud.com/help/zh/vod/user-guide/manage-video-categories).
        $uploadVideoRequest->setCateId(<your category ID>);
        // Example CoverURL: http://example.com/example****.jpg
        //$uploadVideoRequest->setCoverURL("<your CoverURL>");
        //$uploadVideoRequest->setTags('test1,test2');
        //$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
        $uploadVideoRequest->setTemplateGroupId('your-template-group-id');
        $userData = array(
            // Example Callback: https://demo.aliyundoc.com/ProcessMessageCallback
            "MessageCallback"=>array("CallbackURL"=>"<your callback URL>"),
            "Extend"=>array("localId"=>"xxx", "test"=>"www")
        );
        $uploadVideoRequest->setUserData(json_encode($userData));
        $res = $uploader->uploadLocalVideo($uploadVideoRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadLocalVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
            $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    }
}
// Test uploading a web video.
function testUploadWebVideo($accessKeyId, $accessKeySecret, $fileURL)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($fileURL, 'testUploadWebVideo via PHP-SDK');
        $res = $uploader->uploadWebVideo($uploadVideoRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadWebVideo Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
            $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    }
}

####  Run the test code   ####
// The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. Use the AccessKey pair of a RAM user for API access or daily O&M.
// Do not hard-code the AccessKey ID and AccessKey secret into your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
// This example shows how to use an AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$localFilePath = '/opt/video/sample.mp4';
// testUploadLocalVideo($accessKeyId, $accessKeySecret, $localFilePath);

// Example webFileURL: http://example-bucket-****.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc****/daa30814c0c340cf8199926f78aa****-a0bc05ba62c3e95cc672e88b8281****-ld.mp4?auth_key=1608774986-0-0-c56acd302bea0c331370d8ed6865****
$webFileURL = '<your webFileURL>';
testUploadWebVideo($accessKeyId, $accessKeySecret, $webFileURL);

uploadLocalVideo lets you specify a transcoding template group when you upload a video by calling setTemplateGroupId(). If you specify a transcoding template group ID, the video is automatically transcoded as soon as the upload is complete, and you do not need to call the SubmitTranscodeJobs operation separately. To obtain the transcoding template group ID, go to the Configuration Management > Media Processing Configuration > Transcoding Template Groups page in the VOD console.

M3U8 video files

The following code provides an example:

Click to view sample code

<?php
/**
 * Created by Aliyun ApsaraVideo VOD.
 */
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';
date_default_timezone_set('PRC');
// Test uploading a local M3U8 video.
function testUploadLocalM3u8($accessKeyId, $accessKeySecret, $m3u8FilePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($m3u8FilePath, 'testUploadLocalM3u8 via PHP-SDK');
        // Call the API to parse the list of shard addresses from the M3U8 file. If the parsing result is inaccurate, concatenate the address list yourself. By default, the shard files and the M3U8 file are in the same directory.
        $sliceFiles = $uploader->parseM3u8File($m3u8FilePath);
        //print_r($sliceFiles);
        $res = $uploader->uploadLocalM3u8($uploadVideoRequest, $sliceFiles);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadLocalM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
            $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    }
}

// Test uploading a web M3U8 video.
function testUploadWebM3u8($accessKeyId, $accessKeySecret, $m3u8FileUrl)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($m3u8FileUrl, 'testUploadWebM3u8 via PHP-SDK');
        // Call the API to parse the list of shard addresses from the M3U8 file. If the parsing result is inaccurate, concatenate the address list yourself. By default, the shard files and the M3U8 file are in the same directory.
        $sliceFileUrls = $uploader->parseM3u8File($m3u8FileUrl);
        //print_r($sliceFileUrls);
        $res = $uploader->uploadWebM3u8($uploadVideoRequest, $sliceFileUrls);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadWebM3u8 Failed, ErrorMessage: %s\n Location: %s %s\n Trace: %s\n",
            $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTraceAsString());
    }
}
####  Run the test code   ####
// The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. Use the AccessKey pair of a RAM user for API access or daily O&M.
// Do not hard-code the AccessKey ID and AccessKey secret into your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
// This example shows how to use an AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$localM3u8FilePath = '/opt/video/m3u8/sample.m3u8';
//testUploadLocalM3u8($accessKeyId, $accessKeySecret, $localM3u8FilePath);

// Example webM3u8FileURL: http://example-bucket-****.cn-shanghai.aliyuncs.com/b55b904bc612463b812990b7c8cc****/daa30814c0c340cf8199926f78aa****-195a25af366b5edae324c47e99a0****-ld.m3u8?auth_key=1608775606-0-0-9fb038deaecd009dadd86721c585****
$webM3u8FileURL = '<your webM3u8FileURL>';
//testUploadWebM3u8($accessKeyId, $accessKeySecret, $webM3u8FileURL);

Upload acceleration

To upload large files (in GBs or TBs) or perform cross-region uploads, such as uploading a video from the Chinese mainland to a storage address in the Singapore storage region, you can enable the upload acceleration feature. For more information, see Activation method. After you enable this feature, you must add the AccelerateConfig key-value pair to the UserData object in the upload configuration. If the UserData object does not exist, create it. The following code provides an example:

$userData = array(  
    "AccelerateConfig"=>array("Type"=>"oss","Domain"=>"****Bucket.oss-accelerate.aliyuncs.com"),
);       
$uploadVideoRequest->setUserData(json_encode($userData));

Parameter description

Name

Type

Description

Type

string

The type of upload acceleration to enable. Only `oss` is supported.

Domain

string

The acceleration endpoint for the user's bucket. HTTPS is used by default.

Note

Use an acceleration endpoint assigned after activation, for example, `vod-*******.oss-accelerate.aliyuncs.com`.

Batch upload multiple videos

Each call to uploadLocalVideo or uploadWebVideo uploads only a single video file. Batch upload of multiple videos in a single call is not supported. To upload multiple videos in a batch, call the UploadMediaByUrl operation.

When you batch upload videos on the upload page in the console, the videos are also processed one at a time. If you need to upload large files or a batch of files, we recommend that you use the PC client tool.

Scenario 2: Upload images

Click to view sample code

Click to view sample code

<?php
/**
 * Created by Aliyun ApsaraVideo VoD.
 * User: https://www.aliyun.com/product/vod
 */

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';

date_default_timezone_set('PRC');

// Test uploading a local image.
function testUploadLocalImage($accessKeyId, $accessKeySecret, $filePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadImageRequest = new UploadImageRequest($filePath, 'testUploadLocalImage via PHP-SDK');
        $uploadImageRequest->setCateId(1000009458);
        $res = $uploader->uploadLocalImage($uploadImageRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadLocalImage Failed, ErrorMessage: %s\n", $e->getMessage());
    }

}

// Test uploading a web image.
function testUploadWebImage($accessKeyId, $accessKeySecret, $fileURL)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadImageRequest = new UploadImageRequest($fileURL, 'testUploadWebImage via PHP-SDK');
        $uploadImageRequest->setCateId(1000009458);
        $res = $uploader->uploadWebImage($uploadImageRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadWebImage Failed, ErrorMessage: %s\n", $e->getMessage());
    }

}



####  Run the test code   ####
// The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. Use the AccessKey pair of a RAM user for API access or daily O&M.
// Do not hard-code the AccessKey ID and AccessKey secret into your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
// This example shows how to use an AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

$localFilePath = '/opt/image/test-image.jpg';
//testUploadLocalImage($accessKeyId, $accessKeySecret, $localFilePath);

$webFileURL = 'http://vod-download.cn-shanghai.aliyuncs.com/retina/pic/20180208/496AE240-54AE-4CC8-8578-3EEC8F38****.gif';
testUploadWebImage($accessKeyId, $accessKeySecret, $webFileURL);

Scenario 3: Upload auxiliary media assets

The following code provides an example:

Click to view sample code

Click to view sample code

<?php
/**
 * Created by Aliyun ApsaraVideo VoD.
 * User: https://www.aliyun.com/product/vod
 */

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'voduploadsdk' . DIRECTORY_SEPARATOR . 'Autoloader.php';

date_default_timezone_set('PRC');

// Test uploading a local auxiliary media asset.
function testUploadLocalAttachedMedia($accessKeyId, $accessKeySecret, $filePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadAttachedRequest = new UploadAttachedMediaRequest($filePath, 'watermark',
            'testUploadLocalAttachedMedia via PHP-SDK');
        //$uploadAttachedRequest->setCateId(100000****);
        $res = $uploader->uploadLocalAttachedMedia($uploadAttachedRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadLocalAttachedMedia Failed, ErrorMessage: %s\n", $e->getMessage());
    }

}

// Test uploading a web auxiliary media asset.
function testUploadWebAttachedMedia($accessKeyId, $accessKeySecret, $fileURL)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadAttachedRequest = new UploadAttachedMediaRequest($fileURL, 'watermark',
            'testUploadWebAttachedMedia via PHP-SDK');
        //$uploadAttachedRequest->setCateId(100000****);
        $res = $uploader->uploadWebAttachedMedia($uploadAttachedRequest);
        print_r($res);
    } catch (Exception $e) {
        printf("testUploadWebAttachedMedia Failed, ErrorMessage: %s\n", $e->getMessage());
    }

}


####  Run the test code   ####
// The AccessKey pair of an Alibaba Cloud account has permissions to access all APIs. Use the AccessKey pair of a RAM user for API access or daily O&M.
// Do not hard-code the AccessKey ID and AccessKey secret into your project code. This can lead to an AccessKey pair leak and compromise the security of all resources in your account.
// This example shows how to use an AccessKey pair from environment variables to authenticate API access. Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

$localFilePath = '/opt/image/test.png';
//testUploadLocalAttachedMedia($accessKeyId, $accessKeySecret, $localFilePath);

$webFileURL = 'http://vod-download.cn-shanghai.aliyuncs.com/retina/pic/20180208/496AE240-54AE-4CC8-8578-3EEC8F38****.gif';
testUploadWebAttachedMedia($accessKeyId, $accessKeySecret, $webFileURL);

References

Overview of media upload

Overview of STS SDKs