Publish/Subscribe API for PubNub PHP SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
The publish()
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data
should not contain special PHP classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]
For further details, check Calculating Message Payload Size Before Publish.
Message Publish Rate
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably
There are some best practices to ensure messages are delivered when publishing to a channel:
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 msgs per second to any one channel.
Method(s)
To Publish a message
you can use the following method(s) in the PHP SDK:
$pubnub->publish()
->channel(string)
->message(string|array)
->shouldStore(boolean)
->ttl($ttl)
->meta(array)
->usePost(boolean)
->sync();
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | n/a | Destination of message . |
message | String|Array | Yes | n/a | The payload. |
shouldStore | Boolean | Optional | account default | Store in history. |
ttl | Number | Optional | n/a | Set a per message time to live in Message Persistence.
|
meta | Array | Optional | null | Meta data object which can be used with the filtering ability. |
usePost | Boolean | Optional | false | Use POST to publish . |
Basic Usage
Publish a message to a channel
$result = $pubnub->publish()
->channel("my_channel")
->message(["hello", "there"])
->shouldStore(true)
->ttl(15)
->usePost(true)
->sync();
Subscribe to the channel
Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
Response
The publish()
operation returns a PNPublishResult
which contains the following fields:
Property Name | Type | Description |
---|---|---|
getTimetoken() | Integer | An integer representation of the timetoken when the message was published. |
Other Examples
Publish with metadata
$result = $pubnub->publish()
->channel("my_channel")
->message(["hello", "there"])
->meta(["name" => "Alex"])
->sync();
Publish Array
use PubNub\Exceptions\PubNubException;
try {
$result = $pubnub->publish()
->channel("my_channel")
->message(["hello", "there"])
->meta(["name" => "Alex", "online" => true])
->sync();
print_r($result->getTimetoken());
} catch (PubNubException $error) {
handleException($error);
}
Fire
The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire()
isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the PHP SDK:
$pubnub->fire()
->channel(string)
->message(string|array)
->meta(array)
->usePost(boolean)
->sync();
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channel | String | Yes | Destination of message . | |
message | String|Array | Yes | The payload. | |
meta | Array | Optional | null | Meta data object which can be used with the filtering ability. |
usePost | Boolean | Optional | false | Use POST to publish . |
Basic Usage
Fire a message to a channel
use PubNub\Exceptions\PubNubException;
try {
$result = $pubnub->fire()
->channel("my_channel")
->message(["hello","there"])
->usePost(true)
->sync();
echo "Publish worked! Timetoken: " . $result->getTimetoken();
}
catch(\PubNub\Exceptions\PubNubServerException $e) {
echo "Error happened while publishing: " . $e->getMessage();
}