PHP code example of artisan-build / pusher-websocket-php

1. Go to this page and download the library: Download artisan-build/pusher-websocket-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

artisan-build / pusher-websocket-php example snippets


use ArtisanBuild\Pusher\Pusher;
use ArtisanBuild\Pusher\Options;

$pusher = new Pusher('your-app-key', new Options(
    cluster: 'mt1',
    wsHost: '127.0.0.1',
    wsPort: 6001,
    forceTLS: false,
));

// Subscribe to a channel
$channel = $pusher->subscribe('my-channel');

// Listen for events
$channel->bind('my-event', function ($data) {
    echo "Received: " . json_encode($data) . "\n";
});

// Connect to the server
$pusher->connect();

// Public channel
$channel = $pusher->subscribe('news');

// Private channel (l (

// Bind to a specific event
$channel->bind('message', function ($data) {
    // Handle the event
});

// Bind to all events on a channel
$channel->bind_global(function ($event, $data) {
    echo "Event: {$event}\n";
});

// Unbind
$channel->unbind('message');

new Options(
    cluster: 'mt1',           // Pusher cluster (001,             // WebSocket port (non-TLS)
    wssPort: 443,             // WebSocket port (TLS)
    forceTLS: true,           // Force TLS connection
    activityTimeout: 120000,  // Milliseconds before sending ping
    pongTimeout: 30000,       // Milliseconds to wait for pong
    channelAuthorization: [   // For private/presence channels
        'transport' => 'http',
        'endpoint' => 'https://your-app.com/broadcasting/auth',
        'headers' => [
            'Authorization' => 'Bearer your-token',
        ],
    ],
);

$pusher = new Pusher('app-key', new Options(
    wsHost: '127.0.0.1',
    wsPort: 8080,
    channelAuthorization: [
        'transport' => 'http',
        'endpoint' => 'https://your-app.com/broadcasting/auth',
        'headers' => [
            'Authorization' => 'Bearer ' . $token,
            'Accept' => 'application/json',
        ],
    ],
));

// Now private channels will authenticate automatically
$channel = $pusher->subscribe('private-user-123');

channelAuthorization: [
    'customHandler' => function ($params, $callback) {
        // $params->socketId - the socket ID
        // $params->channelName - the channel being authorized

        // Make your own auth request...
        $authData = myCustomAuth($params);

        // Call back with result
        $callback(null, new ChannelAuthorizationData(auth: $authData['auth']));
    },
],
bash
php artisan reverb:start