Updated on 2024-09-04 GMT+08:00

PHP SDK

This section describes how to use the new PHP SDK to quickly develop OCR services.

Prerequisites

  • You have registered a Huawei ID and enabled Huawei Cloud services. Your account cannot be in arrears or frozen.
  • PHP 5.6 or later is available. You can run the php --version command to check the version information.
  • You have obtained an AK and an SK on the My Credentials > Access Keys page. The AK and SK are contained in the credentials.csv file.
    Figure 1 Creating an access key

  • You have obtained the IAM user name, account name, and the project ID of your target region on the My Credentials > API Credentials page. The information will be used during service calling. Save it in advance.
    Figure 2 API Credentials

Installing the SDK

You are advised to use Composer to install the SDK.

Composer is a dependency manager for PHP. It allows you to declare and install dependencies in a project.

// 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 import the autoload file of Composer.

require 'path/to/vendor/autoload.php';

Getting Started

  1. Import dependency modules.
    <?php
    namespace HuaweiCloud\SDK\Ocr\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\Ocr\V1\OcrClient;
  2. Configure client connection parameters.
    • Using the default configuration
      // Use the default configuration.
      $config = HttpConfig::getDefaultConfig();
    • (Optional) Configuring a network proxy
      // Use a proxy server.
      $config->setProxyProtocol('http');
      $config->setProxyHost('proxy.huawei.com');
      $config->setProxyPort(8080);
      $config->setProxyUser('username');
      $config->setProxyPassword('password');
    • (Optional) Configuring the timeout
      // The default connection timeout interval is 60 seconds, and the default read timeout interval is 120 seconds. You can change the default values as needed.
      $config->setTimeout(120);
      $config->setConnectionTimeout(60);
    • (Optional) Configuring an SSL
      // 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. Configure authentication information.
    Configure ak, sk, and projectId. AK is used together with SK to sign requests cryptographically, ensuring that the requests are secret, complete, and correct.
    // Specify the endpoint for OCR, for example, AP-Bangkok.
    $ak = getenv('HUAWEICLOUD_SDK_AK');
    $sk = getenv('HUAWEICLOUD_SDK_SK');
    $endpoint = "https://ocr.ap-southeast-2.myhuaweicloud.com";
    $projectId = getenv('PROJECT_ID');
    $credentials = new BasicCredentials($ak,$sk,$projectId);
    • Hard-coded or plaintext AK and SK are risky. For security purposes, encrypt your AK and SK and store them in the configuration file or environment variables.
    • In this example, the AK and SK are stored in environment variables for identity authentication. Before running this example, configure environment variables HUAWEICLOUD_SDK_AK and HUAWEICLOUD_SDK_SK.

    The authentication parameters are described as follows:

    • ak and sk: access key and secrete access key, respectively. For how to obtain them, see Prerequisites.
    • projectId: Huawei Cloud project ID. For details about how to obtain the ID, see Prerequisites.
    • endpoint: endpoints for Huawei Cloud services. For details, see Regions and Endpoints.
  4. Initialize the client.

    Specifying an endpoint for a cloud service

    $client = OcrClient::newBuilder(new OcrClient)
      ->withHttpConfig($config)
      ->withEndpoint($endpoint)
      ->withCredentials($credentials)
      ->build();
  5. Send a request and check the response.
    // The following uses calling the RecognizePassport API of Passport OCR as an example.
    $request = new RecognizePassportRequest();
    $body = new PassportRequestBody();
    $body->setUrl("Image URL");
    $request->setBody($body);
    try {
      $response = $client->RecognizePassport($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;
  6. Handle the exception.
    Table 1 Exception handling

    Level-1 Category

    Level-1 Category Description

    Level-2 Category

    Level-2 Category 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).

    try {
      $response = $client->RecognizePassport($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;

For how to use the asynchronous client and configure logs, see SDK Center and PHP SDK Usage Guide.

Automatic Generation of Sample Code

API Explorer allows for API search and platform debugging, with features such as quick and comprehensive search, visual debugging, access to help documentation, and online consultation.

You only need to modify API parameters in the API Explorer to automatically generate the corresponding sample code.

Figure 3 API Explorer