PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

pHP

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support

Configuration API for PubNub PHP SDK

PHP V4 complete API reference for building real-time applications on PubNub, including basic usage and sample code.

Configuration

Description

PNConfiguration instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.

Method(s)

To create configuration instance you can use the following function in the PHP V4 SDK:

new PNConfiguration();
ParameterTypeRequiredDefaultsDescription
subscribeKeyStringYessubscribeKey from Admin Portal
publishKeyStringOptionalnullpublishKey from Admin Portal (only required if publishing)
secretKeyStringOptionalnullsecretKey (only required for modifying/revealing access permissions)
cipherKeyStringOptionalnullIf cipherKey is passed, all communications to/from PubNub will be encrypted.
uuidStringYesUUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
authKeyStringOptionalnullIf Access Manager is utilized, client will use this authKey in all restricted requests.
sslBooleanOptionaltrueUse ssl
connectTimeoutIntegerOptional10How long to wait before giving up connection to client.The value is in seconds.
subscribeTimeoutIntegerOptional310How long to keep the subscribe loop running before disconnect.The value is in seconds.
nonSubscribeRequestTimeoutIntegerOptional10On non subscribe operations, how long to wait for server response.The value is in seconds.
filterExpressionStringOptionalnullFeature to subscribe with a custom filter expression.
originStringOptionalps.pndsn.comCustom origin if needed.
useRandomIVBooleanOptionaltrueWhen true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<4.3.0) with existing applications. Never disable random IV on new applications.

Basic Usage

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. If you don't set the UUID, you won't be able to connect to PubNub.

use PubNub\PNConfiguration;

$pnConfiguration = new PNConfiguration();

// subscribeKey from Admin Portal
$pnConfiguration->setSubscribeKey("my_sub_key"); // required

// publishKey from Admin Portal (only required if publishing)
$pnConfiguration->setPublishKey("my_pub_key");

// secretKey (only required for modifying/revealing access permissions)
$pnConfiguration->setSecretKey("my_secretKey");

// if cipherKey is passed, all communicatons to/from pubnub will be encrypted
$pnConfiguration->setCipherKey("my_cipherKey");

// UUID to be used as a device identifier, won't connect if not set
$pnConfiguration->setUuid("my_custom_uuid");

// if Access Manager is utilized, client will use this authKey in all restricted
// requests
$pnConfiguration->setAuthKey("my_auth_key");

// use SSL (enabled by default)
$pnConfiguration->setSecure(true);

// how long to wait before giving up connection to client
$pnConfiguration->setConnectTimeout(10);

// how long to keep the subscribe loop running before disconnect
$pnConfiguration->setSubscribeTimeout(310);

// on non subscribe operations, how long to wait for server response
$pnConfiguration->setNonSubscribeRequestTimeout(300);

// PSV2 feature to subscribe with a custom filter expression
$pnConfiguration->setFilterExpression("such = wow");

Rest Response from Server

Configured and ready to use client configuration instance.

Initialization

Add PubNub to your project using one of the procedures defined under How to Get It Use PHP SDK in your code.

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.

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.

Method(s)

To Initialize PubNub you can use the following method(s) in the PHP V4 SDK:

  1. new PubNub($pnconf);
    
    ParameterTypeRequiredDescription
    pnConfigurationPNConfigurationYesGoto Configuration for more details.

Basic Usage

Initialize the PubNub client API:

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. If you don't set the UUID, you won't be able to connect to PubNub.

use PubNub\PNConfiguration;
use PubNub\PubNub;

$pnconf = new PNConfiguration();

$pnconf->setSubscribeKey("my-key");
$pnconf->setPublishKey("my-key");
$pnconf->setSecure(false);
$pnconf->setUuid("myUniqueUUID");
$pubnub = new PubNub($pnconf);

Returns

It returns the PubNub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.

Other Examples

  1. Initialize a non-secure 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. If you don't set the UUID, you won't be able to connect to PubNub.

    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);
    
  2. Initialization for a Read-Only client:

    In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when 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. If you don't set the UUID, you won't be able to connect to PubNub.

    use PubNub\PNConfiguration;
    use PubNub\PubNub;
    
    $pnConfiguration = new PNConfiguration();
    
    $pnConfiguration->setSubscribeKey("my_sub_key");
    
    $pubnub = new PubNub($pnConfiguration);
    
  3. Use a custom UUID

    Set a custom UUID to identify your users.

    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. If you don't set the UUID, you won't be able to connect to PubNub.

    use PubNub\PNConfiguration;
    use PubNub\PubNub;
    
    $pnconf = new PNConfiguration();
    
    $pnconf->setSubscribeKey("mySubscribeKey");
    $pnconf->setPublishKey("myPublishKey");
    $pnconf->setUuid("myUniqueUUID");
    
    $pubnub = new PubNub($pnconf);
    
  4. Initializing with Access Manager: Requires Access Manager add-onRequires that the Access Manager add-on is enabled for your key. See this page on enabling add-on features on your keys:
    https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

    Note

    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secret key be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure server-side platforms.

    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.

    For applications that will administer PAM permissions, the API is initialized with the secretKey as in the following example:

    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. If you don't set the UUID, you won't be able to connect to PubNub.

    use PubNub\PNConfiguration;
    use PubNub\PubNub;
    
    $pnConfiguration = new PNConfiguration();
    
    $pnConfiguration->setSubscribeKey("my_sub_key");
    $pnConfiguration->setPublishKey("my_pub_key");
    $pnConfiguration->setSecretKey("my_secret_key");
    $pnConfiguration->setUuid("myUniqueUUID");
    $pubnub = new PubNub($pnConfiguration);
    

    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secretKey to sign all PAM messages to the PubNub Network.

Event Listeners

Description

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

Listeners should be added before calling the method.

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

CategoryDescription
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.
PNUnknownCategoryUnknown error happened.

UUID

Description

These functions are used to set/get a user ID on the fly.

Property(s)

To set/get UUID you can use the following property(s) in PHP V4 SDK:

  1. $pnconf->setUuid(string);
    
    ParameterTypeRequiredDefaultDescription
    uuidStringYesUUID to be used as a device identifier. If you don't set the UUID, you won't be able to connect to PubNub.
  2. $pnconf->getUuid();
    

    This method doesn't take any arguments.

Basic Usage

Set UUID:

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. If you don't set the UUID, you won't be able to connect to PubNub.

$pnconf = new PNConfiguration();
$pnconf->setUuid("myUniqueUUID");

Get UUID:

$pubnub->getConfiguration()
    ->getUuid();

Authentication Key

Description

Setter and getter for users auth key.

  1. $pnconf->setAuthKey(string);
    
    ParameterTypeRequiredDescription
    AuthKeyStringYesIf Access Manager is utilized, client will use this authkey in all restricted requests.
  2. $pnconf->getAuthKey();
    

    This method doesn't take any argument.

Basic Usage

Set Auth Key

$pubnub->getConfiguration()
    ->setAuthKey("my_newauthkey");

Get Auth Key

$pubnub->getConfiguration()
    ->getAuthKey();

Returns

None.

Filter Expression

Requires Stream Controller add-on Requires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

Description

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set/get filters you can use the following methods. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

  1. setFilterExpression( string filterExpression )
    
    ParameterTypeRequiredDescription
    filterExpressionstringYesLogical expression to be evaluated on PubNub servers
  2. getFilterExpression
    

    This method doesn't take any arguments.

Basic Usage

Set Filter Expression

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. If you don't set the UUID, you won't be able to connect to PubNub.

use PubNub\PNConfiguration;
use PubNub\PubNub;

$pnconf = new PNConfiguration();

$pnconf->setSubscribeKey("my_sub_key");
$pnconf->setFilterExpression("uuid == 'my_uuid'");

$pubnub = new PubNub($pnconf);

Get Filter Expression

$pubnub->getFilterConfiguration();
← Getting StartedPublish & Subscribe →
  • Configuration
    • Description
    • Method(s)
    • Basic Usage
    • Rest Response from Server
  • Initialization
    • Description
    • Method(s)
    • Basic Usage
    • Returns
    • Other Examples
  • Event Listeners
    • Description
  • UUID
    • Description
    • Property(s)
    • Basic Usage
  • Authentication Key
    • Description
    • Basic Usage
    • Returns
  • Filter Expression
    • Description
    • Method(s)
    • Basic Usage
© PubNub Inc. - Privacy Policy