Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Add Docs
phpcent
https://github.com/centrifugal/phpcent
Admin
phpcent is a PHP library that enables communication with Centrifugo v5 HTTP API for real-time
...
Tokens:
11,299
Snippets:
97
Trust Score:
9.6
Update:
1 week ago
Context
Skills
Chat
Benchmark
96.7
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# phpcent phpcent is a PHP library for communicating with the [Centrifugo v5 HTTP API](https://centrifugal.dev/docs/server/server_api). It provides a simple, fluent interface to interact with a running Centrifugo real-time messaging server from a PHP backend, allowing server-side publishing, channel management, presence inspection, and JWT token generation for client authentication. The library wraps cURL-based HTTP requests to Centrifugo's REST API and handles JSON encoding/decoding, authentication headers, SSL configuration, and JWT generation. It supports all major Centrifugo server-side operations: publishing messages to channels, broadcasting to multiple channels, managing subscriptions and connections, querying presence and history data, and generating HS256-signed connection and subscription tokens for WebSocket clients. --- ## Installation Install via Composer from Packagist. ```bash composer require centrifugal/phpcent:~6.0 ``` --- ## Client Initialization Instantiate the `\phpcent\Client` with the Centrifugo HTTP API endpoint and optional credentials. ```php <?php require 'vendor/autoload.php'; // Basic initialization with fluent setters $client = new \phpcent\Client("http://localhost:8000/api"); $client->setApiKey("my-api-key"); $client->setSecret("my-secret-key"); // All-in-one constructor (url, apikey, secret) $client = new \phpcent\Client( "http://localhost:8000/api", "my-api-key", "my-secret-key" ); ``` --- ## publish — Publish a message to a channel Sends a data payload to all subscribers of the specified channel. Optionally skip writing the message to history with `$skipHistory = true`. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); try { $response = $client->publish("news:feed", [ "id" => 42, "title" => "Breaking News", "body" => "Something important happened.", "ts" => time(), ]); // Success: $response->result is an empty object {} echo "Published successfully\n"; } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } // Skip history when publishing $client->publish("chat:room1", ["text" => "Hello!"], true); ``` --- ## broadcast — Broadcast a message to multiple channels Sends the same data payload to all specified channels in a single API call. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); try { $response = $client->broadcast( ["notifications:user#1", "notifications:user#2", "notifications:user#3"], ["type" => "alert", "message" => "Your order has shipped!"] ); echo "Broadcast complete\n"; } catch (\Exception $e) { echo "Broadcast failed: " . $e->getMessage() . "\n"; } ``` --- ## subscribe — Server-side subscribe a user to a channel Forces a user to subscribe to a channel from the server side. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); $response = $client->subscribe("chat:room42", "user-123"); echo "User subscribed\n"; ``` --- ## unsubscribe — Unsubscribe a user from a channel Removes a user's server-side subscription to the given channel. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); try { $response = $client->unsubscribe("chat:room42", "user-123"); echo "User unsubscribed successfully\n"; } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` --- ## disconnect — Disconnect a user from Centrifugo Forcefully disconnects a user (all their connections) from the Centrifugo server. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); try { $response = $client->disconnect("user-123"); echo "User disconnected\n"; } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` --- ## presence — Get current channel presence information Returns information about all clients currently subscribed to a channel, including client IDs and user IDs. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); $client->setUseAssoc(true); // decode response as associative array try { $response = $client->presence("chat:room42"); // $response['result']['presence'] is a map of client_id => client_info foreach ($response['result']['presence'] as $clientId => $info) { echo "Connected client: $clientId, user: " . $info['user'] . "\n"; } } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` --- ## presenceStats — Get presence statistics for a channel Returns aggregate counts of unique clients and users subscribed to a channel, without full presence detail. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); $response = $client->presenceStats("chat:room42"); // $response->result->num_clients - total connected clients // $response->result->num_users - total unique users echo "Clients: " . $response->result->num_clients . "\n"; echo "Users: " . $response->result->num_users . "\n"; ``` --- ## history — Retrieve message history for a channel Fetches stored messages from a channel's history. Supports limiting results, reverse ordering, and pagination via a `since` offset. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); // Get last 10 messages $response = $client->history("chat:room42", 10); // Get last 5 messages in reverse order $response = $client->history("chat:room42", 5, [], true); // Paginate: get messages since a specific epoch/offset $response = $client->history("chat:room42", 10, [ 'offset' => 15, 'epoch' => 'some-epoch-value', ]); foreach ($response->result->publications as $pub) { print_r($pub->data); } ``` --- ## historyRemove — Clear channel history Removes all stored history messages for the specified channel. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); try { $client->historyRemove("chat:room42"); echo "History cleared\n"; } catch (\Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` --- ## channels — List all active channels Returns a list of all channels that currently have active subscribers. Supports an optional glob pattern filter. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); // All active channels $response = $client->channels(); foreach ($response->result->channels as $channel => $info) { echo "Active channel: $channel\n"; } // Filter channels by pattern $response = $client->channels("chat:*"); foreach ($response->result->channels as $channel => $info) { echo "Chat channel: $channel\n"; } ``` --- ## info — Get Centrifugo server info Returns information about the running Centrifugo server nodes. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); $response = $client->info(); // $response->result->nodes is an array of node info objects foreach ($response->result->nodes as $node) { echo "Node: " . $node->name . ", clients: " . $node->num_clients . "\n"; } ``` --- ## batch — Send multiple commands in a single request Executes multiple Centrifugo API commands in one HTTP request, reducing round-trip overhead. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api", "my-api-key"); $response = $client->batch([ "commands" => [ [ "presence_stats" => ["channel" => "chat:room1"] ], [ "publish" => [ "channel" => "chat:room1", "data" => ["text" => "Hello from batch!"] ] ], [ "history" => ["channel" => "chat:room1", "limit" => 5] ], ] ]); // $response->replies contains one result per command foreach ($response->replies as $reply) { print_r($reply); } ``` --- ## generateConnectionToken — Generate a JWT for WebSocket connection authentication Creates an HS256-signed JWT that a frontend client presents when connecting to Centrifugo. Supports expiration, user metadata, info claims, and server-side channel subscriptions. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api"); $client->setSecret("my-centrifugo-secret"); // Non-expiring token (not recommended for production) $token = $client->generateConnectionToken("user-123"); // Token valid for 5 minutes $token = $client->generateConnectionToken("user-123", time() + 5 * 60); // Token with additional info and server-side subscriptions $token = $client->generateConnectionToken( "user-123", time() + 3600, ["name" => "Alice", "role" => "admin"], // info ["notifications:user#user-123", "global"], // server-side channels ["plan" => "pro"] // meta ); // Use $token in JavaScript: // const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket', { token: '...' }); echo $token; // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9... ``` --- ## generateSubscriptionToken — Generate a JWT for private channel subscription Creates an HS256-signed JWT allowing a specific user to subscribe to a private channel. Required when `channel_token_auth` is enabled in Centrifugo. ```php <?php $client = new \phpcent\Client("http://localhost:8000/api"); $client->setSecret("my-centrifugo-secret"); // Basic subscription token $token = $client->generateSubscriptionToken("user-123", "private:room42"); // Token valid for 30 minutes with additional channel info $token = $client->generateSubscriptionToken( "user-123", "private:room42", time() + 30 * 60, ["permissions" => ["read", "write"]] ); echo $token; // eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9... ``` --- ## SSL and Connection Configuration Configure TLS, timeouts, and DNS resolution options for production environments. ```php <?php // Disable SSL verification (development only) $client = new \phpcent\Client("https://centrifugo.example.com/api", "my-api-key"); $client->setSafety(false); // Use a self-signed certificate securely $client = new \phpcent\Client("https://localhost:8000/api", "my-api-key"); $client->setCert("/path/to/certificate.pem"); $client->setCAPath("/path/to/ca-bundle"); // optional CA directory // Set connection and request timeouts $client->setConnectTimeoutOption(3); // 3 seconds to establish connection $client->setTimeoutOption(10); // 10 seconds max for full request // Use 0 for no timeout: $client->setConnectTimeoutOption(0); // Force IPv4 DNS resolution (fixes cURL IPv6 resolution timeouts) $client->forceIpResolveV4(); // Return responses as associative arrays instead of stdClass objects $client->setUseAssoc(true); $response = $client->publish("chat:room1", ["msg" => "hi"]); // Now $response['result'] instead of $response->result ``` --- ## Summary phpcent is the standard PHP integration layer for Centrifugo real-time servers, enabling PHP backends to drive WebSocket-based real-time features without managing connection state. Core use cases include: publishing live updates (chat messages, notifications, dashboards) from PHP controllers or workers, generating short-lived JWTs for authenticating WebSocket connections and private channel subscriptions, managing user sessions by forcefully disconnecting or unsubscribing users, and inspecting channel state via presence and history APIs. In typical integration patterns, phpcent is used server-side within Laravel/Symfony controllers or background queue workers to publish events after database writes, while the JWT generation methods are called from authentication endpoints to issue tokens that frontend JavaScript (using the Centrifuge JS client) exchanges for a live WebSocket connection. The fluent configuration API and full SSL/TLS support make it straightforward to deploy in both local development (with Docker-hosted Centrifugo) and production environments behind HTTPS.