Sending and receiving messages in Amazon SQS with Amazon SDK for PHP Version 3 - Amazon SDK for PHP
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Sending and receiving messages in Amazon SQS with Amazon 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 Service Quotas User 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 Amazon SDK for PHP is available here on GitHub.

Credentials

Before running the example code, configure your Amazon credentials, as described in Credentials. Then import the Amazon SDK for PHP, as described in Basic usage.

Send a message

Imports

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

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\Exception\AwsException; use Aws\Sqs\SqsClient;

Sample Code

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->receiveMessage([ 'AttributeNames' => ['SentTimestamp'], 'MaxNumberOfMessages' => 1, 'MessageAttributeNames' => ['All'], 'QueueUrl' => $queueUrl, // REQUIRED 'WaitTimeSeconds' => 0, ]); if (!empty($result->get('Messages'))) { 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()); }