PHPPHP V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


 

These docs are for PubNub 4.x for PHP which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.x for PHP.

If you have questions about the PubNub for PHP SDK, please contact us at support@pubnub.com.

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 is 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. Message data should not contain special PHP V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K 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.5KB) 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 please check: https://support.pubnub.com/support/discussions/topics/14000006322

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 cannot 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 (i.e. not concurrently).
  • Check that the return code is success (e.g. [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 e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not 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.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the PHP V4 SDK:
  1. ParameterTypeRequiredDefaultDescription
    channelStringYesDestination of message.
    messageString|ArrayYesThe payload.
    shouldStoreBooleanOptionalaccount default

    Store in history.

    metaArrayOptionalnullMeta data object which can be used with the filtering ability.
    usePostBooleanOptionalfalseUse POST to publish.

Publish a message to a channel:

$result = $pubnub->publish()
    ->channel("my_channel")
    ->message(["hello", "there"])
    ->usePost(true)
    ->sync();
 
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.
The publish() operation returns a PNPublishResult which contains the following fields:
Property NameTypeDescription
getTimetoken()IntegerAn integer representation of the time token when the message was published.
  1. $result = $pubnub->publish()
                  ->channel("my_channel")
                  ->message(["hello", "there"])
                  ->meta(["name" => "Alex"])
                  ->sync();
  2. 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) {
        handleExpection($error);
    }
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. 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() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the PHP V4 SDK:
  1. ParameterTypeRequiredDefaultDescription
    channelStringYesDestination of message.
    messageString|ArrayYesThe payload.
    metaArrayOptionalnullMeta data object which can be used with the filtering ability.
    usePostBooleanOptionalfalseUse POST to publish.

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();
}
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. To subscribe to a channel 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.

Perhaps a mention that creating a special exit message would be advisable.

 Unsubscribing from all the channel(s) 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 the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the PHP V4 SDK:
  1. ParameterTypeRequiredDescription
    channelsString|ArrayOptionalSubscribe to channels, Either channel or channel_group is required.
    channelGroupsString|ArrayOptionalSubscribe to channel_groups, Either channel or channel_group is required.
    withTimetokenIntegerOptionalPass a timetoken.
    withPresenceBooleanOptionalAlso subscribe to related presence information.
Subscribe to a channel:
$pubnub->subscribe()
    ->channels("my_channel")
    ->execute();
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.
PNStatus:
Property NameTypeDescription
getCategory() PNStatusCategory Details of StatusCategory are here.
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.
Operation OperationTypeOperation type of the request.
PNMessageResult:
MethodTypeDescription
getMessage()ObjectThe message sent on channel.
getSubscription()StringThe channel on which the message was received.
getTimetoken()IntegerTimetoken for the message.
PNPresenceEventResult:
MethodTypeDescription
getStatusCode()IntegerEvents like join, leave, timeout, state-change.
getUuid()Stringuuid for event.
getTimestamp()Integertimestamp for event.
getOccupancy()IntegerCurrent occupancy.
getSubscription()StringMessage has been received on channel.
getTimetoken()Integertimetoken of the message.
  1. use Monolog\Handler\ErrorLogHandler;
    use PubNub\PNConfiguration;
    use PubNub\PubNub;
    
    $pnconf = new PNConfiguration();
    
    $pnconf->setPublishKey("demo");
    $pnconf->setSubscribeKey("demo");
    
    $pubnub = new PubNub($pnconf);
    
    $pubnub->getLogger()->pushHandler(new ErrorLogHandler());
    
    $pubnub->subscribe()->channels("my_channel")->execute();
  2. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    $pubnub->subscribe()
        ->channels(["my_channel1", "my_channel2"])
        ->execute();
  3. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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.
    $pubnub->subscribe()
        ->channels("my_channel")
        ->withPresence()
        ->execute();
    {
    	"action": "join",
    	"timestamp": 1345546797,
    	"uuid": "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
    	"occupancy": 2
    }
    
    {
        "action" : "leave",
        "timestamp" : 1345549797,
        "uuid" : "175c2c67-b2a9-470d-8f4b-1db94f90e39e",
        "occupancy" : 1
    }
    {
    	"action": "timeout",
    	"timestamp": 1345549797,
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"occupancy": 0
    }
    
    {
    	"action": "state-change",
    	"uuid": "76c2c571-9a2b-d074-b4f8-e93e09f49bd",
    	"timestamp": 1345549797,
    	"data": {
    		"isTyping": true
    	}
    }
    
    {
    	"action":"interval",
    	"timestamp":1474396578,
    	"occupancy":2
    }
    

    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:

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "joined" : ["uuid2", "uuid3"],
        "timedout" : ["uuid1"]
    }
    

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), 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.

    {
        "action" : "interval",
        "occupancy" : <# users in channel>,
        "timestamp" : <unix timestamp>,
        "here_now_refresh" : true
    }
    
  4. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., 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 (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    $pubnub->subscribe()
        ->channels("foo.*")
        ->execute();
  5. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    use PubNub\PubNub;
    use PubNub\PNConfiguration;
    use PubNub\Callbacks\SubscribeCallback;
    
    $pnconf = new PNConfiguration();
    
    $pnconf->setPublishKey("demo");
    $pnconf->setSubscribeKey("demo");
    
    $pubnub = new PubNub($pnconf);
    
    class MySubscribeCallback extends SubscribeCallback {
        function status($pubnub, $status) {
            if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
                $result = $pubnub->setState()
                              ->channels("awesomeChannel")
                              ->channelGroups("awesomeChannelGroup")
                              ->state([
                                  "fieldA" => "awesome",
                                  "fieldB" => 10
                              ])
                              ->sync();
                print_r($result);
            }
        }
    
        function message($pubnub, $message) {
        }
    
        function presence($pubnub, $presence) {
        }
    }
    
    $subscribeCallback = new MySubscribeCallback();
    
    $pubnub->addListener($subscribeCallback);
    
    $pubnub->subscribe()
        ->channels("my_channel")
        ->execute();
  6. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    $pubnub->subscribe()
        ->channelGroups(["cg1", "cg2"])
        ->execute();
  7. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    $pubnub->subscribe()
        ->channelGroups("awesome_channel_group")
        ->withPresence()
        ->execute();
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.
To Unsubscribe from a channel you can use the following method(s) in the PHP V4 SDK
  1. ParameterTypeRequiredDefaultsDescription
    getChannelsStringOptionalfalseThe channels to get the here now details.
    getChannelGroupsStringOptionalfalseThe channel groups to get the here now details.
    setChannelsArrayOptionalfalseUnsubscribe to channels, Either channel or channelGroup is required.
    setChannelGroupsArrayOptionalfalseUnsubscribe to channel groups, Either channel or channelGroup is required.
Unsubscribe from a channel:
use PubNub\Callbacks\SubscribeCallback;
use PubNub\Enums\PNStatusCategory;
use PubNub\PNConfiguration;
use PubNub\PubNub;
use PubNub\Exceptions\PubNubUnsubscribeException;

$pnconfig = new PNConfiguration();

$pnconfig->setPublishKey("demo");
$pnconfig->setSubscribeKey("demo");

$pubnub = new PubNub($pnconfig);

class MySubscribeCallback extends SubscribeCallback {
    function status($pubnub, $status) {
        if ($this->checkUnsubscribeCondition()) {
            throw (new PubNubUnsubscribeException())->setChannels("awesomeChannel");
        }
    }

    function message($pubnub, $message) {
    }

    function presence($pubnub, $presence) {
    }

    function checkUnsubscribeCondition() {
        // return true or false
    }
}

$subscribeCallback = new MySubscribeCallback();

$pubnub->addListener($subscribeCallback);

$pubnub->subscribe()
    ->channels("awesomeChannel")
    ->execute();
The output below demonstrates the response to a successful call:
{
	"action" : "leave"
}
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    use PubNub\Callbacks\SubscribeCallback;
    use PubNub\Exceptions\PubNubUnsubscribeException;
    
    class MySubscribeCallback extends SubscribeCallback {
        function status($pubnub, $status) {
            throw new PubNubUnsubscribeException();
        }
    
        function message($pubnub, $message) {
        }
    
        function presence($pubnub, $presence) {
        }
    }
    {
    	"action" : "leave"
    }
    
  2. use PubNub\Callbacks\SubscribeCallback;
    use PubNub\Exceptions\PubNubUnsubscribeException;
    
    class MySubscribeCallback extends SubscribeCallback {
        function status($pubnub, $status) {
            throw (new PubNubUnsubscribeException())->setChannelGroups(["my_channel"]);
        }
    
        function message($pubnub, $message) {
        }
    
        function presence($pubnub, $presence) {
        }
    }
    {
    	"action": "leave"
    }
    

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

use PubNub\PubNub;
use PubNub\Enums\PNStatusCategory;
use PubNub\Callbacks\SubscribeCallback;
use PubNub\PNConfiguration;

class MySubscribeCallback extends SubscribeCallback {
    function status($pubnub, $status) {
        if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
        // This event happens when radio / connectivity is lost 
        } else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory){
        // Connect event. You can do stuff like publish, and know you'll get it // Or just use the connected event to confirm you are subscribed for // UI / internal notifications, etc 
        } else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory){
        // Handle message decryption error. Probably client configured to // encrypt messages and on live data feed it received plain text. 
        }
    }

    function message($pubnub, $message){
    // Handle new message stored in message.message 
    }
    function presence($pubnub, $presence){
    // handle incoming presence data 
    }
}

$pnconf = new PNConfiguration();
$pubnub = new PubNub($pnconf);

$pnconf->setSubscribeKey("my_sub_key");
$pnconf->setPublishKey("my_pub_key");

$subscribeCallback = new MySubscribeCallback();

$pubnub->addListener($subscribeCallback);

// Subscribe to a channel, this is not async.
$pubnub->subscribe()
->channels("hello_world")
->execute();

// Use the publish command separately from the Subscribe code shown above.
// Subscribe is not async and will block the execution until complete.
$result = $pubnub->publish()
->channel("hello_world")
->message("Hello PubNub")
->sync();

print_r($result);
$subscribeCallback = new MySubscribeCallback();

$pubnub->addListener($subscribeCallback);

// some time later
$pubnub->removeListener($subscribeCallback);
CategoriesDescription
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategoryRequest failed because of access error (active PAM). status.errorData.channels or status.errorData.channelGroups contain list of channels and/or groups to which user with specified auth key doesn't have access.
PNMalformedResponseCategoryRequest received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message.
PNBadRequestCategoryRequest can't be completed because not all required values has been passed or passed values has unexpected data type.
PNDecryptionErrorCategoryHistory API may return this status category in case if some messages can't be decrypted. Unencrypted message will be returned in status.associatedObject where associatedObject is PNMessageData which contain channel and message properties.
PNTimeoutCategoryUsed API didn't received response from server in time.
PNUnknownCategoryNo specific category was assigned to the request.
PNUnexpectedDisconnectCategoryThe SDK is not able to reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNUnexpectedDisconnectCategoryThe SDK is not able to reach the PubNub Data Stream Network because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNCancelledCategoryRequest was cancelled by user.
PNUnknownCategory Unknown error happened.

Go to Presence