PHP V4 SDK 4.1.7
Get Code: without composer
Clone repo:
git clone https://github.com/pubnub/php.git ./pubnub-php
Copy
src
folder to your project.Include
autoloader.php
file in your project:require_once('src/autoloader.php');
Download dependency
monolog
from https://github.com/Seldaek/monolog and copy themonolog
folder from thesrc
folder to thesrc
folder of your project.Download dependency
psr/Log
from https://github.com/php-fig/log/tree/master and copy thepsr
folder to thesrc
folder of your project.Download dependency
rmccue
from https://github.com/rmccue/Requests and copy theRequests
folder and the fileRequests.php
from thelibrary
folder to thesrc
folder of your project.
Get Code: with composer
Add pubnub package to your composer.json file:
{ "require": { "pubnub/pubnub": "~4.1.7" } }
Run
composer install --no-dev
from the command line.This will install all the PubNub PHP SDK and all its dependencies in the
vendor
folder of the project.Include
autoload.php
file in your project:require_once('vendor/autoload.php');
Get Code: source
https://github.com/pubnub/php/tree/master
Hello World
Add PubNub to your project using one of the procedures defined under Get Code.
use PubNub\PubNub;
PEM files
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.
Note
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. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
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");
$pnconf->setUuid("myUniqueUUID");
$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);
Copy and paste examples
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:
Init
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.
Important
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.
#####Initializing the client:
Note
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. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
use PubNub\PNConfiguration;
use PubNub\PubNub;
$pnConfiguration = new PNConfiguration();
$pnConfiguration->setSubscribeKey("my_sub_key");
$pnConfiguration->setPublishKey("my_pub_key");
$pnConfiguration->setSecure(false);
$pnConfiguration->setUuid("myUniqueUUID");
$pubnub = new PubNub($pnConfiguration);
Listeners
Adding listeners
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);
Removing listeners
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
// some time later
$pubnub->removeListener($subscribeCallback);
Listener status events
Category | Description |
---|---|
PNConnectedCategory | SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed). |
PNAccessDeniedCategory | Request 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. |
PNMalformedResponseCategory | Request received in response non-JSON data. It can be because of publish WiFi hotspot which require authorization or proxy server message. |
PNBadRequestCategory | Request can't be completed because not all required values has been passed or passed values has unexpected data type. |
PNDecryptionErrorCategory | History 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. |
PNTimeoutCategory | Used API didn't received response from server in time. |
PNUnknownCategory | No specific category was assigned to the request. |
PNUnexpectedDisconnectCategory | The 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. |
PNUnexpectedDisconnectCategory | The 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. |
PNCancelledCategory | Request was cancelled by user. |
PNUnknownCategory | Unknown error happened. |
Time
Call time()
to verify the client connectivity to the origin:
$result = $pubnub->time()
->sync();
print_r($result);
Subscribe
Subscribe (listen on) a channel:
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.
$pubnub->subscribe()
->channels("my_channel")
->execute();
Note
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
Publish a message to a channel:
$result = $pubnub->publish()
->channel("my_channel")
->message(["hello", "there"])
->sync();
print_r($result);
Here Now
Get occupancy of who's here now
on the channel by UUID:
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
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());
}
}
Presence
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
.
Note
Requires you to enable the Presence
add-on for your key. Refer to the How do I enable add-on features for my keys? knowledge base article for details on enabling features.
$pubnub->subscribe()
->channels("my_channel")
->withPresence()
->execute();
Note
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.
History
Retrieve published messages from archival storage:
Note
Requires that the Storage and Playback
add-on is enabled for your key. How do I enable add-on features for my keys? - see https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
$result = $pubnub->history()
->channel("history_channel")
->count(100)
->sync();
Unsubscribe
Stop subscribing (listening) to 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();