PHP SDK call examples for ECS
ECS SDK V2.0 for PHP lets you call Elastic Compute Service (ECS) API operations directly from PHP code. This guide walks you through installation and a working example that calls the DescribeInstances operation to query ECS instances.
Prerequisites
Before you begin, make sure you have:
A RAM user with an AccessKey pair — The AccessKey of an Alibaba Cloud account grants full access to all resources. Create a Resource Access Management (RAM) user and grant it only the permissions required. For instructions, see Create an AccessKey.
ECS permissions on the RAM user — The example in this guide runs a read-only query (DescribeInstances), so the
AliyunECSReadonlyAccesssystem policy is sufficient. For custom permissions, see Create a custom policy and Authorization information. ECS also provides ready-made policy examples at Custom policies. For a full list of system policies, see System policies for ECS.AccessKey configured as environment variables — Set
ALIBABA_CLOUD_ACCESS_KEY_IDandALIBABA_CLOUD_ACCESS_KEY_SECRETin your environment. See Configure environment variables on Linux, macOS, and Windows.
Install ECS SDK V2.0 for PHP
Install the SDK using Composer. For other installation options, visit SDK Center.
composer require alibabacloud/ecs-20140526 4.3.0Use ECS SDK V2.0 for PHP
All SDK interactions follow the same three-step pattern:
Initialize a client — configure credentials and the endpoint.
Create a request object — set the operation parameters.
Call the operation — send the request and handle the response or exception.
The sections below walk through each step, followed by complete runnable sample code.
Step 1: Initialize a client
Alibaba Cloud SDKs support multiple credential types, including AccessKey pairs and Security Token Service (STS) tokens. This example uses an AccessKey pair. For other credential options, see Manage access credentials.
<?php
require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use Darabonba\OpenApi\Models\Config;
class Sample
{
public static function createClient()
{
$config = new Config([
// Read credentials from environment variables to avoid hardcoding sensitive values.
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
"endpoint" => "ecs.cn-hangzhou.aliyuncs.com",
]);
return new Ecs($config);
}
}Step 2: Create a request object
Each operation has a corresponding request object named {OperationName}Request. For DescribeInstances, the request object is DescribeInstancesRequest.
Before constructing the request, review the available parameters in the DescribeInstances API reference.
// Create a request object.
$describeInstancesRequest = new DescribeInstancesRequest([
"regionId" => "cn-beijing"
]);Step 3: Call the API operation
Each operation has a corresponding response object named {OperationName}Response. For DescribeInstances, the response is a DescribeInstancesResponse object.
Pass a RuntimeOptions object to configure timeout and proxy settings. For details, see Advanced settings.
// Create a runtime configuration object for timeout and proxy settings.
$runtime = new RuntimeOptions();
// Send the request.
$describeInstancesResponse = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);Step 4: Handle exceptions
The SDK raises two exception types:
`TeaUnableRetryError` — thrown when a network error causes all retry attempts to fail. Call
getLastException()to retrieve details of the last failed request, useful for diagnosing connectivity issues.`TeaError` — thrown for business-level errors returned by the API, such as invalid parameters or insufficient permissions. Use
getMessage()for a human-readable description,getCode()for the error code to look up in the API reference, and$error->datafor the full structured error payload.
In production, log error details, alert where appropriate, and implement retry logic for transient failures.
Complete sample code
<?php
require_once 'vendor/autoload.php';
use AlibabaCloud\SDK\Ecs\V20140526\Ecs;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ecs\V20140526\Models\DescribeInstancesRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
class Sample
{
public static function main()
{
try {
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
// Use the endpoint that matches the target region.
"endpoint" => "ecs.cn-beijing.aliyuncs.com",
]);
$client = new Ecs($config);
// Create a request object.
$describeInstancesRequest = new DescribeInstancesRequest([
"regionId" => "cn-beijing"
]);
// Create a runtime configuration object for timeout and proxy settings.
$runtime = new RuntimeOptions();
// Send the request.
$describeInstancesResponse = $client->describeInstancesWithOptions($describeInstancesRequest, $runtime);
var_dump($describeInstancesResponse);
} catch (\Exception $error) {
if ($error instanceof TeaError) {
// Business error: use getMessage() for a description, getCode() to look up
// the error in the API reference, and $error->data for the full payload.
print_r("message:" . $error->getMessage() . "\n");
print_r("code:" . $error->getCode() . "\n");
print_r($error->data);
} elseif ($error instanceof TeaUnableRetryError) {
// Network error: call getLastException() to retrieve the last failed request
// details for diagnosing connectivity issues.
print_r($error->getLastException());
} else {
// Unexpected error: log the message for investigation.
print_r("message:" . $error->getMessage());
}
}
}
}
Sample::main();What's next
Make generic calls to any ECS API operation without a typed request object: Generic calls
If you are using the older SDK version, see V1.0 PHP SDK