Here are some useful PHP code examples to help you along with Amazon Web Services (AWS). This post is updated frequently, so bookmark this page! Also, feel free to suggest an example code that others may find useful.
Pro tip!
Some of the AWS APIs provide a lot of data back in the form of associative arrays. Unfortunately, traversing these arrays can be painful without a little help. Thank goodness for JMESPath! JMESPath lets extract elements from a JSON document in a declarative manner.
Additionally, read https://aws.amazon.com/sdk-for-php/ to help you set up the AWS SDK the first time.
How to create an AWS PHP client connection
The PHP code examples for AWS show a few common ways of creating a connection.
AWS client connection using the default credentials file:
try {
$client = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-2'
]);
} catch (AwsException $e) {
//handle exception
}
Here is an example where the AWS client connects directly using AWS IAM credentials:
//Create a client connection using AWS IAM credentials
try {
//get the AWS IAM key and secret from an environment variable
$awsCredentials = new Aws\Credentials\Credentials(getenv("AWS_KEY"), getenv("AWS_SECRET"));
$client = new Aws\CloudWatchLogs\CloudWatchLogsClient([
'version' => 'latest',
'region' => getenv("AWS_REGION"),
'credentials' => $awsCredentials
]);
} catch (AwsException $e) {
//handle exception
}
AWS client connection using a custom .ini file to specify credentials using the CredentialProvider:
try {
//get the credentials from a custom ini file
$provider = CredentialProvider::ini(null, "/path/to/your/config.ini");
//create connection
$awsCredentials = [
'version' => 'latest',
'region' => getenv("AWS_REGION"),
'credentials' => $provider
];
$client = new SqsClient($awsCredentials);
} catch (AwsException $e) {
//handle exception
}
How to use AWS EC2 with PHP
This example will show how you connect to AWS EC2 and access things like the security groups.
// Describe all the AWS instances in a region
$clientConfig = [
'DryRun' => false, //check whether you have the required permissions for the action
'IncludeAllInstances' => true, //includes all or only running instances
];
$result = $client->describeInstances($clientConfig);
foreach ($result['Reservations'] as $reservation) {
foreach ($reservation['Instances'] as $instance) {
var_dump([
"instanceId" => ( isset($instance['InstanceId']) ? $instance['InstanceId'] : '' ),
"imageId" => ( isset($instance['ImageId']) ? $instance['ImageId'] : '' ),
"instanceType" => ( isset($instance['InstanceType']) ? $instance['InstanceType'] : ''),
"keyName" => ( isset($instance['KeyName']) ? $instance['KeyName'] : '' ),
"instanceName" => $instanceName,
"availabilityZone" => ( isset($instance['Placement']['AvailabilityZone']) ? $instance['Placement']['AvailabilityZone'] : ''),
"privateDnsName" => ( isset($instance['PrivateDnsName']) ? $instance['PrivateDnsName'] : 'n/a' ),
"privateIpAddress" => ( isset($instance['PrivateIpAddress']) ? $instance['PrivateIpAddress'] : 'n/a' ),
"publicDnsName" => ( isset($instance['PublicDnsName']) ? $instance['PublicDnsName'] : 'n/a' ),
"instanceState" => ( isset($instance['State']['Name']) ? $instance['State']['Name'] : '' ),
"publicIpAddress" => ( isset($instance['PublicIpAddress']) ? $instance['PublicIpAddress'] : 'n/a'),
"securityGroupIds" => implode(COMMA, $securityGroupIds),
"subnetId" => ( isset($instance['SubnetId']) ? $instance['SubnetId'] : '' ),
"vpcId" => ( isset($instance['VpcId']) ? $instance['VpcId'] : '' ),
"architecture" => ( isset($instance['Architecture']) ? $instance['Architecture'] : '' ),
"awsAccountId" => ( isset($reservation['OwnerId']) ? $reservation['OwnerId'] : '' ),
"credentialId" => $args['credentialId'],
"region" => $args['awsRegion']
]);
}
}
// Describe security groups
$result = $client->describeSecurityGroups([]);
foreach ($result['SecurityGroups'] as $securityGroup) {
//check inbound rules
$ipPermissionsIngress = $securityGroup['IpPermissions'];
foreach ($ipPermissionsIngress as $ipPermissionIngress) {
foreach ($ipPermissionIngress['IpRanges'] as $ipRange) {
if ($ipRange['CidrIp'] == "0.0.0.0/0") {
//do something
}
}
}
//check outbound rules
$ipPermissionsEgress = $securityGroup['IpPermissionsEgress'];
foreach ($ipPermissionsEgress as $ipPermissionEgress) {
foreach ($ipPermissionEgress['IpRanges'] as $ipRange) {
if ($ipRange['CidrIp'] == "0.0.0.0/0") {
//do something
}
}
}
var_dump([
"securityGroupName" => $securityGroup['GroupName'],
"securityGroupId" => $securityGroup['GroupId'],
"vpcId" => $securityGroup['VpcId'],
"awsRegion" => $args["awsRegion"]
]);
}
// Describe security group rules
$request = array_merge($request, [
'GroupIds' => explode(COMMA, $args["securityGroupIds"])
]);
$result = $client->describeSecurityGroups($request);
//inbound rules
foreach ($result['SecurityGroups'] as $securityGroup) {
$ipPermissions = $securityGroup['IpPermissions'];
foreach ($ipPermissions as $ipPermission) {
var_dump(ipPermission);
}
}
//outbound rules
foreach ($result['SecurityGroups'] as $securityGroup) {
$ipPermissionsEgress = $securityGroup['IpPermissionsEgress'];
foreach ($ipPermissionsEgress as $ipPermissionEgress) {
var_dump(ipPermissionEgress);
}
}
// Create a security group
$result = $client->createSecurityGroup([
'GroupName' => $securityGroupName,
'Description' => $securityGroupName,
'VpcId' => $vpcId,
]);
// Remove a security group
$result = $client->deleteSecurityGroup([
'GroupId' => $securityGroupId,
]);
// Start and stop an instance
if ($action == "start") {
$result = $client->startInstances(array(
'InstanceIds' => $instanceArr,
));
}
if ($action == "stop") {
$result = $client->stopInstances(array(
'InstanceIds' => $instanceArr,
));
}
// Change the security groups and instance is assigned too
$query = [
'InstanceId' => $instanceId,
'Groups' => explode(COMMA, $groupNamesCSV)
];
$client->modifyInstanceAttribute($query);
// Authorize security group ingress
$rule = [
"FromPort" => $fromPort,
"IpProtocol" => $protocol,
"IpRanges" => [
[
"CidrIp" => $CIDR,
"Description" => $description
]
],
"ToPort" => $toPort,
];
$client->authorizeSecurityGroupIngress([
'GroupId' => $securityGroupId,
'IpPermissions' => [
$rule,
],
]);
// Authorize security group egress
$rule = [
"FromPort" => $fromPort,
"IpProtocol" => $protocol,
"IpRanges" => [
[
"CidrIp" => $CIDR,
"Description" => $description
]
],
"ToPort" => $toPort,
];
$client->authorizeSecurityGroupEgress([
'GroupId' => $securityGroupId,
'IpPermissions' => [
$rule,
],
]);
// Revoke security group ingress
if ($args["protocol"] == "ALL") {
$rule = [
'IpProtocol' => -1,
'IpRanges' => [
[
'CidrIp' => $args["cidrIp"]
],
],
];
}
if ($args["protocol"] != "ALL") {
$rule = [
'IpProtocol' => $args["protocol"],
'FromPort' => $args["fromPort"],
'ToPort' => $args["toPort"],
'IpRanges' => [
[
'CidrIp' => $args["cidrIp"]
],
],
];
}
$result = $client->revokeSecurityGroupIngress([
'GroupId' => $args["securityGroupId"],
'IpPermissions' => [
$this->__buildSecurityGroupRuleArray($args),
],
]);
// Revoke security group egress
if ($args["protocol"] == "ALL") {
$rule = [
'IpProtocol' => -1,
'IpRanges' => [
[
'CidrIp' => $args["cidrIp"]
],
],
];
}
if ($args["protocol"] != "ALL") {
$rule = [
'IpProtocol' => $args["protocol"],
'FromPort' => $args["fromPort"],
'ToPort' => $args["toPort"],
'IpRanges' => [
[
'CidrIp' => $args["cidrIp"]
],
],
];
}
$result = $client->revokeSecurityGroupEgress([
'GroupId' => $args["securityGroupId"],
'IpPermissions' => [
$this->__buildSecurityGroupRuleArray($args),
],
]);
How to use AWS SQS with PHP
See how you can send, receive, delete and change message visibility on your AWS SQS queue.
// Send a message to SQS
$params = [
'MessageAttributes' => $messageAttributes,
'MessageBody' => $messageBody,
'QueueUrl' => $queueUrl,
'DelaySeconds' => $delaySeconds
];
$result = $client->sendMessage($params);
// Receive a message from SQS
$result = $client->receiveMessage(array(
'AttributeNames' => ['SentTimestamp'],
'MaxNumberOfMessages' => $maxJobs,
'MessageAttributeNames' => ['All'],
'QueueUrl' => $queueUrl, // REQUIRED
'WaitTimeSeconds' => 0,
));
return $result;
// Delete a message from SQS
$result = $client->deleteMessage(array(
'QueueUrl' => $queueUrl, // REQUIRED
'ReceiptHandle' => $receiptHandle,
));
return $result;
// Change an SQS message's visibility
$result = $client->changeMessageVisibility(array(
'QueueUrl' => $queueUrl, // REQUIRED
'ReceiptHandle' => $receiptHandle,
'VisibilityTimeout' => $visibilityTimeoutSecs
));
return $result;
How to use AWS Secrets Manager with PHP
This example shows you can fetch a secret from AWS Secrets Manager.
// Fetch a secret
$result = $client->getSecretValue([
'SecretId' => $secretName,
]);
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (isset($result['SecretString'])) {
$secret = $result['SecretString'];
} else {
$secret = base64_decode($result['SecretBinary']);
}
// Decode json
$jsonObj = json_decode($secret, true);
if ($jsonObj === null && json_last_error() !== JSON_ERROR_NONE) {
throw new Exception("Secret json decode failed!");
}
return $jsonObj;