Publish/Subscribe API for PHP SDK

PubNub's publish-processing latency, the time to accept and acknowledge a publish request, is about 0.5 ms within the same region. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

Publish​

publish() sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.

  • You must initialize PubNub with the publishKey.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)​

To Publish a message you can use the following method(s) in the PHP SDK:

1$pubnub->publish()
2 ->channel(string)
3 ->message(string|array)
4 ->shouldStore(boolean)
5 ->ttl($ttl)
6 ->meta(array)
7 ->usePost(boolean)
8 ->customMessageType(string)
9 ->sync();
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Destination of message (channel ID).
message *
Type: String|Array
Default:
n/a
The payload.
shouldStore
Type: Boolean
Default:
account default
Store in history.
ttl
Type: Number
Default:
n/a
Set a per message time to live in Message Persistence.
  1. If shouldStore = true, and ttl = 0, the message is stored with no expiry time.
  2. If shouldStore = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal.
  3. If shouldStore = false, the ttl parameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
meta
Type: Array
Default:
null
Meta data object which can be used with the filtering ability.
usePost
Type: Boolean
Default:
false
Use POST to publish.
customMessageType
Type: string
Default:
n/a
A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Sample code​

Publish a message to a channel​

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

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 NameTypeDescription
getTimetoken()IntegerAn integer representation of the timetoken when the message was published.

Other examples​

Publish with metadata​

1

Publish array​

1

Fire​

The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.

Method(s)​

To Fire a message you can use the following method(s) in the PHP SDK:

1$pubnub->fire()
2 ->channel(string)
3 ->message(string|array)
4 ->meta(array)
5 ->usePost(boolean)
6 ->sync();
* required
ParameterDescription
channel *
Type: String
Default:
n/a
Destination of message (channel ID).
message *
Type: String|Array
Default:
n/a
The payload.
meta
Type: Array
Default:
null
Meta data object which can be used with the filtering ability.
usePost
Type: Boolean
Default:
false
Use POST to publish.

Sample code​

Fire a message to a channel​

1

Signal​

The signal() function sends a signal to all subscribers of a channel.

  • You must initialize PubNub with the publishKey.
  • The message payload size (without the URI or headers) is limited to 64 bytes. If you require a larger payload size, contact support.

Method(s)​

To Send a signal you can use the following method(s) in the PHP SDK:

1$pubnub->signal()
2 ->channel(string)
3 ->message(string|array)
4 ->sync();
* required
ParameterDescription
channel *
Type: String
The channel ID to send the signal to.
message *
Type: String|Array
The signal message payload.

Sample code​

Send a signal to a channel​

1

Response​

The signal() operation returns a PNSignalResult which contains the following fields:

Property NameTypeDescription
getTimetoken()intAn int representation of the timetoken when the signal was sent.

Subscribe​

Receive messages​

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

No built-in event throttling

The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.

To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.

Description​

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel ID. To subscribe to a channel ID the client must send the appropriate subscribeKey at initialization.

By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.

Subscribe call is blocking and it will block until:
  • A message is published on the channel(s) it is subscribed to (message callback).
  • A presence event is received on the channel(s) it is subscribed to (presence callabck).
  • A status event is triggered by SDK (status callback).

Inside of all of the callbacks above you can throw PubNubUnsubscribeException to exit the subscribe loop.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)​

To Subscribe to a channel you can use the following method(s) in the PHP SDK:

1$pubnub->subscribe()
2 ->channels(string|array)
3 ->channelGroups(string|array)
4 ->withTimetoken(integer)
5 ->withPresence(boolean)
6 ->execute();
* required
ParameterDescription
channels
Type: String or Array
Subscribe to channels, Either channel ID or channel_group is required.
channelGroups
Type: String or Array
Subscribe to channel_groups, Either channel ID or channel_group is required.
withTimetoken
Type: Integer
Pass a timetoken.
withPresence
Type: Boolean
Also subscribe to related presence information.

For information on how to receive presence events and what those events are, refer to Presence Events.

Sample code​

Subscribe to a channel:

1

Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Response​

PNStatus:

Property NameTypeDescription
getCategory()PNStatusCategorySee the PHP SDK status categories.
isError()boolThis is true if an error occurred in the execution of the operation.
getException()PubNubExceptionError data of the exception (if Error is true).
getStatusCode()intStatus code of the execution.
OperationOperationTypeOperation type of the request.

PNMessageResult:

MethodDescription
getMessage()
Type: Object
The message sent on the channel ID.
getSubscription()
Type: String
The channel ID on which the message was received.
getTimetoken()
Type: Integer
Timetoken for the message.

PNPresenceEventResult:

MethodDescription
getStatusCode()
Type: Integer
Events like join, leave, timeout, state-change.
getUuid()
Type: String
uuid for event.
getTimestamp()
Type: Integer
timestamp for event.
getOccupancy()
Type: Integer
Current occupancy.
getSubscription()
Type: String
Message has been received on the channel ID.
getTimetoken()
Type: Integer
timetoken of the message.

Add DataSync listener​

DataSync objects publish create, update, and delete events on ordinary channels. The PHP SDK ships no dedicated DataSync SDK entity, so subscribe to the object's data channel with subscribe() like any other channel and receive the events in the dataSyncEvent method of your SubscribeCallback subclass, attached with addListener.

Events fan out beyond the object's own channel

An update or delete on a user, channel, or entity is also delivered on the channel of every object connected to it by a relationship or membership. Refer to Where each event is delivered for the full delivery table.

addListener attaches at the PubNub client scope, there is no per-subscription listener in this SDK. Every DataSync event your client receives on any subscribed channel arrives on the same dataSyncEvent method, so branch on getType() and getChannel() inside it. The method is not abstract, so an existing listener that doesn't override it keeps working and ignores DataSync events. Like any other subscribe call, execute() blocks, so run it in a long-running CLI process rather than inside a web request.

Enable DataSync events on the class

To receive DataSync events, enable event publishing for the object's class in the Admin Portal. Refer to DataSync events for details.

Projections filter what a token receives

A token scoped to a projection only receives events published to that projection's channel, and the event's getEntity(), getRelationship(), or getMembership() payload only carries the fields the class tags with that projection. Refer to Projection channels.

PNDataSyncEventResult carries:

MethodDescription
getEvent()
Type: String
create, update, or delete.
getType()
Type: String
The object kind: user, channel, entity, membership, or relationship.
getClassName()
Type: String
The specific class within the kind.
getClassLevel()
Type: String
Global or SubKey.
getClassVersion()
Type: Integer
The class schema version the event was published under.
getEntity()
Type: PNDataSyncEntity
Populated on create and update for a user, channel, or entity. Subject to projection filtering.
getRelationship()
Type: PNDataSyncRelationship
Populated on create and update for a relationship or a membership. Subject to projection filtering.
getMembership()
Type: PNDataSyncMembership
Populated on create and update for a membership. Subject to projection filtering.
getId()
Type: String
The id of the changed object.
getDeletedAt()
Type: String
Populated on delete. ISO 8601 deletion timestamp.
getSource()
Type: String
Always data-sync, events from other sources never reach a listener.
getVersion()
Type: String
Schema version of the event envelope.
getChannel()
Type: String
The channel the event was received on.
getSubscription()
Type: String
The subscription match that delivered the event, such as a wildcard or channel group.
getTimetoken()
Type: String
Publish timetoken of the event.

On a delete event, getEntity(), getRelationship(), and getMembership() all return null, only getId() and getDeletedAt() are populated. getId(), getETag(), getCreatedAt(), getUpdatedAt(), and getExpiresAt() on the state records are never filtered by a projection, only getPayload() and getStatus() are. For a membership, getRelationship() reports the channel as entity A and the user as entity B, and getMembership() returns the same record under its getChannelId() and getUserId() names.

1

For the fetch methods, refer to DataSync API. For the concurrency pattern, refer to the ETags concept documentation.

Other examples​

Basic subscribe with logging​

1

Subscribing to multiple channels​

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

1

Subscribing to a Presence channel​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.

1

Sample Responses​

Join event​
1{
2 "action": "join",
3 "timestamp": 1345546797,
4 "uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
5 "occupancy": 2
6}
Leave event​
1{
2 "action" : "leave",
3 "timestamp" : 1345549797,
4 "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
5 "occupancy" : 1
6}
Timeout event​
1{
2 "action": "timeout",
3 "timestamp": 1345549797,
4 "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
5 "occupancy": 0
6}
Custom Presence event (state change)​
1{
2 "action": "state-change",
3 "uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
4 "timestamp": 1345549797,
5 "data": {
6 "isTyping": true
7 }
8}
Interval event​
1{
2 "action":"interval",
3 "timestamp":1474396578,
4 "occupancy":2
5}

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "joined" : ["uuid2", "uuid3"],
6 "timedout" : ["uuid1"]
7}

If the full interval message is greater than 30 KB (since the max publish payload is ∼32 KiB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

1{
2 "action" : "interval",
3 "occupancy" : <# users in channel>,
4 "timestamp" : <unix timestamp>,
5 "here_now_refresh" : true
6}

Wildcard subscribe to channels​

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

1

Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

Subscribing with state​

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

1

Subscribe to a channel group​

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Subscribe to the Presence channel of a channel group​

Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Unsubscribe​

To unsubscribe you should throw PubNubUnsubscribeException somewhere inside status/message/presence callbacks of your subscribe listeners. You should specify channel and / or channel group names to unsubscribe and keep a subscription loop running if some other channels left. Otherwise the exception will unsubscribe from all channels and channel-groups.

Method(s)​

To Unsubscribe from a channel you can use the following method(s) in the PHP SDK:

1(new PubNubUnsubscribeException())
2 ->setChannels(array)
3 ->setChannelGroups(array);
* required
ParameterDescription
getChannels
Type: String
Default:
false
The channels to get the here now details.
getChannelGroups
Type: String
Default:
false
The channel groups to get the here now details.
setChannels
Type: Array
Default:
false
Unsubscribe to channels, Either channel ID or channelGroup is required.
setChannelGroups
Type: Array
Default:
false
Unsubscribe to channel groups, Either channel ID or channelGroup is required.

Sample code​

Unsubscribe from a channel:

1

Rest response from server​

The output below demonstrates the response to a successful call:

1{
2 "action" : "leave"
3}

Other examples​

Unsubscribing from multiple channels​

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Example response​
1{
2 "action" : "leave"
3}

Unsubscribe from a channel group​

1

Example response​
1{
2 "action": "leave"
3}

Was this page useful?

Last updated on