Halaman ini belum tersedia dalam bahasa lokal Anda. Kami berusaha keras untuk menambahkan lebih banyak versi bahasa. Terima kasih atas dukungan Anda.

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

PHP SDK User Guide

Updated on 2024-08-05 GMT+08:00

This section describes how to quickly integrate the PHP SDK for development.

Prerequisites

  • You have registered with Huawei Cloud and completed real-name authentication.
    NOTE:

    If you are a Huawei Cloud (International) user, you need to complete real-name authentication when you:

    • Purchase and use cloud services on Huawei Cloud nodes in the Chinese mainland. In this case, real-name authentication is required by the laws and regulations of the Chinese mainland.
    • Plan to use Live in regions in the Chinese mainland.
  • You have obtained and added an ingest domain name and a streaming domain name (both licensed) on the Live console, and associated the domain names.
  • The development environment (PHP 5.6 or later) is available.
  • You have obtained the access key (AK) and secret access key (SK) of the Huawei Cloud account. You can create and view your AK and SK on the My Credentials > Access Keys page of the Huawei Cloud console. For details, see Access Keys.
  • You have obtained the project ID of the corresponding region of Live. You can view the project ID on the My Credentials > API Credentials page of the Huawei Cloud console. For details, see API Credentials.

Installing an SDK

The Live server SDK supports PHP 5.6 or later. Run the php --version command to check the PHP version.

You are advised to install the SDK using Composer.

Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will install them for you.
1
2
3
4
# Install Composer.
curl -sS https://getcomposer.org/installer | php 
# Install the PHP SDK.
composer require huaweicloud/huaweicloud-sdk-php
After the installation is complete, you need to generate the necessary files that Composer will use for autoloading.
1
require 'path/to/vendor/autoload.php';

Procedure

  1. Import the dependent module.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    namespace HuaweiCloud\SDK\Live\V1\Model;
    require_once "vendor/autoload.php";
    use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
    use HuaweiCloud\SDK\Core\Http\HttpConfig;
    use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
    use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
    use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
    // Import the specified Live library.
    use HuaweiCloud\SDK\Live\V1\LiveClient;
    

  2. Configure client attributes.

    1. Use the default configuration.
      1
      2
      // Use the default configuration.
      $config = HttpConfig::getDefaultConfig();
      
    2. (Optional) Configure a proxy.
      1
      2
      3
      4
      5
      6
      7
      8
      // (Optional) Use a proxy server.
      // There will be huge security risks if the password of the proxy server is directly written into the code. You are advised to store the password in ciphertext in the configuration file or environment variables and decrypt the password when using it.
      // Before configuring a proxy, specify the environment variable PROXY_PASSWORD in the local environment.
      $config->setProxyProtocol('http');
      $config->setProxyHost('proxy.huawei.com');
      $config->setProxyPort(8080);
      $config->setProxyUser('username');
      $config->setProxyPassword(getenv('PROXY_PASSWORD'));
      
    3. (Optional) Configure a connection.
      1
      2
      // (Optional) Configure the connection timeout. The timeout can be set to timeout in a unified manner, or set to connect timeout or read timeout as required.
      $config->setConnectionTimeout(3);
      
    4. (Optional) Configure SSL.
      1
      2
      3
      4
      # (Optional) Skip server certificate verification.
      $config->setIgnoreSslVerification(true);
      # Configure the server CA certificate so that the SDK can verify the server certificate.
      $config->setCertFile("{yourCertFile}");
      

  3. Initialize authentication information.

    You can use one of the following two authentication modes:

    • Permanent AK and SK

      Obtain a permanent AK, SK, and project ID. For details, see Prerequisites.

      1
      $basicCredentials = new BasicCredentials($ak,$sk,$projectId);
      
    • Temporary AK and SK

      Obtain a temporary AK, SK, and security token through a token or through an agency.

      1
      $basicCredentials = BasicCredentials(ak, sk, projectId).withSecurityToken(securityToken);
      
    The related parameters are as follows:
    • ak: AK of the Huawei Cloud account. You are advised to store the AK in ciphertext in the configuration file or environment variables and decrypt it when using it.
    • sk: SK of the Huawei Cloud account. You are advised to store the SK in ciphertext in the configuration file or environment variables and decrypt it when using it.
    • project_id: ID of the project where Live is provided. Select a project ID based on the region of the project.
    • securitytoken: security token used for temporary AK and SK authentication

  4. Initialize the client.

    1
    2
    3
    4
    5
    6
    7
    // Initialize the Live client.
    $client = LiveClient::newBuilder(new LiveClient)
      ->withHttpConfig($config)
      ->withEndpoint($endpoint)
      ->withCredentials($credentials)
      ->build();
    $request = new CreateDomainRequest();
    

    endpoint: regions where Live is used and endpoints of each service. For details, see Regions and Endpoints.

  5. Send a request and view the response.

    1
    2
    3
    4
    // Initialize the request. The following uses the API for querying transcoding templates as an example.
    $request = new ShowTranscodingsTemplateRequest("play.example.huaweicloud.com");
    $response = $client->ShowTranscodingsTemplate($request);
    echo $response;
    

  6. Perform troubleshooting.

    Table 1 Troubleshooting

    Level 1

    Description

    Level 2

    Description

    ConnectionException

    Connection exception

    HostUnreachableException

    The network is unreachable or access is rejected.

    SslHandShakeException

    SSL authentication is abnormal.

    RequestTimeoutException

    Response timeout exception

    CallTimeoutException

    The server fails to respond to a single request before timeout.

    RetryOutageException

    No valid response is returned after the maximum number of retries specified in the retry policy is reached.

    ServiceResponseException

    Server response exception

    ServerResponseException

    Internal server error. HTTP response code: [500,].

    ClientRequestException

    Invalid request parameter. HTTP response code: [400, 500).

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    // Perform troubleshooting.
    try {
      $response = $client->ShowTranscodingsTemplate($request);
    } catch (ConnectionException $e) {
      $msg = $e->getMessage();
      echo "\n". $msg ."\n";
    } catch (RequestTimeoutException $e) {
      $msg = $e->getMessage();
      echo "\n". $msg ."\n";
    } catch (ServiceResponseException $e) {
      echo "\n";
      echo $e->getHttpStatusCode(). "\n";
      echo $e->getErrorCode() . "\n";
      echo $e->getErrorMsg() . "\n";
    }
    

  7. Use the listener to obtain original HTTP requests and responses.

    The original HTTP requests and responses are required for debugging HTTP requests sent by the service side. The SDK provides the listener to obtain the original and encrypted HTTP requests and responses.

    CAUTION:

    Original information is printed only during debugging. Do not print the header and body of an original HTTP request in the production system because this information contains sensitive data but is not encrypted. If the request body is binary, that is, Content-Type is set to binary, the body will be displayed as *** without the detailed content.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    $requestHandler = function ($argsMap) {
        if (isset($argsMap['request'])) {
            $sdkRequest = $argsMap['request'];
            $requestHeaders = $sdkRequest->headerParams;
            $requestBase = "> Request " . $sdkRequest->method . ' ' .
                $sdkRequest->url . "\n";
            if (count($requestHeaders) > 0) {
                $requestBase = $requestBase . '> Headers:' . "\n";
                foreach ($requestHeaders as $key => $value) {
                    $requestBase = $requestBase . '    ' . $key . ' : ' .
                        $value . "\n";
                }
                $requestBase = $requestBase . '> Body: ' .
                    $sdkRequest->body . "\n\n";
            }
            if (isset($argsMap['logger'])) {
                $logger = $argsMap['logger'];
                $logger->addDebug($requestBase);
            }
        }
    };
    
    $responseHandler = function ($argsMap) {
        if (isset($argsMap['response'])) {
            $response = $argsMap['response'];
            $responseBase = "> Response HTTP/1.1 " .
                $response->getStatusCode() . "\n";
            $responseHeaders = $response->getHeaders();
            if (count($responseHeaders) > 0) {
                $responseBase = $responseBase . '> Headers:' . "\n";
                foreach ($responseHeaders as $key => $value) {
                    $valueToString = '';
                    if (is_array($value)) {
                        $valueToString = ''.join($value);
                    }
                    $responseBase = $responseBase . '    ' . $key . ' : '
                        . $valueToString . "\n";
                }
                $responseBody = $response->getBody();
                $responseBase = $responseBase . '> Body: ' . (string)
                    $responseBody . "\n\n";
            }
            if (isset($argsMap['logger'])) {
                $logger = $argsMap['logger'];
                $logger->addDebug($responseBase);
            }
        }
    };
    
    $httpHandler = new HttpHandler();
    $httpHandler->addRequestHandlers($requestHandler);
    $httpHandler->addResponseHandlers($responseHandler);
    
    $iamClient = LiveClient::newBuilder()
        ->withHttpConfig($config)
        ->withEndpoint($endpoint)
        ->withCredentials(null)
        ->withStreamLogger($stream = 'php://stdout',$logLevel =Logger::INFO) // Print logs to the console.
        ->withFileLogger($logPath='./test_log.txt', $logLevel = Logger::INFO) // Print logs to a file.
        ->withHttpHandler($httpHandler)
        ->build();
    

Sample Code

Before the calling, replace the variables {your endpoint string} and {your project id} as needed.

There will be huge security risks if the AK and SK used for authentication are directly written into the code. You are advised to store the AK and SK in ciphertext in the configuration file or environment variables and decrypt them when using them.

In this example, the AK and SK are stored in environment variables. Before running this example, specify the environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK in the local environment.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
namespace HuaweiCloud\SDK\Live\V1\Model;
require_once "vendor/autoload.php";
use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\Live\V1\LiveClient;

$ak = getenv('HUAWEICLOUD_SDK_AK');
$sk = getenv('HUAWEICLOUD_SDK_SK');
$endpoint = "https://live.cn-north-4.myhuaweicloud.com";
$projectId = "";
$credentials = new BasicCredentials($ak,$sk,$projectId);
$config = HttpConfig::getDefaultConfig();
$config->setIgnoreSslVerification(true);

$client = LiveClient::newBuilder(new LiveClient)
  ->withHttpConfig($config)
  ->withEndpoint($endpoint)
  ->withCredentials($credentials)
  ->build();
$request = new ShowTranscodingsTemplateRequest();

try {
  $response = $client->ShowTranscodingsTemplate($request);
} catch (ConnectionException $e) {
  $msg = $e->getMessage();
  echo "\n". $msg ."\n";
} catch (RequestTimeoutException $e) {
  $msg = $e->getMessage();
  echo "\n". $msg ."\n";
} catch (ServiceResponseException $e) {
  echo "\n";
  echo $e->getHttpStatusCode(). "\n";
  echo $e->getErrorCode() . "\n";
  echo $e->getErrorMsg() . "\n";
}
echo "\n";
echo $response;

Kami menggunakan cookie untuk meningkatkan kualitas situs kami dan pengalaman Anda. Dengan melanjutkan penelusuran di situs kami berarti Anda menerima kebijakan cookie kami. Cari tahu selengkapnya

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback