AWS SDK for PHP
Developer Guide

Sending and Receiving Messages in Amazon SQS with AWS SDK for PHP Version 3

To learn about Amazon SQS messages, see Sending a Message to an SQS Queue and Receiving and Deleting a Message from an SQS Queue in the Amazon SQS Developer Guide.

The following examples show how to:

  • Deliver a message to a specified queue using SendMessage.

  • Retrieve one or more messages (up to 10) from a specified queue using ReceiveMessage.

  • Delete a message from a queue using DeleteMessage.

All the example code for the AWS SDK for PHP Version 3 is available here on GitHub.

Credentials

Before running the example code, configure your AWS credentials, as described in Credentials for the AWS SDK for PHP Version 3. Then import the AWS SDK for PHP, as described in Basic Usage Patterns of the AWS SDK for PHP Version 3.

Send a Message

Imports

require 'vendor/autoload.php'; use Aws\Sqs\SqsClient; use Aws\Exception\AwsException;

Sample Code

$client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); $params = [ 'DelaySeconds' => 10, 'MessageAttributes' => [ "Title" => [ 'DataType' => "String", 'StringValue' => "The Hitchhiker's Guide to the Galaxy" ], "Author" => [ 'DataType' => "String", 'StringValue' => "Douglas Adams." ], "WeeksOn" => [ 'DataType' => "Number", 'StringValue' => "6" ] ], 'MessageBody' => "Information about current NY Times fiction bestseller for week of 12/11/2016.", 'QueueUrl' => 'QUEUE_URL' ]; try { $result = $client->sendMessage($params); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

Receive and Delete Messages

Imports

require 'vendor/autoload.php'; use Aws\Sqs\SqsClient; use Aws\Exception\AwsException;

Sample Code

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->receiveMessage(array( 'AttributeNames' => ['SentTimestamp'], 'MaxNumberOfMessages' => 1, 'MessageAttributeNames' => ['All'], 'QueueUrl' => $queueUrl, // REQUIRED 'WaitTimeSeconds' => 0, )); if (count($result->get('Messages')) > 0) { var_dump($result->get('Messages')[0]); $result = $client->deleteMessage([ 'QueueUrl' => $queueUrl, // REQUIRED 'ReceiptHandle' => $result->get('Messages')[0]['ReceiptHandle'] // REQUIRED ]); } else { echo "No messages in queue. \n"; } } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }