Azure Service Bus Queue and PHP
This article describes how to put a message in the Azure Service Bus Queue with PHP.
To put a message in the queue you need to create an SAS Token. This SAS Token is needed to authorize the Azure Service Bus.
<?php
// Create SAS token
function CreateSASToken()
{
$namespace = "MyServiceBusNamespace"; // Change to your namespace.
$queuename = "TestMessageQueue"; // Change to your queue name.
$sharedAccessKeyName = "TestAccessKey";
$sharedAccessKey = "Gdfi2lb4fqNdozFGTRUsvfqZSMCMzfh/2oj02CZ0LPE="; // Change!
$expireInSeconds = 1000;
$t0 = time(); // Returns the current time measured in the number of seconds since the Unix Epoch
$expire = $t0 + $expireInSeconds;
$sr = urlencode("https://$namespace.servicebus.windows.net/$queuename");
$tohash = utf8_encode($sr . "\n" . $expire);
$sig = base64_encode(
hash_hmac('sha256', $tohash, $sharedAccessKey, true)
);
$sig = urlencode($sig);
$se = $expire;
$skn = $sharedAccessKeyName;
$token = "SharedAccessSignature sr=$sr&sig=$sig&se=$se&skn=$skn";
return $token;
}
?>
Then you can put a message in the queue like this:
<?php
function PostToQueue($token, $message)
{
$namespace = "MyServiceBusNamespace"; // Change to your namespace.
$queuename = "TestMessageQueue"; // Change to your queue name.
$serviceUrl = "https://$namespace.servicebus.windows.net/$queuename/messages";
$messageLength = strlen($message);
$header = "Content-type: application/atom+xml;\r\n".
"Content-Length: $messageLength\r\n" .
"Authorization: $token\r\n";
$options = array(
'http' => array(
'header' => $header,
'content' => $message,
'method' => 'POST'
)
);
$context = stream_context_create($options);
$result = file_get_contents($serviceUrl, false, $context);
// Do error handling!
return $result;
}
?>