This topic describes how to install and use the PHP SDK for the Alibaba Cloud Vision Intelligence Open Platform and includes code examples.
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
-
Before installing and using the Alibaba Cloud SDK, ensure you have an Alibaba Cloud account and an access key. For more information, see Create an access key.
-
Install the SDK package for the relevant AI capability. Follow these steps:
-
Download and install Composer:
curl -sS https://getcomposer.org/installer | php. -
Run the Composer command to install the latest version of the SDK package for a specific capability. For example, to install the package for Face and body services, run
php composer.phar require alibabacloud/facebody-20191230. For more information, see the following table. -
In your code, include the Composer autoloader:
<?php require __DIR__ . '/vendor/autoload.php';.NotePHP: >=5.6
AI capability
SDK link
GitHub link
Face and body
Text recognition
Goods technology
Content moderation
Image recognition
Image enhancement
Image segmentation
Object detection
Visual search
Image analysis and processing
Video enhancement
Video understanding
Video segmentation
Asynchronous task management
Server-side face verification (20200910 dedicated version)
-
Configure environment variables
Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.
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
Open a terminal in IntelliJ IDEA.
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_IDandALIBABA_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.Open File Explorer, right-click This PC, and then select Properties.
In the left-side navigation pane, click Advanced system settings.
On the Advanced tab of the System Properties dialog box, click Environment Variables.
In the Environment Variables dialog box, click New.
In the New System Variable dialog box, add the environment variables
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRET, and set them to the AccessKey ID and AccessKey Secret that you have prepared.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)
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));
The sections that require modification are marked in the code comments and summarized below:
-
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
Actionparameter 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 changeocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code. -
Change the endpoint to match the capability. If the endpoint does not match the capability, an
InvalidAction.NotFounderror is returned. For more information about endpoints, see endpoints. -
Use the client class from the package of the corresponding capability.
-
Use the request and response objects from the package and class of the corresponding capability.
-
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 besegmentCommonImageWithOptions.
Local file or public URL
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));
The sections that require modification are marked in the code comments and summarized below:
-
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
Actionparameter 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 changeocr20191230toimageseg20191230andRecognizeBankCardtoSegmentCommonImagein your code. -
Change the endpoint to match the capability. If the endpoint does not match the capability, an
InvalidAction.NotFounderror is returned. For more information about endpoints, see endpoints. -
Use the client class from the package of the corresponding capability.
-
Use the request and response objects from the package and class of the corresponding capability.
-
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 besegmentCommonImageAdvance.
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
-
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.0NoteBecause Psr7 depends on
guzzlehttp/guzzle, which requiresguzzlehttp/psr7: ^1.9 || ^2.4, changing the version does not affect SDK usage. -
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.mdfile to run the code and download SDK dependencies.composer install && php src/Sample.phpNoteIf 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.
-
Run
composer config -g repo.packagist composer https://repo.packagist.org. -
Run
composer requirewith the required package dependency, such asalibabacloud/facebody-20191230. -
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.mdfile 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));, removearray_slice($argv, 1)to change the line toSample::main(). -
In the
public static function main($args){}method definition, remove the$argsparameter.
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:
-
Checks if
openssl.cafileis set in the php.ini file. -
Checks if
curl.cainfois set in the php.ini file. -
Checks if
/etc/pki/tls/certs/ca-bundle.crtexists (provided by the ca-certificates package on Red Hat, CentOS, and Fedora). -
Checks if
/etc/ssl/certs/ca-certificates.crtexists (provided by the ca-certificates package on Ubuntu and Debian). -
Checks if
/usr/local/share/certs/ca-root-nss.crtexists (provided by the ca_root_nss package on FreeBSD). -
Checks if
/usr/local/etc/openssl/cert.pemexists (provided by Homebrew on OS X). -
Checks if
C:\windows\system32\curl-ca-bundle.crtexists (Windows). -
Checks if
C:\windows\curl-ca-bundle.crtexists (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.