### PHP S3 Getting Started Example Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_s3_code_examples.md This comprehensive example demonstrates a full S3 workflow including bucket creation, file upload, download, copy, listing, and deletion. It requires the AWS SDK for PHP and a configured AWS environment. Ensure you have a 'testfile.txt' in the same directory as the script. ```php echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon S3 getting started demo using PHP!\n"); echo("--------------------------------------\n"); $region = 'us-west-2'; $this->s3client = new S3Client([ 'region' => $region, ]); /* Inline declaration example $s3client = new Aws S3 S3Client(['region' => 'us-west-2']); */ $this->bucketName = "amzn-s3-demo-bucket-" . uniqid(); try { $this->s3client->createBucket([ 'Bucket' => $this->bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => $region], ]); echo "Created bucket named: $this->bucketName \n"; } catch (Exception $exception) { echo "Failed to create bucket $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket creation before continuing."); } $fileName = __DIR__ . "/local-file-" . uniqid(); try { $this->s3client->putObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, 'SourceFile' => __DIR__ . '/testfile.txt' ]); echo "Uploaded $fileName to $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to upload $fileName with error: " . $exception->getMessage(); exit("Please fix error with file upload before continuing."); } try { $file = $this->s3client->getObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, ]); $body = $file->get('Body'); $body->rewind(); echo "Downloaded the file and it begins with: {" . $body->read(26) . "}.\n"; } catch (Exception $exception) { echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with file downloading before continuing."); } try { $folder = "copied-folder"; $this->s3client->copyObject([ 'Bucket' => $this->bucketName, 'CopySource' => "$this->bucketName/$fileName", 'Key' => "$folder/$fileName-copy", ]); echo "Copied $fileName to $folder/$fileName-copy.\n"; } catch (Exception $exception) { echo "Failed to copy $fileName with error: " . $exception->getMessage(); exit("Please fix error with object copying before continuing."); } try { $contents = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); echo "The contents of your bucket are: \n"; foreach ($contents['Contents'] as $content) { echo $content['Key'] . "\n"; } } catch (Exception $exception) { echo "Failed to list objects in $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with listing objects before continuing."); } try { $objects = []; foreach ($contents['Contents'] as $content) { $objects[] = [ 'Key' => $content['Key'], ]; } $this->s3client->deleteObjects([ 'Bucket' => $this->bucketName, 'Delete' => [ 'Objects' => $objects, ], ]); $check = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); if (isset($check['Contents']) && count($check['Contents']) > 0) { throw new Exception("Bucket wasn't empty."); } echo "Deleted all objects and folders from $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with object deletion before continuing."); } try { $this->s3client->deleteBucket([ 'Bucket' => $this->bucketName, ]); echo "Deleted bucket $this->bucketName.\n"; } catch (Exception $exception) { ``` -------------------------------- ### Start Crawler with AWS SDK for PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md This example demonstrates how to initiate a Glue crawler. Ensure the crawler name is valid. ```php $crawlerName = "example-crawler-test-" . $uniqid; $databaseName = "doc-example-database-$uniqid"; $glueService->startCrawler($crawlerName); ``` ```php public function startCrawler($crawlerName): Result { return $this->glueClient->startCrawler([ 'Name' => $crawlerName, ]); } ``` -------------------------------- ### Getting Started with AWS Glue using PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md This comprehensive example demonstrates the creation of an AWS Glue crawler, a job for data transformation, and the management of related resources. It requires AWS credentials and specific Python scripts for the job. ```php namespace Glue; use Aws\Glue\GlueClient; use Aws\S3\S3Client; use AwsUtilities\AWSServiceClass; use GuzzleHttp\Psr7\Stream; use Iam\IAMService; class GettingStartedWithGlue { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the AWS Glue getting started demo using PHP!\n"); echo("--------------------------------------\n"); $clientArgs = [ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]; $uniqid = uniqid(); $glueClient = new GlueClient($clientArgs); $glueService = new GlueService($glueClient); $iamService = new IAMService(); $crawlerName = "example-crawler-test-" . $uniqid; AWSServiceClass::$waitTime = 5; AWSServiceClass::$maxWaitAttempts = 20; $role = $iamService->getRole("AWSGlueServiceRole-DocExample"); $databaseName = "doc-example-database-" . $uniqid; $path = 's3://crawler-public-us-east-1/flight/2016/csv'; $glueService->createCrawler($crawlerName, $role['Role']['Arn'], $databaseName, $path); $glueService->startCrawler($crawlerName); echo "Waiting for crawler"; do { $crawler = $glueService->getCrawler($crawlerName); echo "."; sleep(10); } while ($crawler['Crawler']['State'] != "READY"); echo "\n"; $database = $glueService->getDatabase($databaseName); echo "Found a database named " . $database['Database']['Name'] . "\n"; //Upload job script $s3client = new S3Client($clientArgs); $bucketName = "test-glue-bucket-" . $uniqid; $s3client->createBucket([ 'Bucket' => $bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => 'us-west-2'], ]); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => 'run_job.py', 'SourceFile' => __DIR__ . '/flight_etl_job_script.py' ]); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => 'setup_scenario_getting_started.yaml', 'SourceFile' => __DIR__ . '/setup_scenario_getting_started.yaml' ]); $tables = $glueService->getTables($databaseName); $jobName = 'test-job-' . $uniqid; $scriptLocation = "s3://$bucketName/run_job.py"; $job = $glueService->createJob($jobName, $role['Role']['Arn'], $scriptLocation); $outputBucketUrl = "s3://$bucketName"; $runId = $glueService->startJobRun($jobName, $databaseName, $tables, $outputBucketUrl)['JobRunId']; echo "waiting for job"; do { $jobRun = $glueService->getJobRun($jobName, $runId); echo "."; sleep(10); } while (!array_intersect([$jobRun['JobRun']['JobRunState']], ['SUCCEEDED', 'STOPPED', 'FAILED', 'TIMEOUT'])); echo "\n"; $jobRuns = $glueService->getJobRuns($jobName); $objects = $s3client->listObjects([ 'Bucket' => $bucketName, ])['Contents']; foreach ($objects as $object) { echo $object['Key'] . "\n"; } echo "Downloading " . $objects[1]['Key'] . "\n"; /** @var Stream $downloadObject */ $downloadObject = $s3client->getObject([ 'Bucket' => $bucketName, 'Key' => $objects[1]['Key'], ])['Body']->getContents(); echo "Here is the first 1000 characters in the object."; echo substr($downloadObject, 0, 1000); $jobs = $glueService->listJobs(); echo "Current jobs:\n"; foreach ($jobs['JobNames'] as $jobsName) { echo "{$jobsName}\n"; } echo "Delete the job.\n"; $glueClient->deleteJob([ 'JobName' => $job['Name'], ]); echo "Delete the tables.\n"; foreach ($tables['TableList'] as $table) { $glueService->deleteTable($table['Name'], $databaseName); } } } ``` -------------------------------- ### Getting Started with DynamoDB using PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_dynamodb_code_examples.md This example demonstrates the fundamental operations for using DynamoDB with PHP. It covers creating a table, adding and retrieving items, updating attributes, performing batch writes, and deleting items. Ensure you have the necessary AWS SDK for PHP setup and supporting files. ```php namespace DynamoDb\Basics; use Aws\DynamoDb\Marshaler; use DynamoDb; use DynamoDb\DynamoDBAttribute; use DynamoDb\DynamoDBService; use function AwsUtilities\loadMovieData; use function AwsUtilities\testable_readline; class GettingStartedWithDynamoDB { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the Amazon DynamoDB getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new DynamoDBService(); $tableName = "ddb_demo_table_$uuid"; $service->createTable( $tableName, [ new DynamoDBAttribute('year', 'N', 'HASH'), new DynamoDBAttribute('title', 'S', 'RANGE') ] ); echo "Waiting for table..."; $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]); echo "table $tableName found!\n"; echo "What's the name of the last movie you watched?\n"; while (empty($movieName)) { $movieName = testable_readline("Movie name: "); } echo "And what year was it released?\n"; $movieYear = "year"; while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) { $movieYear = testable_readline("Year released: "); } $service->putItem([ 'Item' => [ 'year' => [ 'N' => "$movieYear", ], 'title' => [ 'S' => $movieName, ], ], 'TableName' => $tableName, ]); echo "How would you rate the movie from 1-10?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } echo "What was the movie about?\n"; while (empty($plot)) { $plot = testable_readline("Plot summary: "); } $key = [ 'Item' => [ 'title' => [ 'S' => $movieName, ], 'year' => [ 'N' => $movieYear, ], ] ]; $attributes = ["rating" => [ 'AttributeName' => 'rating', 'AttributeType' => 'N', 'Value' => $rating, ], 'plot' => [ 'AttributeName' => 'plot', 'AttributeType' => 'S', 'Value' => $plot, ] ]; $service->updateItemAttributesByKey($tableName, $key, $attributes); echo "Movie added and updated."; $batch = json_decode(loadMovieData()); $service->writeBatch($tableName, $batch); $movie = $service->getItemByKey($tableName, $key); echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n"; echo "What rating would you like to give {$movie['Item']['title']['S']}?\n"; $rating = 0; while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) { $rating = testable_readline("Rating (1-10): "); } $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating); $movie = $service->getItemByKey($tableName, $key); echo "Ok, you have rated {$movie['Item']['title']['S']} as a {$movie['Item']['rating']['N']}\n"; $service->deleteItemByKey($tableName, $key); echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n"; echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n"; $birthYear = "not a number"; while (!is_numeric($birthYear) || $birthYear >= date("Y")) { $birthYear = testable_readline("Birth year: "); } $birthKey = [ 'Key' => [ ``` -------------------------------- ### Navigate to S3 Example Directory Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/cloud9.md Change directory to the S3 examples folder within the cloned repository. This is a prerequisite for running S3-related code examples. ```bash $ cd aws-doc-sdk-examples/php/example_code/s3 ``` -------------------------------- ### Hello Amazon S3: List Buckets Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_s3_code_examples.md Get started with Amazon S3 by listing all buckets in your account. Requires the AWS SDK for PHP and a configured AWS region. ```php use Aws\S3\S3Client; $client = new S3Client(['region' => 'us-west-2']); $results = $client->listBuckets(); var_dump($results); ``` -------------------------------- ### MultipartUploader Configuration Example Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-multipart-upload.md Demonstrates how to instantiate MultipartUploader with specific parameters. ```php new MultipartUploader($client, $source, ['params' => ['CacheControl' => {{}}]]) ``` -------------------------------- ### StartCrawler Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md Starts an AWS Glue crawler. This example shows how to initiate a crawler using its name. ```APIDOC ## StartCrawler ### Description Starts an AWS Glue crawler. ### Method `startCrawler(string $crawlerName): Result` ### Parameters - **crawlerName** (string) - Required - The name of the crawler to start. ### Request Example ```php $crawlerName = "example-crawler-test-" . $uniqid; $glueService->startCrawler($crawlerName); ``` ### Response - **Result** - An object indicating the success of the operation. ``` -------------------------------- ### ObjectUploader Configuration Example Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-multipart-upload.md Instantiates an ObjectUploader with custom parameters for a multipart upload. This example shows how to pass an associative array for 'params' to configure subcommands like setting CacheControl. ```php new ObjectUploader($bucket, $key, $body, $acl, ['params' => ['CacheControl' => {{}}]]) ``` -------------------------------- ### Get Tables with AWS SDK for PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md This example shows how to retrieve a list of tables within a specified Glue database. Ensure the database name is correctly provided. ```php $databaseName = "doc-example-database-$uniqid"; $tables = $glueService->getTables($databaseName); ``` ```php public function getTables($databaseName): Result { return $this->glueClient->getTables([ 'DatabaseName' => $databaseName, ]); } ``` -------------------------------- ### Create IAM User, Role, Policy, Assume Role, and List S3 Buckets with PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_iam_code_examples.md This comprehensive example demonstrates creating an IAM user, an IAM role with a policy allowing it to list S3 buckets, and a user policy to allow assuming that role. It then attempts to list S3 buckets with the user (which should fail), assumes the role using STS, and successfully lists S3 buckets with the assumed role's temporary credentials. Finally, it cleans up all created resources. Ensure you have the AWS SDK for PHP v3 installed via Composer. ```php namespace Iam\Basics; require 'vendor/autoload.php'; use Aws\Credentials\Credentials; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\Sts\StsClient; use Iam\IAMService; echo("\n"); echo("--------------------------------------\n"); print("Welcome to the IAM getting started demo using PHP!\n"); echo("--------------------------------------\n"); $uuid = uniqid(); $service = new IAMService(); $user = $service->createUser("iam_demo_user_$uuid"); echo "Created user with the arn: {$user['Arn']}\n"; $key = $service->createAccessKey($user['UserName']); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; $listAllBucketsPolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"s3:ListAllMyBuckets\", \"Resource\": \"arn:aws:s3:::*\"}] }"; $listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument); echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n"; $service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']); $inlinePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Action\": \"sts:AssumeRole\", \"Resource\": \"{$assumeRoleRole['Arn']}\"}] }"; $inlinePolicy = $service->createUserPolicy("iam_demo_inline_policy_$uuid", $inlinePolicyDocument, $user['UserName']); //First, fail to list the buckets with the user $credentials = new Credentials($key['AccessKeyId'], $key['SecretAccessKey']); $s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]); try { $s3Client->listBuckets([ ]); echo "this should not run"; } catch (S3Exception $exception) { echo "successfully failed!\n"; } $stsClient = new StsClient(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]); sleep(10); $assumedRole = $stsClient->assumeRole([ 'RoleArn' => $assumeRoleRole['Arn'], 'RoleSessionName' => "DemoAssumeRoleSession_$uuid", ]); $assumedCredentials = [ 'key' => $assumedRole['Credentials']['AccessKeyId'], 'secret' => $assumedRole['Credentials']['SecretAccessKey'], 'token' => $assumedRole['Credentials']['SessionToken'], ]; $s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $assumedCredentials]); try { $s3Client->listBuckets([]); echo "this should now run!\n"; } catch (S3Exception $exception) { echo "this should now not fail\n"; } $service->detachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']); $deletePolicy = $service->deletePolicy($listAllBucketsPolicy['Arn']); echo "Delete policy: {$listAllBucketsPolicy['PolicyName']}\n"; $deletedRole = $service->deleteRole($assumeRoleRole['Arn']); echo "Deleted role: {$assumeRoleRole['RoleName']}\n"; $deletedKey = $service->deleteAccessKey($key['AccessKeyId'], $user['UserName']); $deletedUser = $service->deleteUser($user['UserName']); echo "Delete user: {$user['UserName']}\n"; ``` -------------------------------- ### Start Crawler Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md Starts an AWS Glue crawler to crawl data sources. ```APIDOC ## startCrawler ### Description Initiates the execution of a specified AWS Glue crawler. ### Method Signature public function startCrawler(string $crawlerName): Result ### Parameters - **crawlerName** (string) - Required - The name of the crawler to start. ### Response Example (Result object indicating the crawler has started) ``` -------------------------------- ### List Files in S3 Example Directory Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/cloud9.md List the contents of the S3 example directory to view available code files, such as ListBuckets.php. ```bash $ ls ``` -------------------------------- ### CreateDBSnapshot Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_rds_code_examples.md The following code example shows how to use `CreateDBSnapshot` to create a manual snapshot of a DB instance. ```APIDOC ## CreateDBSnapshot ### Description Creates a manual snapshot of a DB instance. Snapshots are backups of your database. ### Method `createDBSnapshot` ### Parameters #### Request Body - **DBInstanceIdentifier** (string) - Required - The identifier of the DB instance to snapshot. - **DBSnapshotIdentifier** (string) - Required - The identifier for the DB snapshot. ### Request Example ```php require __DIR__ . '/vendor/autoload.php'; use Aws\Exception\AwsException; $rdsClient = new Aws\Rds\RdsClient([ 'region' => 'us-east-2' ]); $dbIdentifier = '<<{{db-identifier}}>>'; $snapshotName = '<<{{backup_2018_12_25}}>>'; try { $result = $rdsClient->createDBSnapshot([ 'DBInstanceIdentifier' => $dbIdentifier, 'DBSnapshotIdentifier' => $snapshotName, ]); var_dump($result); } catch (AwsException $e) { echo $e->getMessage(); echo "\n"; } ``` ### Response #### Success Response (200) - **DBSnapshot** (array) - Contains a description of the created DB snapshot. #### Response Example ```json { "@metadata": { "statusCode": 200, "effectiveUri": "https://rds.us-east-2.amazonaws.com", "headers": { "content-type": "application/x-amz-json-1.1", "date": "Mon, 01 Jan 2024 12:00:00 GMT", "server": "amazon.com, Amazon Internal", "x-amz-request-id": "some-request-id" }, "transferStats": { "total": { "bytes": 12345 } } }, "DBSnapshot": { "DBSnapshotIdentifier": "<<{{backup_2018_12_25}}>>", "DBInstanceIdentifier": "<<{{db-identifier}}>>", "SnapshotCreateTime": "2024-01-01T12:00:00.000Z", "Engine": "MySQL", "AllocatedStorage": 5, "Status": "creating" } } ``` ``` -------------------------------- ### ListPolicies Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_iam_code_examples.md This example demonstrates how to list all IAM policies that you have created. You can filter by path prefix and use pagination. ```APIDOC ## ListPolicies ### Description Lists all the IAM policies that you have created. You can use the path-prefix to limit the list to only those policies that are prefixes of the specified path name. ### Method `listPolicies` ### Parameters #### Path Parameters - **PathPrefix** (string) - Optional - The path prefix to filter the results by. - **Marker** (string) - Optional - The marker to use for pagination. - **MaxItems** (integer) - Optional - The maximum number of items to return. ### Request Example ```php public function listPolicies($pathPrefix = "", $marker = "", $maxItems = 0) { $listPoliciesArguments = []; if ($pathPrefix) { $listPoliciesArguments["PathPrefix"] = $pathPrefix; } if ($marker) { $listPoliciesArguments["Marker"] = $marker; } if ($maxItems) { $listPoliciesArguments["MaxItems"] = $maxItems; } return $this->iamClient->listPolicies($listPoliciesArguments); } ``` ### Response #### Success Response (200) Returns a list of IAM policies. The response includes the policy name, ARN, default version ID, and path for each policy. ``` -------------------------------- ### Start AWS Glue Crawler Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md Starts an AWS Glue crawler. Use this after creating or updating a crawler to begin scanning data sources. ```php public function startCrawler($crawlerName): Result { return $this->glueClient->startCrawler([ 'Name' => $crawlerName, ]); } ``` -------------------------------- ### Start Job Run Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md Starts a run for a specified AWS Glue ETL job. ```APIDOC ## startJobRun ### Description Initiates a new execution run for an AWS Glue ETL job with specified parameters. ### Method Signature public function startJobRun(string $jobName, string $databaseName, array $tables, string $outputBucketUrl): Result ### Parameters - **jobName** (string) - Required - The name of the job to run. - **databaseName** (string) - Required - The name of the input database for the job. - **tables** (array) - Required - An array containing table information, expected to have 'TableList' with at least one table. - **outputBucketUrl** (string) - Required - The S3 URL where the job output should be stored. ### Response Example (Result object containing details of the job run) ``` -------------------------------- ### Clone AWS SDK for PHP Examples Repository Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/cloud9.md Use this command in the Cloud9 terminal to download all official AWS SDK for PHP code examples into your environment's root directory. ```bash $ git clone https://github.com/awsdocs/aws-doc-sdk-examples.git ``` -------------------------------- ### Install AWS SDK for PHP using Composer Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/cloud9.md Use this Composer command to add the AWS SDK for PHP as a project dependency. Ensure Composer is installed globally or use the provided command to run it via the `composer.phar` file. ```bash $ composer require aws/aws-sdk-php ``` ```bash $ php -d memory_limit=-1 composer.phar require aws/aws-sdk-php ``` -------------------------------- ### Start AWS Glue Job Run Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md Starts a run for a specified AWS Glue job. It passes arguments including input database, table, and output bucket URL, which are used by the ETL script. ```php public function startJobRun($jobName, $databaseName, $tables, $outputBucketUrl): Result { return $this->glueClient->startJobRun([ 'JobName' => $jobName, 'Arguments' => [ 'input_database' => $databaseName, 'input_table' => $tables['TableList'][0]['Name'], 'output_bucket_url' => $outputBucketUrl, '--input_database' => $databaseName, '--input_table' => $tables['TableList'][0]['Name'], '--output_bucket_url' => $outputBucketUrl, ], ]); } ``` -------------------------------- ### Create an IAM user Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/iam-examples-managing-users.md This example demonstrates how to create a new IAM user with a specified username. ```APIDOC ## Create an IAM user ### Description Creates a new IAM user. ### Method `createUser` ### Parameters #### Request Body - **UserName** (string) - Required - The name for the new IAM user. ### Request Example ```php $client->createUser([ 'UserName' => 'string' ]); ``` ### Response #### Success Response (200) Returns information about the newly created user. #### Response Example ```json { "User": { "Path": "string", "UserName": "string", "UserId": "string", "Arn": "string", "CreateDate": "datetime" }, "ResponseMetadata": { "RequestId": "string" } } ``` ``` -------------------------------- ### StartJobRun Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md This example demonstrates how to initiate a job run in AWS Glue using the PHP SDK. It includes setting up job parameters and arguments, and retrieving the JobRunId from the response. ```APIDOC ## `StartJobRun` ### Description Initiates a new run for a specified AWS Glue job. This operation allows you to pass arguments to the job, such as input database, table, and output bucket URL. ### Method Signature `public function startJobRun($jobName, $databaseName, $tables, $outputBucketUrl): Result` ### Parameters - **`$jobName`** (string) - The name of the job to run. - **`$databaseName`** (string) - The name of the input database for the job. - **`$tables`** (array) - An array containing information about the tables, expected to have a 'TableList' key. - **`$outputBucketUrl`** (string) - The S3 URL where the job output should be stored. ### Request Body (Conceptual) This method constructs an arguments array for the `startJobRun` API call, including: - `input_database`: The name of the input database. - `input_table`: The name of the input table (extracted from the `$tables` parameter). - `output_bucket_url`: The S3 URL for the output bucket. - `--input_database`: A prefixed argument for the input database. - `--input_table`: A prefixed argument for the input table. - `--output_bucket_url`: A prefixed argument for the output bucket URL. ### Response - **`JobRunId`** (string) - The unique identifier for the initiated job run. ``` -------------------------------- ### Create and Wait for S3 Bucket Existence Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_waiters.md This example demonstrates creating an S3 bucket and then using a waiter to confirm its existence. If the waiter polls too many times, a RuntimeException will be thrown. ```php // Create a bucket $s3Client->createBucket(['Bucket' => 'amzn-s3-demo-bucket']); // Wait until the created bucket is available $s3Client->waitUntil('BucketExists', ['Bucket' => 'amzn-s3-demo-bucket']); ``` -------------------------------- ### Get information about an IAM user Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/iam-examples-managing-users.md This example shows how to retrieve detailed information about a specific IAM user. ```APIDOC ## Get information about an IAM user ### Description Retrieves the user name, path, user ID, and ARN for the IAM user. ### Method `getUser` ### Parameters #### Request Body - **UserName** (string) - Required - The name of the user to retrieve information for. ### Request Example ```php $client->getUser([ 'UserName' => 'string' ]); ``` ### Response #### Success Response (200) Returns detailed information about the specified IAM user. #### Response Example ```json { "User": { "Path": "string", "UserName": "string", "UserId": "string", "Arn": "string", "CreateDate": "datetime" }, "ResponseMetadata": { "RequestId": "string" } } ``` ``` -------------------------------- ### Get AWS Glue Job Run Status - PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_glue_code_examples.md This example shows how to get the status of an AWS Glue job run and waits until it completes or fails. It polls the job run status every 10 seconds. ```php $jobName = 'test-job-' . $uniqid; $outputBucketUrl = "s3://$bucketName"; $runId = $glueService->startJobRun($jobName, $databaseName, $tables, $outputBucketUrl)['JobRunId']; echo "waiting for job"; do { $jobRun = $glueService->getJobRun($jobName, $runId); echo "."; sleep(10); } while (!array_intersect([$jobRun['JobRun']['JobRunState']], ['SUCCEEDED', 'STOPPED', 'FAILED', 'TIMEOUT'])); echo "\n"; public function getJobRun($jobName, $runId, $predecessorsIncluded = false): Result { return $this->glueClient->getJobRun([ 'JobName' => $jobName, 'RunId' => $runId, 'PredecessorsIncluded' => $predecessorsIncluded, ]); } ``` -------------------------------- ### Initialize Auto Scaling Client and Describe Groups in PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_auto-scaling_code_examples.md This example shows how to initialize an Auto Scaling client with specific region, version, and profile, and then describe all Auto Scaling groups. ```php public function helloService() { $autoScalingClient = new AutoScalingClient([ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]); $groups = $autoScalingClient->describeAutoScalingGroups([]); var_dump($groups); } } ``` -------------------------------- ### Create Pre-signed URL for S3 GET Request (PHP) Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-presigned-url.md Generates a pre-signed URL for an HTTP GET request to retrieve an S3 object. The URL is valid for the specified expiration time. Ensure the SDK is installed via Composer. ```php 'us-west-2', ]); // Supply a CommandInterface object and an expires parameter to the `createPresignedRequest` method. $request = $s3Client->createPresignedRequest( $s3Client->getCommand('GetObject', [ 'Bucket' => 'amzn-s3-demo-bucket', 'Key' => 'demo-key', ]), '+1 hour' ); // From the resulting RequestInterface object, you can get the URL. $presignedUrl = (string) $request->getUri(); echo $presignedUrl; ``` -------------------------------- ### Instantiate Aws\Sdk and Create Clients (PHP) Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_migration.md Instantiate the `Aws\Sdk` class with configuration and create service clients using `create()` methods. The 'version' option is required. ```php 'my_profile', 'region' => 'us-east-1', 'version' => 'latest', 'DynamoDb' => [ 'region' => 'us-west-2', ], ]); $sqs = $sdk->createSqs(); // Note: Amazon SQS client will be configured for us-east-1. $dynamodb = $sdk->createDynamoDb(); // Note: DynamoDB client will be configured for us-west-2. ``` -------------------------------- ### ExecuteStatement Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_dynamodb_code_examples.md Demonstrates how to execute PartiQL statements against DynamoDB using the `ExecuteStatement` operation in the AWS SDK for PHP. This includes examples for inserting, getting, updating, and deleting items. ```APIDOC ## `ExecuteStatement` ### Description This method demonstrates executing PartiQL statements against DynamoDB. It can be used for various operations like inserting, getting, updating, and deleting items by providing the appropriate SQL-like statement and parameters. ### Method `executeStatement` ### Parameters - **Statement** (string) - Required - The PartiQL statement to execute. - **Parameters** (array) - Required - An array of parameters to be used in the statement. ### SDK Usage Example (PHP) ```php public function insertItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => "$statement", 'Parameters' => $parameters, ]); } public function getItemByPartiQL(string $tableName, array $key): Result { list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']); return $this->dynamoDbClient->executeStatement([ 'Parameters' => $parameters, 'Statement' => $statement, ]); } public function updateItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); } public function deleteItemByPartiQL(string $statement, array $parameters) { $this->dynamoDbClient->executeStatement([ 'Statement' => $statement, 'Parameters' => $parameters, ]); } ``` For API details, see [ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/ExecuteStatement) in *AWS SDK for PHP API Reference*. ``` -------------------------------- ### Example Directory Download Path Handling Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/directory-operations.md Illustrates how S3 object keys are transformed into local file paths when downloading a directory, considering an S3 prefix and a destination directory. ```php 'default', 'region' => 'us-east-2', ]; // Create an SDK class used to share configuration across clients. $sdk = new Aws\\Sdk($sharedConfig); // Use an Aws\Sdk class to create the S3Client object. $s3 = $sdk->createS3(); $result = $s3->listBuckets(); foreach ($result['Buckets'] as $bucket) { echo $bucket['Name'] . "\n"; } // Convert the result object to a PHP array $array = $result->toArray(); ``` -------------------------------- ### Get an email template Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ses-template.md This example shows how to retrieve the content of an existing email template from Amazon SES using the AWS SDK for PHP. You only need to provide the template name. ```APIDOC ## Get an email template To view the content for an existing email template including the subject line, HTML body, and plain text, use the `GetTemplate` operation. Only TemplateName is required. **Imports** ```php require 'vendor/autoload.php'; use Aws\Exception\AwsException; ``` **Sample Code** ```php $SesClient = new Aws\Ses\SesClient([ 'profile' => 'default', 'version' => '2010-12-01', 'region' => 'us-east-2' ]); $name = 'Template_Name'; try { $result = $SesClient->getTemplate([ 'TemplateName' => $name, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails echo $e->getMessage(); echo "\n"; } ``` ``` -------------------------------- ### Global Configuration for Client Instantiation: AWS SDK for PHP v2 Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_migration.md Configuration file example for setting global defaults and service-specific overrides when instantiating clients in version 2 of the SDK using Aws::factory(). ```php array('_aws'), 'services' => array( 'default_settings' => array( 'params' => array( 'profile' => 'my_profile', 'region' => 'us-east-1' ) ), 'dynamodb' => array( 'extends' => 'dynamodb', 'params' => array( 'region' => 'us-west-2' ) ), ) ); ``` ```php get('sqs'); // Note: SQS client will be configured for us-east-1. $dynamodb = $aws->get('dynamodb'); // Note: DynamoDB client will be configured for us-west-2. ``` -------------------------------- ### Invoke Lambda Function from SQS Trigger (PHP) Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/php_sqs_code_examples.md Implement a Lambda function that receives messages from an SQS queue. This example uses bref/bref and bref/logger for simplicity. Ensure vendor dependencies are installed. ```php // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 logger = $logger; } /** * @throws InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $body = $record->getBody(); // TODO: Do interesting work based on the new message } } } $logger = new StderrLogger(); return new Handler($logger); ``` -------------------------------- ### Using `assumeRoleWithWebIdentityCredentialProvider` Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/assume-role-with-web-identity-provider.md This example demonstrates how to use the `assumeRoleWithWebIdentityCredentialProvider` to obtain credentials and then use them with an S3 client. It also shows how to memoize the provider to avoid repeated loading and parsing. ```APIDOC ## Using `assumeRoleWithWebIdentityCredentialProvider` ### Description This code snippet shows how to instantiate the `assumeRoleWithWebIdentityCredentialProvider` and use it to configure an S3 client. It also demonstrates the use of `CredentialProvider::memoize` to cache the credentials. ### Method `Aws\Credentials\CredentialProvider::assumeRoleWithWebIdentityCredentialProvider()` ### Parameters This method can optionally accept an array of configuration options. The primary option shown is `stsClient`. ### Request Example ```php use Aws\Credentials\CredentialProvider; use Aws\S3\S3Client; $provider = CredentialProvider::assumeRoleWithWebIdentityCredentialProvider(); // Cache the results in a memoize function to avoid loading and parsing // the ini file on every API operation $provider = CredentialProvider::memoize($provider); $client = new S3Client([ 'region' => 'us-west-2', 'version' => '2006-03-01', 'credentials' => $provider ]); ``` ### Response This method returns a callable that, when invoked, will attempt to load credentials. The actual credentials are used by the client configuration. ``` -------------------------------- ### Get SNS Topic Attributes with PHP Source: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.md Retrieve properties of an existing SNS topic using the `GetTopicAttributes` operation. Ensure the AWS SDK for PHP is installed via Composer and the necessary namespaces are imported. ```php require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->getTopicAttributes([ 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } ```