PHP code examples for AWS

13Shares

Here are useful PHP code examples for your next project that integrates with AWS. This post is updated frequently so bookmark this page! Also, feel free to suggest examples that you found useful.

You should read https://aws.amazon.com/sdk-for-php/ to help you setup the AWS SDK the first time.

Pro tip!

Some of the AWS APIs provide a lot of data back in the form of associative arrays. Traversing these arrays can be painful without a little help. This is where JMESPath becomes quite useful! JMESPath enables you to declaratively specify how to extract elements from a JSON document.

How to create an AWS PHP client connection

The PHP code examples for AWS shows a few common ways of creating a connection. Below is an example of setting up a connection by not using the default AWS credentials file.

//Standard way of creating an AWS client connection using PHP

try {
  $client = new Aws\S3\S3Client([
      'version' => 'latest',
      'region' => 'us-east-2'
  ]);
} catch (AwsException $e) {
    //handle exception
}

//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
}

//Create a client connection by not using the default AWS IAM credentials file

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 acess 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 chnge 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;

You may also want to see some of my other posts about PHP coding here: https://anto.online/category/coding/php/.

Hi, my name is Anto! I am a cloud computing hobbyist! Give me anything to do with the cloud, and I am interested. I work for a Cloud computing company by day and as a Cloud computing hobbyist by night! My projects use PHP, NodeJs, Ubuntu, MySQL and of course Amazon Web Services. Hopefully, my blog aids your cloud journey! Feel free to post a comment and share your thoughts.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.