All Products
Search
Document Center

ApsaraVideo VOD:Use the upload SDK for PHP to upload files

Last Updated:Apr 22, 2024

This topic describes how to use the upload SDK for PHP to upload media files to ApsaraVideo VOD for storage.

Upload process

The upload SDK for Java follows the general upload process of ApsaraVideo VOD SDKs. For more information, see Upload process. The following content describes the process of using the upload SDK for PHP:

  1. Complete the configurations as described in the Prerequisites section.

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

  3. Configure upload information to implement the upload logic.

  4. The default endpoint of the upload SDK for PHP is cn-shanghai. If you want to upload media files to a region other than the China (Shanghai) region, you can configure AliyunVodUploader to specify a region when you initialize the SDK. For more information about the supported endpoints, see Endpoints.

    The following sample code provides an example on how to upload media files to the China (Beijing) region:

    $apiRegionId = 'cn-beijing';  // Upload media files to the China (Beijing) region.
    $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 and grant permissions to a RAM user.

  • 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 Use STS to upload videos.

    Note

    For more information about the scenarios in which STS can be used, see Comparison between credentials and STS.

Integrate the upload SDK for PHP

  1. Download the package VodUploadSDK-PHP_1.0.3.zip that contains the upload SDK for PHP and sample code. For more information, see SDK overview and download.

    Note
    • In this example, the upload SDK for PHP V1.0.3 is used. You can use other versions based on your business requirements.

    • For more information about the directories after decompression, see Directories.

  2. Decompress the VodUploadSDK-PHP_1.0.3.zip file and copy the voduploadsdk folder in the VodUploadSDK-PHP_1.0.3 directory to your project.

Update the upload SDK for PHP

If new operations or new features of existing operations are unavailable in the current SDK, update the SDK to the latest version. For more information, see Upload SDK.

Note

You can obtain the version number and release date of the current SDK in the first line of the ChangeLog.txt file in the voduploadsdk directory.

Directories

/VodUploadSDK-PHP_1.0.3.zip/VodUploadSDK-PHP_1.0.3/voduploadsdk/uploader

  • UploadVideoRequest.php

    Directory

    Description

    UploadVideoRequest

    The request class for video upload. For more information about the parameters, see CreateUploadVideo.

  • UploadImageRequest.php

    Directory

    Description

    UploadImageRequest

    The request class for image upload. For more information about the parameters, see CreateUploadImage.

  • UploadAttachedMediaRequest.php

    Directory

    Description

    UploadAttachedMediaRequest

    The request class for the upload of auxiliary media assets. For more information about the parameters, see CreateUploadAttachedMedia.

  • AliyunVodUploader.php

    Directory

    Description

    __construct

    The constructor used to set the AccessKey pair, access region, and access domain name of ApsaraVideo VOD. For more information, see Create and grant permissions to a RAM user and Region IDs of ApsaraVideo VOD.

    uploadLocalVideo

    The API operation that is used to upload local videos.

    uploadWebVideo

    The API operation that is used to upload online videos.

    uploadLocalImage

    The API operation used to upload local images.

    uploadWebImage

    The API operation used to upload online images.

    uploadLocalAttachedMedia

    The API operation used to upload local auxiliary media assets.

    uploadWebAttachedMedia

    The API operation used to upload online auxiliary media assets.

    uploadLocalM3u8

    The API operation used to upload local M3U8 videos.

    uploadWebM3u8

    The API operation used to upload online M3U8 videos.

    parseM3u8File

    The API operation used to parse the M3U8 index file to obtain the URLs of part files.

    setEcsRegionId

    The API operation used to specify the region of the Elastic Compute Service (ECS) instance on which the upload script is to be deployed. If the region of the ECS instance is the same as the storage region in ApsaraVideo VOD, the file is automatically uploaded over the internal network.

    setEnableSSL

    The API operation used to specify whether to send requests over HTTPS. By default, HTTPS is disabled to prevent failures when related extensions are not installed or a configuration exception occurs.

    uploadProgressCallback

    The API operation used to configure the callback for the upload progress. This results can be overridden.

  • AliyunVodUtils.php

    Directory

    Description

    AliyunVodUtils

    The utility class that provides static functions for truncating strings and obtaining extensions and file names.

    AliyunVodLog

    The log class that provides the logging feature. You can configure the logSwitch parameter to enable or disable logging.

    AliyunVodDownloader

    The class that is used to download online files.

    AliyunVodReportUpload

    The class that is used to report the upload progress.

    AliyunVodError

    The class that is used to define error codes.

/VodUploadSDK-PHP_1.0.3.zip/VodUploadSDK-PHP_1.0.3/voduploadsdk

  • aliyun-php-sdk-core: the base class on which the upload SDK depends. This package encapsulates Alibaba Cloud API signatures and HTTP requests.

  • aliyun-php-sdk-vod: the ApsaraVideo VOD SDK. This package encapsulates API requests of ApsaraVideo VOD.

  • aliyun-php-sdk-oss: the Object Storage Service (OSS) class on which the upload SDK depends. This package encapsulates operations such as OSS uploads.

/VodUploadSDK-PHP_1.0.3.zip/VodUploadSDK-PHP_1.0.3/samples

  • uploadVideo.php: sample code for video upload.

  • uploadImage.php: sample code for image upload.

  • uploadAttachedMedia.php: sample code for the upload of auxiliary media assets.

Scenario 1: Upload audio and video files

Regular audio and video files

The upload SDK for PHP supports the following types of audio and video files:

  • Use multipart upload to upload a local file. You can upload a file of up to 48.8 TB in size. Resumable upload is not supported. For more information, see the testUploadLocalVideo function in the sample code.

  • Use the file URL to upload an online file. You can upload a file of up to 48.8 TB in size. Before you upload online files, you must download the files to a local disk. Make sure that the local disk has sufficient space. For more information, see the testUploadWebVideo function in the sample code.

Show 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 the upload of a local audio or video file.
function testUploadLocalVideo($accessKeyId, $accessKeySecret, $filePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($filePath, 'testUploadLocalVideo via PHP-SDK');
        //$uploadVideoRequest->setCateId(1);
        // The URL of the video thumbnail. Example: http://example.com/example****.jpg.
        //$uploadVideoRequest->setCoverURL("<your CoverURL>");
        //$uploadVideoRequest->setTags('test1,test2');
        //$uploadVideoRequest->setStorageLocation('outin-xx.oss-cn-beijing.aliyuncs.com');
        //$uploadVideoRequest->setTemplateGroupId('6ae347b0140181ad371d197ebe289****');
        $userData = array(
            // The callback URL. Example: 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 the upload of an online audio or video file.
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 on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');

//$localFilePath = 'C:\test\sample.mp4';
$localFilePath = '/opt/video/sample.mp4';
//testUploadLocalVideo($accessKeyId, $accessKeySecret, $localFilePath);

// The URL of the online audio or video file. Example: 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);

M3U8 files

Sample code:

Show 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 the upload of a local M3U8 video.
function testUploadLocalM3u8($accessKeyId, $accessKeySecret, $m3u8FilePath)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($m3u8FilePath, 'testUploadLocalM3u8 via PHP-SDK');
        // Parse the part file URLs of the M3U8 file. If the parsing result is invalid, concatenate the URLs of part files. By default, the part files and M3U8 file are stored 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 the upload of an online M3U8 video.
function testUploadWebM3u8($accessKeyId, $accessKeySecret, $m3u8FileUrl)
{
    try {
        $uploader = new AliyunVodUploader($accessKeyId, $accessKeySecret);
        $uploadVideoRequest = new UploadVideoRequest($m3u8FileUrl, 'testUploadWebM3u8 via PHP-SDK');
        // Parse the part file URLs of the M3U8 file. If the parsing result is invalid, concatenate the URLs of part files. By default, the part files and M3U8 file are stored 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 on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
$accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');
$accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
$localM3u8FilePath = '/opt/video/m3u8/sample.m3u8';
//testUploadLocalM3u8($accessKeyId, $accessKeySecret, $localM3u8FilePath);

// The URL of the online M3U8 video. Example: 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);

Scenario 2: Upload images

Show sample code

Show 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 the upload of 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 the upload of an online 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 on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
$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

Sample code:

Show sample code

Show 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 the upload of 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 the upload of an online 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 on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M. 
// We recommend that you not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
// In this example, ApsaraVideo VOD reads the AccessKey pair from the environment variables to implement identity verification for API access. Before you run the sample code, configure the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET. 
$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

STS SDK overview