SelectPHP Publish & Subscribe API Reference for Realtime Apps

These docs are for version 3.8.3 of the PHP SDK. To check out the docs for the latest version Click Here.
 

PubNub 4.0 for PHP is our latest and greatest! Please click here for our PubNub 4.0 for PHP docs and SDK.

PubNub 3.x for PHP will encounter End Of Life (EOL) Aug 1st, 2018. All users currently on 3.x should begin migrating to 4.x. The 3.x SDK will continue to work. We will no longer support it and if you run into an issue, we will request that you upgrade to the latest version before solving the issue.

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 publish_key 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 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

 
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.
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.
 

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 SDK:
  1. ParameterTypeRequiredDescription
    channelStringYesSpecifies channel name to publish messages to.
    messageJSONYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
    storeInHistoryBooleanOptionalIf true the messages are stored in history, default true.

Publish a message to a channel:

use Pubnub\Pubnub;
 
// *subscribe to the same channel below
// from another script/terminal or debug console
$publish_result = $pubnub->publish('hello_world','Hello PubNub!');
  
print_r($publish_result);
 
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 function returns the following formatted response:
[1, "Sent", "13769558699541401"]
  1. $pubnub->publish("my_channel", ["key" => ["inner", "value"]]);
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 subscribe_key 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 that it will block until a message is published on the channel(s) it is subscribed to.
  • Returning false will exit the subscribe loop after the first message.
  • Returning true will continue to keep script subscribed after it receives a message and keep blocking.
  • Perhaps a mention that creating a special exit message would be advisable.
The same is applicable to $timeoutHandler callback
 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 SDK:
  1. ParameterTypeRequiredDescription
    callbackFunctionYesThis callback is called on receiving a message from the channel.
    channelArray, String or ListYesSpecifies the channel to subscribe to. It is possible to specify multiplechannels as a list or as an array. See Examples for more info.
    timetokenNumberOptionalSpecifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
    presencebooleanOptionalShould be set to true in presence requests.
    timeoutHandlercallableOptionalTimeout handler will be invoked in the case of cURL timeout. Default value is 310 seconds and can be changed using setSubscribeTimeout() method.
Subscribe to a channel:
$pubnub->subscribe('my_channel', function ($envelope) {
    $msg = $envelope['message'];
    print_r($msg);

    if (strcmp($msg, "exit") == 0) {
        print_r('<<< So long, and thanks for all the messages! >>>');
        return false;
    }
    else {
        print_r('>>> May I have some more message, please? <<<');
        return true;
    }
});
The output below demonstrates the response format to a successful call:
[[], "Time Token"]
  1.  $pubnub->subscribe('my_channel', function ($envelope) {
                 print_r($envelope['message']);
             });
  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('my_channel_1,my_channel_2', function ($envelope) {
                 print_r($envelope['message']);
             });
    $pubnub->subscribe(['my_channel_1','my_channel_2','my_channel_3'], function ($result) {
        print_r($result);
    });
    
  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.
     # subscribe directly to presence channel
     
     $pubnub->subscribe('my_channel-pnpres', function ($envelope) {
                 print_r($envelope['message']);
             });
    
    {
    	"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.*
    // subscribe
    $pubnub->subscribe("ab.*", function ($message) {
        print_r($message);
    });
    
    // presence
    $pubnub->presence("ab.*", function ($message) {
        print_r($message);
    });
  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.
    $pubnub->setState("my_channel", [
        'full' => "Robert Plant"
    ]);
    
    $pubnub->subscribe('my_channel', function ($envelope) {
                 print_r($envelope['message']);
             });
    
    
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.
This functions subscribes to a channel group.
To Subscribe to a Channel Group you can use the following method(s) in the PHP SDK
  1. ParameterTypeRequiredDescription
    channelGroupStringYesThe channelGroup to subscribe to.
    callbackFunctionYesThis callback is called on receiving a message from the channel.
    timeTokenNumberOptionalSpecifies timetoken from which to start returning any available cached messages.
    timeoutHandlerCallableOptionalTimeout handler will be invoked in the case of cURL timeout. Default value is 310 seconds and can be changed using setSubscribeTimeout() method.
Subscribe to a channel group
$channelGroup = "family";
$pubnub->channelGroupSubscribe($channelGroup, $callback);
[[], "Time Token"]
  1. 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->channelGroupSubscribe($channelGroup."-pnpres", $callback);