PHPPubNub PHP V4 SDK 4.0.0

 

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.

  1. You need only src folder. To get it clone repo:
            git clone https://github.com/pubnub/php.git ./pubnub-php
            
  2. Copy src folder to your project and include autoloader.php file.
  3. Require autoloader.php:
            require_once('src/autoloader.php');
            
  1. Add pubnub package to your composer.json file:
            {
                "require": {
                    "pubnub/pubnub": "~4.0.0"
                }
            }
            
  2. Run composer install from command line.
 In case of an error, please copy the Requests folder and the file Requests.php into the src folder from rmccue>requests>library.



Add PubNub to your project using one of the procedures defined under How to Get It.
use PubNub\PubNub;
 
PEM files can be downloaded for the domains pubsub.pubnub.com, pubsub.pubnub.net and ps.pndsn.com using the commands:
                echo Q | openssl s_client -connect pubsub.pubnub.com:443 -servername pubsub.pubnub.com -showcerts
                echo Q | openssl s_client -connect pubsub.pubnub.net:443 -servername pubsub.pubnub.net -showcerts
                echo Q | openssl s_client -connect ps.pndsn.com:443 -servername ps.pndsn.com -showcerts
                
You need to set the verify_peer to true to use the PEM files.
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");

$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);
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform PAM administrative operations from this PHP V4 instance.

For security reasons you should only include the secret-key on a highly secured server. The secret-key is only required for granting rights using our Access Manager.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

use PubNub\PNConfiguration;
use PubNub\PubNub;

$pnConfiguration = new PNConfiguration();

$pnConfiguration->setSubscribeKey("my_sub_key");
$pnConfiguration->setPublishKey("my_pub_key");
$pnConfiguration->setSecure(false);

$pubnub = new PubNub($pnConfiguration);
use PubNub\Enums\PNStatusCategory;
use PubNub\Callbacks\SubscribeCallback;

class MySubscribeCallback extends SubscribeCallback {
    function status($pubnub, $status) {
        // The status object returned is always related to subscribe but could contain
        // information about subscribe, heartbeat, or errors
        // use the operationType to switch on different options
        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.
        } else if ($status->getCategory() === PNStatusCategory::PNAccessDeniedCategory) {
            // This means that PAM does allow this client to subscribe to this
            // channel and channel group configuration. This is another explicit error
        }
    }

    function message($pubnub, $message) {
        // Handle new message stored in message.message
    }

    function presence($pubnub, $presence) {
        // handle incoming presence data
    }
}

$subscribeCallback = new MySubscribeCallback();
$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.
PNUnknownCategory Unknown error happened.
Call time() to verify the client connectivity to the origin:
$result = $pubnub->time()
              ->sync();

print_r($result);

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.

$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.
Publish a message to a channel:
$result = $pubnub->publish()
              ->channel("my_channel")
              ->message(["hello", "there"])
              ->sync();

print_r($result);
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
try {
    $result = $pubnub->hereNow()
                  ->channels(["my_channel", "demo"])
                  ->includeUuids(true)
                  ->sync();
} catch (PubNubException $err) {
    print_r($err);
}

foreach ($result->getChannels() as $channelData) {
    print("---\n");
    printf("channel: %s\n", $channelData->getChannelName());
    printf("occupancy: %s\n", $channelData->getOccupancy());

    foreach ($channelData->getOccupants() as $occupant) {
        printf("uuid: %s, state: %s\n", $occupant->getUuid(), $occupant->getState());
    }
}
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
$pubnub->subscribe()
    ->channels("my_channel")
    ->withPresence()
    ->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.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
$result = $pubnub->history()
              ->channel("history_channel")
              ->count(100)
              ->sync();
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();