PHP

更新时间:
复制 MD 格式

This topic describes how to install and use the PHP SDK for the Alibaba Cloud Vision Intelligence Open Platform and includes code examples.

Note

If you have questions about SDK integration, API usage, or other issues related to the AI capabilities of the Alibaba Cloud Vision Intelligence Open Platform, join our DingTalk group (ID: 23109592) for support.

This SDK requires PHP 5.6 or later. If your environment does not meet this requirement, upgrade your PHP version.

Prerequisites

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • An Alibaba Cloud account has full access to all API operations. We recommend that you use a RAM user for API calls or routine O&M. For more information, see Create a RAM user.

  • Do not save your AccessKey ID or AccessKey Secret in project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised.

  • Configure environment variables on Linux and macOS

    1. Open a terminal in IntelliJ IDEA.

    2. Run the following commands to configure the environment variables.

      Replace <access_key_id> with the AccessKey ID of your RAM user and <access_key_secret> with the AccessKey Secret of your RAM user. If you need to configure more permissions, see Control access permissions using a RAM policy.

      export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
      export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Configure environment variables on Windows

    Create a new environment variable file, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared. Then, restart the Windows operating system. The following example uses Windows 10.

    1. Open File Explorer, right-click This PC, and then select Properties.

    2. In the left-side navigation pane, click Advanced system settings.

    3. On the Advanced tab of the System Properties dialog box, click Environment Variables.

    4. In the Environment Variables dialog box, click New.

    5. In the New System Variable dialog box, add the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.

    6. Restart the Windows operating system for the configurations to take effect.

Code examples

This section uses the RecognizeBankCard operation as an example.

File in an OSS bucket (Shanghai)

Note

For the endpoints and supported regions for each AI capability, see endpoints.

<?php
// 1. This is an example for the RecognizeBankCard operation of the Text recognition capability. To use other capabilities, import the corresponding packages and classes. You can find the package name in the SDK Packages table earlier in this document. The operation name is the `Action` parameter value in the corresponding API documentation. For example, if you want to use general segmentation, its documentation is at https://help.aliyun.com/document_detail/151960.html. From the documentation, it belongs to the Image segmentation category and its operation name is `SegmentCommonImage`. You would need to change `Ocr` to `Imageseg` and `RecognizeBankCard` to `SegmentCommonImage` in your code. Also, modify the version number `V20191230` if it has changed.
use AlibabaCloud\SDK\Ocr\V20191230\Ocr;
use AlibabaCloud\SDK\Ocr\V20191230\Models\RecognizeBankCardRequest;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Sample {

    /**
     * Initialize the client with an access key pair
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocr Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
      // Initialize the configuration object Darabonba\OpenApi\Models\Config.
      // The Config object stores configurations such as accessKeyId, accessKeySecret, and endpoint.
      $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 2. The endpoint. Note: Change this to the endpoint of the corresponding capability. For more information, see https://help.aliyun.com/document_detail/143103.html
        $config->endpoint = "ocr.cn-shanghai.aliyuncs.com";
        // 3. This is an example for Text recognition. To use other capabilities, import the client class of the corresponding category.
        return new Ocr($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args) {
        // 4. Create an access key ID and access key secret. For more information, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using an access key of a RAM user, you must also grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // The access key ID and access key secret are read from environment variables. You must set up the environment variables before running the example.    
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        // 5. This is an example for the RecognizeBankCard operation of Text recognition. To use other capabilities, use the corresponding packages and classes. For parameter settings, see the documentation for the specific capability.
        $recognizeBankCardRequest = new RecognizeBankCardRequest();
        $recognizeBankCardRequest->imageURL = "http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg";
        $runtime = new RuntimeOptions([]);
        try {
            // 6. This is an example for the RecognizeBankCard operation of Text recognition. To use other capabilities, use the corresponding packages and classes. Note that the method name `recognizeBankCardWithOptions` must also be changed to the method name of the corresponding capability. The method name is generated from the operation name according to specific rules. For example, if the operation name is `SegmentCommonImage`, the method name is `segmentCommonImageWithOptions`.
            $resp = $client->recognizeBankCardWithOptions($recognizeBankCardRequest, $runtime);
            # Get the entire response
            echo Utils::toJSONString($resp->body);
            # Get a single field. This is just an example. For the fields of a specific capability, see the relevant documentation.
            echo Utils::toJSONString($resp->body->data->cardNumber);
        } catch (Exception $exception) {
            # Get the complete error message
            echo Utils::toJSONString($exception);
            # Get a single field
            echo $exception->getCode();
        }
    }
}

// Include autoload.php
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
Note

The sections that require modification are marked in the code comments and summarized below:

  1. When importing packages, you must import the package and related classes for the corresponding AI capability. You can find the package name in the SDK Packages table and the operation name in the Action parameter of the relevant API documentation.

    For example, to use the general segmentation capability, refer to the General Segmentation API documentation. You can see that it belongs to the Image segmentation category (imageseg20191230) and the operation name is SegmentCommonImage. You need to change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. Change the endpoint to match the capability. If the endpoint does not match the capability, an InvalidAction.NotFound error is returned. For more information about endpoints, see endpoints.

  3. Use the client class from the package of the corresponding capability.

  4. Use the request and response objects from the package and class of the corresponding capability.

  5. When calling a client method, change the method name to match the corresponding operation. The method name is generated from the operation name. For example, if the capability name is SegmentCommonImage, the corresponding method name should be segmentCommonImageWithOptions.

Local file or public URL

Important

The main difference when using a local file or one from a publicly accessible URL is that you must use an xxxAdvanceRequest object. The file is passed as a stream through the imageURLObject parameter.

<?php
// 1. This is an example for the RecognizeBankCard operation of the Text recognition capability. To use other capabilities, import the corresponding packages and classes. You can find the package name in the SDK Packages table earlier in this document. The operation name is the `Action` parameter value in the corresponding API documentation. For example, if you want to use general segmentation, its documentation is at https://help.aliyun.com/document_detail/151960.html. From the documentation, it belongs to the Image segmentation category and its operation name is `SegmentCommonImage`. You would need to change `Ocr` to `Imageseg` and `RecognizeBankCard` to `SegmentCommonImage` in your code. Also, modify the version number `V20191230` if it has changed.
use AlibabaCloud\SDK\Ocr\V20191230\Ocr;
use AlibabaCloud\SDK\Ocr\V20191230\Models\RecognizeBankCardAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;

class Sample {

    /**
     * Initialize the client with an access key pair
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocr Client
     */
    public static function createClient($accessKeyId, $accessKeySecret){
        // Initialize the configuration object Darabonba\OpenApi\Models\Config.
        // The Config object stores configurations such as accessKeyId, accessKeySecret, and endpoint.
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        // 2. The endpoint. Note: Change this to the endpoint of the corresponding capability. For more information, see https://help.aliyun.com/document_detail/143103.html
        $config->endpoint = "ocr.cn-shanghai.aliyuncs.com";
        // 3. This is an example for Text recognition. To use other capabilities, import the client class of the corresponding category.
        return new Ocr($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args) {
        // 4. Create an access key ID and access key secret. For more information, see https://help.aliyun.com/document_detail/175144.html.
        // If you are using an access key of a RAM user, you must also grant the AliyunVIAPIFullAccess permission to the RAM user. For more information, see https://help.aliyun.com/document_detail/145025.html.
        // The access key ID and access key secret are read from environment variables. You must set up the environment variables before running the example.
        $accessKeyId = getenv('ALIBABA_CLOUD_ACCESS_KEY_ID');      
        $accessKeySecret = getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET');
        $runtime = new RuntimeOptions([]);
        // 5. This is an example for the RecognizeBankCard operation of Text recognition. To use other capabilities, use the corresponding packages and classes. For parameter settings, see the documentation for the specific capability.
        $recognizeBankCardAdvanceRequest = new RecognizeBankCardAdvanceRequest();
        // Scenario 1: Use a local file
        $file = fopen('/tmp/bankCard.png', 'rb');
        // Scenario 2: Use any accessible URL
        // $file = fopen('http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/ocr/RecognizeBankCard/yhk1.jpg', 'rb');
        $stream = new Stream($file);
        $recognizeBankCardAdvanceRequest->imageURLObject = $stream;
        try {
            // 6. This is an example for the RecognizeBankCard operation of Text recognition. To use other capabilities, use the corresponding packages and classes. Note that the method name `recognizeBankCardAdvance` must also be changed to the method name of the corresponding capability. The method name is generated from the operation name according to specific rules. For example, if the operation name is `SegmentCommonImage`, the method name is `segmentCommonImageAdvance`.
            $resp = $client->recognizeBankCardAdvance($recognizeBankCardAdvanceRequest, $runtime);
            # Get the entire response
            echo Utils::toJSONString($resp->body);
            # Get a single field. This is just an example. For the fields of a specific capability, see the relevant documentation.
            echo Utils::toJSONString($resp->body->data->cardNumber);
        } catch (Exception $exception) {
            # Get the complete error message
            echo Utils::toJSONString($exception);
            # Get a single field
            echo $exception->getCode();
        }
    }
}

// Include autoload.php
$path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
if (file_exists($path)) {
    require_once $path;
}
Sample::main(array_slice($argv, 1));
Note

The sections that require modification are marked in the code comments and summarized below:

  1. When importing packages, you must import the package and related classes for the corresponding AI capability. You can find the package name in the SDK Packages table and the operation name in the Action parameter of the relevant API documentation.

    For example, to use the general segmentation capability, refer to the General Segmentation API documentation. You can see that it belongs to the Image segmentation category (imageseg20191230) and the operation name is SegmentCommonImage. You need to change ocr20191230 to imageseg20191230 and RecognizeBankCard to SegmentCommonImage in your code.

  2. Change the endpoint to match the capability. If the endpoint does not match the capability, an InvalidAction.NotFound error is returned. For more information about endpoints, see endpoints.

  3. Use the client class from the package of the corresponding capability.

  4. Use the request and response objects from the package and class of the corresponding capability.

  5. When calling a client method, change the method name to match the corresponding operation. The method name is generated from the operation name. For example, if the capability name is SegmentCommonImage, the corresponding method name should be segmentCommonImageAdvance.

FAQ

If you encounter an error similar to the following when you run composer require alibabacloud/facebody-20191230 or install other SDKs, use the solutions in this topic to troubleshoot the issue.

Installing the SDK generates a vendor directory. Do not place your project code in this directory. Your project code directory and the vendor directory should be at the same level. In the following example, src contains the project code and vendor is the directory generated after the SDK is installed.

VIDEO4/
├── src      # Project code
└── vendor   # Generated after SDK installation

Resolving the "Problem 1..." error

Error message

Problem 1
    - alibabacloud/tea-oss-utils 0.3.0 requires guzzlehttp/psr7 ^1.0 -> found guzzlehttp/psr7[1.0.0, ..., 1.9.0] but the package is fixed to 2.4.3 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

Solution

  1. The current SDK supports only Psr7 v1.x. If you are using a PHP 8 environment, you must downgrade Psr7 to a v1.x version, such as 1.9.0. Run the following command:

    composer require guzzlehttp/psr7 1.9.0
    Note

    Because Psr7 depends on guzzlehttp/guzzle, which requires guzzlehttp/psr7: ^1.9 || ^2.4, changing the version does not affect SDK usage.

  2. If the preceding steps do not resolve the issue, go to the API Portal for the capability, download the complete project, and import it. In the project, you can run the PHP command from the README.md file to run the code and download SDK dependencies.

    composer install && php src/Sample.php
    Note

    If you have questions about SDK integration, API usage, or other issues related to the AI capabilities of the Alibaba Cloud Vision Intelligence Open Platform, join our DingTalk group (ID: 23109592) for support.

Resolving the "Problem 2..." error

Error message

Problem 2
 - Root composer.json requires alibabacloud/facebody-20191230 3.0.3 -> satisfiable by alibabacloud/facebody-20191230[3.0.3].
 - alibabacloud/facebody-20191230 3.0.3 requires alibabacloud/tea-oss-utils ^0.3.0 -> found alibabacloud/tea-oss-utils[dev-master, 0.1.0, ..., 0.2.3] but it does not match the constraint.

Solution

An issue with the mirror site may cause this error.

  1. Run composer config -g repo.packagist composer https://repo.packagist.org.

  2. Run composer require with the required package dependency, such as alibabacloud/facebody-20191230.

  3. If the preceding steps do not resolve the issue, go to the API Portal for the capability, download the complete project, and import it. In the project, you can run the PHP command from the README.md file to run the code and download SDK dependencies.

    composer install && php src/Sample.php

Resolving API call errors

If you encounter an API call error, first upgrade the SDK package to the latest version. For the latest version, refer to the SDK links for each capability. If your application imports multiple SDK packages, upgrade all of them to their latest versions to prevent version conflicts.

Latest package not found in Packagist

If you cannot find the latest package version displayed in OpenAPI Explorer in the Packagist repository, this can happen because of a synchronization delay after a new version is released. If the version is not available, try again later or use the latest version available in the Packagist repository.

Resolving the "array_slice()" error

This error occurs because an array parameter is reserved for structural consistency. Modify the code as follows:

  • In Sample::main(array_slice($argv, 1));, remove array_slice($argv, 1) to change the line to Sample::main().

  • In the public static function main($args){} method definition, remove the $args parameter.

These changes resolve the error.

Resolving an incorrect RuntimeOptions import error

Error message

#0 [8]ErrorException in OpenApiClient.php line 701
Undefined property: AlibabaCloud\Tea\OSSUtils\OSSUtils\RuntimeOptions::$key

Solution

This error typically occurs when the RuntimeOptions package is imported incorrectly during manual dependency setup. The correct package path is AlibabaCloud\Tea\Utils\Utils\RuntimeOptions. Ensure you import the correct package and remove any incorrect imports, such as for OSSUtils\RuntimeOptions, leaving only the import for Tea\Utils\Utils\RuntimeOptions.

Resolving link access failure after an API call

Error message

When you call an API in PHP, the returned URL is http:\/\/vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com. If you copy and directly access this URL, the connection fails with the following error message:

<Error>
  <Code>SignatureDoesNotMatch</Code>
  <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
  <RequestId>6426522505F8E23936436D6A</RequestId>
  <HostId>vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com</HostId>
  <OSSAccessKeyId>xxx</OSSAccessKeyId>
</Error>

Solution

The // characters in the response string are escaped, which causes this issue. Obtain the accessible URL by printing the imageURL parameter separately, for example, $resp->body->data->imageURL.

Resolving SSL certificate errors in PHP

Error message

Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)
Stack trace:
#0 D:\phpstudy_pro\WWW\aliai\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(158): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\...))
#1 D:\phpstudy_pro\WWW\aliai\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(110): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\...))
#2 D:\phpstudy_pro\WWW\aliai\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(47): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\Cu...))

Solution

The latest SDK lets you configure the request protocol for OpenAPI in the client, which overrides the default settings. You can ignore certificate errors by setting runtime options. For more information, see Configure HTTPS requests.

In Windows, the logic for obtaining certificates in PHP depends on the configuration of the php.ini file. For more information, see Guzzle.

Not all systems have a CA bundle on disk. For example, Windows and OS X do not have a common local CA bundle. When you set verify to true, Guzzle searches for a suitable CA bundle on your operating system. When using cURL or streams with PHP 5.6 or later, Guzzle tries to find the CA bundle in the following order:

  1. Checks if openssl.cafile is set in the php.ini file.

  2. Checks if curl.cainfo is set in the php.ini file.

  3. Checks if /etc/pki/tls/certs/ca-bundle.crt exists (provided by the ca-certificates package on Red Hat, CentOS, and Fedora).

  4. Checks if /etc/ssl/certs/ca-certificates.crt exists (provided by the ca-certificates package on Ubuntu and Debian).

  5. Checks if /usr/local/share/certs/ca-root-nss.crt exists (provided by the ca_root_nss package on FreeBSD).

  6. Checks if /usr/local/etc/openssl/cert.pem exists (provided by Homebrew on OS X).

  7. Checks if C:\windows\system32\curl-ca-bundle.crt exists (Windows).

  8. Checks if C:\windows\curl-ca-bundle.crt exists (Windows).

Technical support

If the preceding methods do not resolve your issue, search for the DingTalk group number (23109592) to join the Alibaba Cloud Vision Intelligence Open Platform consultation group, where a technical specialist will assist you.