1. Go to this page and download the library: Download webrek/supabase-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/ */
webrek / supabase-php example snippets
use Supabase\Client;
$supabase = new Client('https://YOUR-PROJECT.supabase.co', 'YOUR-ANON-KEY');
$realtime = $supabase->withAccessToken($jwt)->realtime();
$realtime->connect();
$realtime->channel('room-1', ['private' => true])
->onBroadcast('*', function (array $message): void { /* ... */ })
->subscribe();
// Long-running worker: rotate the token without reconnecting. Joined channels
// receive an access_token event; later joins carry the new token.
$realtime->setAuth($freshJwt);
$channel = $realtime->channel('room-1')
->onPresenceSync(function (): void {
// Fired every time the full presence state is (re)synced — on join and
// after every diff. Read the current snapshot with presenceState().
})
->onPresenceJoin(function (string $key, array $currentPresences, array $newPresences): void {
// A client started tracking; $newPresences lists their state payloads.
})
->onPresenceLeave(function (string $key, array $currentPresences, array $leftPresences): void {
// A client stopped tracking.
})
->subscribe();
// Announce your own state (any serialisable array):
$channel->track(['user_id' => 42, 'online_at' => time()]);
// Read the current snapshot:
// array<string, list<array<string, mixed>>> — keyed by presence key; each
// presence carries a `presence_ref` field plus your tracked payload.
$state = $channel->presenceState();
// Stop broadcasting (leaves the channel's presence):
$channel->untrack();
$client = new Client('https://YOUR-PROJECT.supabase.co', 'YOUR-ANON-KEY', new ClientOptions(
webSocketFactory: new MyWebSocketConnectionFactory(),
realtimeAutoReconnect: true,
realtimeReconnectBaseDelay: 1.0, // initial retry delay in seconds (default)
realtimeReconnectMaxDelay: 30.0, // cap on retry delay in seconds (default)
));
$realtime = $client->realtime();
$realtime->connect();
// ... subscribe channels ...
$realtime->run(); // loops forever; reconnects + re-subscribes if the socket drops
use Supabase\Realtime\WebSocketConnection;
use Supabase\Realtime\WebSocketConnectionFactory;
final class MyWebSocketConnection implements WebSocketConnection
{
private $client; // your WebSocket client of choice
public function connect(string $url, array $headers = []): void
{
// open the connection to $url with $headers
}
public function send(string $data): void
{
// send a text frame
}
public function receive(float $timeoutSeconds): ?string
{
// return the next text frame, or null if $timeoutSeconds elapsed
}
public function close(int $code = 1000, string $reason = ''): void
{
// close the connection
}
public function isConnected(): bool
{
// report connection state
}
}
final class MyWebSocketConnectionFactory implements WebSocketConnectionFactory
{
public function create(): WebSocketConnection
{
return new MyWebSocketConnection();
}
}
use Supabase\Client;
use Supabase\ClientOptions;
use Supabase\Realtime\PhrityWebSocketConnectionFactory;
$client = new Client('https://YOUR-PROJECT.supabase.co', 'YOUR-ANON-KEY', new ClientOptions(
webSocketFactory: new PhrityWebSocketConnectionFactory(),
));
// Sign up (returns null if the project @b.com', 'password');
// Sign in
$session = $supabase->auth()->signInWithPassword('[email protected]', 'password');
$session->accessToken; // string (redacted in dumps; never logged)
$session->user->id; // string
// Get / update the user behind a JWT
$user = $supabase->auth()->getUser($session->accessToken);
$user = $supabase->auth()->updateUser($session->accessToken, ['data' => ['name' => 'Ada']]);
// Refresh and sign out
$session = $supabase->auth()->refreshSession($session->refreshToken);
$supabase->auth()->signOut($session->accessToken);
// OTP, password reset, OAuth URL
$supabase->auth()->signInWithOtp(['email' => '[email protected]']);
$supabase->auth()->resetPasswordForEmail('[email protected]');
$url = $supabase->auth()->getOAuthSignInUrl('github', ['redirect_to' => 'https://app.test/cb']);
use Supabase\Auth\Pkce;
// 1. Before redirecting
$pkce = Pkce::generate();
$_SESSION['pkce_verifier'] = $pkce->verifier;
header('Location: ' . $supabase->auth()->getOAuthSignInUrl('github', [
'redirect_to' => 'https://app.test/auth/callback',
], $pkce));
// 2. In the callback (?code=...)
$session = $supabase->auth()->exchangeCodeForSession($_GET['code'], $_SESSION['pkce_verifier']);
use Supabase\Auth\Session;
// From a JWT you already hold (cookie, Authorization header, ...)
$asUser = $supabase->withAccessToken($jwt);
$todos = $asUser->from('todos')->select()->execute(); // RLS applies as that user
// From a Session — refreshed first if it is expired or expires within 30s
$asUser = $supabase->withSession($session, onTokenRefreshed: function (Session $fresh): void {
// persist $fresh->accessToken / $fresh->refreshToken (cookie, cache, ...)
});
use Supabase\ClientOptions;
$supabase = new Client($url, $anonKey, new ClientOptions(
jwksCache: $psr16Cache, // any PSR-16 store: APCu, Redis, filesystem, ...
jwksCacheTtl: 600, // seconds (default)
));
$claims = $supabase->auth()->getClaims($jwt); // AuthException if invalid, expired or not yet valid
$claims->sub; // user id
$claims->role; // 'authenticated'
$claims->email;
$claims->raw['aal']; // any other claim
use Supabase\Client;
use Supabase\ClientOptions;
$supabase = new Client('https://YOUR-PROJECT.supabase.co', 'YOUR-ANON-KEY', new ClientOptions(
httpClient: $myPsr18Client,
requestFactory: $myPsr17Factory,
streamFactory: $myPsr17Factory,
));
use Supabase\Exception\SupabaseException;
try {
$supabase->functions()->invoke('broken');
} catch (SupabaseException $e) {
$e->getStatusCode(); // HTTP status
$e->getErrorCode(); // Supabase error code, if any
$e->getResponseBody(); // raw response body
}
$httpClient = new \GuzzleHttp\Client([
'allow_redirects' => false,
'timeout' => 10,
'verify' => true,
]);
new Client($url, $key, new ClientOptions(httpClient: $httpClient));
bash
composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.