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:
Complete the prerequisites. For more information, see Prerequisites.
Integrate the PHP upload SDK. For more information, see Integrate the PHP upload SDK.
Implement the upload logic, which involves configuring upload information.
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 The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use the AccessKey pair of a RAM user to call API operations or perform routine O&M.
We recommend that you do not hard-code the AccessKey ID and AccessKey secret into your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account is 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
Download the SDK and demo.
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
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');
//$uploadVideoRequest->setCateId(1);
// 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('6ae347b0140181ad371d197ebe289****');
$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);
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`. |
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);