Firebase Admin PHP SDK

repository·8.x·Indexed 25 days ago

https://github.com/beste/firebase-php

A Firebase Admin SDK for PHP that provides privileged server-side access to Firebase services, including Auth, Firestore, Cloud Messaging, Realtime Database, Remote Config, Cloud Storage, and App Check. It features a Factory class for service initialization and supports integration with Laravel and Symfony.

Tokens
31.1K
Snippets
103
Records
138
Agent score
81%

What's inside firebase-php

  1. Understand SignInResult

    8.x

    Custom authentication methods return an instance of Kreait irebase\Auth\SignInResult\SignInResult. This object provides access to the authentication data returned by the Firebase API.

    Available Accessors:

    • $signInResult->idToken(): Returns the ID token (string|null).
    • $signInResult->firebaseUserId(): Returns the Firebase UID (string|null).
    • $signInResult->accessToken(): Returns the access token (string|null).
    • $signInResult->refreshToken(): Returns the refresh token (string|null).
    • $signInResult->data(): Returns the full payload of the response (array).
    • $signInResult->asTokenResponse(): Returns the result in a format suitable for client-side consumption (array).
    $tokenResponse = [
        'token_type' => 'Bearer',
        'access_token' => '...',
        'id_token' => '...',
        'refresh_token' => '...',
        'expires_in' => 3600,
    ];
  2. Perform atomic transactions

    8.x

    Use runTransaction() to update data based on its current state. This ensures that if the data changes during the operation, the transaction fails rather than overwriting with stale data.

    Important: You must call $transaction->snapshot($reference) before attempting to modify a reference within a transaction.

    use Kreaitirebase//... (imports)
    use Kreaitirebase//... (imports)
    
    $counterRef = $database->getReference('counter');
    
    $result = $database->runTransaction(function (Transaction $transaction) use ($counterRef) {
        // You must snapshot the reference to change its value
        $counterSnapshot = $transaction->snapshot($counterRef);
    
        $counter = $counterSnapshot->getValue() ?: 0;
        $newCounter = ++$counter;
    
        $transaction->set($counterRef, $newCounter);
    
        return $newCounter;
    });
  3. Perform shallow queries to optimize large datasets

    8.x

    Shallow queries allow you to limit the depth of data returned. If the location contains a JSON object, the values for each key will be truncated to true, allowing you to see the structure without downloading large child nodes.

    Note: Shallow queries cannot be combined with any other query methods (like ordering or filtering).

    $database->getReference('currencies')
        ->shallow()
        ->getSnapshot();
  4. Handle Cloud Messaging errors and exceptions

    8.x

    All errors returned by the Firebase FCM API are converted into exceptions that implement the Kreait\ Firebase\\Exception\\MessagingException interface.

    Key features of these exceptions:

    • errors(): A method available on all MessagingException implementations that provides additional error details.
    • retryAfter(): Available on certain exceptions (like QuotaExceeded or ServerUnavailable) to return a DateTimeImmutable indicating when it is safe to retry the request.
    • token(): Available on NotFound exceptions to retrieve the specific token that could not be found.
  5. Query users with pagination and filters

    8.x

    If you need to paginate through subsets of users or apply specific filters, use queryUsers(). You can define a query using either a UserQuery object or a simple associative array.

    Query Modifiers

    • Sorting: You can sort by FIELD_CREATED_AT, FIELD_LAST_LOGIN_AT, FIELD_NAME, FIELD_USER_EMAIL, or FIELD_USER_ID.
    • Order: Use inDescendingOrder() or inAscendingOrder() (default).
    • Pagination: Use withOffset() and withLimit(). Note that the maximum supported limit is 500.

    Filtering

    You can filter by FILTER_EMAIL, FILTER_PHONE_NUMBER, or FILTER_UID.

    Important Constraints:

    • Filters do not support partial matches.
    • Only one filter can be applied at a time. If you specify multiple filters, only the last one will be submitted.
    use Kreait\Firebase\Auth\UserQuery;
    
    # Building a user query object
    $userQuery = UserQuery::all()
        ->sortedBy(UserQuery::FIELD_USER_EMAIL)
        ->inDescendingOrder()
        ->withOffset(1)
        ->withLimit(499); // Max limit is 500
    
    # Using an array
    $userQuery = [
        'sortBy' => UserQuery::FIELD_USER_EMAIL,
        'order' => UserQuery::ORDER_DESC,
        'offset' => 1,
        'limit' => 499,
    ];
    
    # Filtering examples
    $userQuery = UserQuery::all()->withFilter(UserQuery::FILTER_EMAIL, '<email>');
    $userQuery = ['filter' => [UserQuery::FILTER_EMAIL => '<email>']];
    
    $users = $auth->queryUsers($userQuery);
  6. Work with immutable objects

    8.x

    Most objects in this SDK are immutable. You can identify them by the presence of with* methods (e.g., withChangedProperty()). When calling these methods, the original object remains unchanged; you must capture the returned object to access the modifications.

    $changedObject = $object->withChangedProperty();
  7. Quickstart: Initialize Firebase services using the Factory

    8.x

    To access Firebase services, use the Kreait\Firebase\Factory class. You typically initialize the factory with a service account JSON file and, if necessary, a specific database URI. From the factory instance, you can create service-specific clients such as Auth, Realtime Database, Cloud Messaging, Remote Config, Cloud Storage, and Firestore.

    use Kreaitirebaseactory;
    
    $factory = (new Factory)
        ->withServiceAccount('/path/to/firebase_credentials.json')
        ->withDatabaseUri('https://my-project-default-rtdb.firebaseio.com');
    
    $auth = $factory->createAuth();
    $realtimeDatabase = $factory->createDatabase();
    $cloudMessaging = $factory->createMessaging();
    $remoteConfig = $factory->createRemoteConfig();
    $cloudStorage = $factory->createStorage();
    $firestore = $factory->createFirestore();
  8. Quick Start: Initialize Firebase services with Factory

    8.x

    To connect your application to Firebase, use the Kreait\Firebase\Factory class. You can configure the factory with a service account JSON file and a database URI, then use it to instantiate various Firebase service clients such as Auth, Realtime Database, Cloud Messaging, Remote Config, Cloud Storage, and Firestore.

    use Kreaitirebaseactory;
    
    $factory = (new Factory)
        ->withServiceAccount('/path/to/firebase_credentials.json')
        ->withDatabaseUri('https://my-project-default-rtdb.firebaseio.com');
    
    $auth = $factory->createAuth();
    $realtimeDatabase = $factory->createDatabase();
    $cloudMessaging = $factory->createMessaging();
    $remoteConfig = $factory->createRemoteConfig();
    $cloudStorage = $factory->createStorage();
    $firestore = $factory->createFirestore();
  9. Upgrade from 7.x to 8.0

    8.x

    Upgrading to version 8.0 involves several breaking changes aimed at reducing runtime overhead and improving security.

    Key Requirements:

    • PHP Version: Support for PHP < 8.3 has been dropped. You must use PHP 8.3, 8.4, or 8.5.
    • Firebase Dynamic Links: This feature has been removed from the SDK as the service was shut down on August 25th, 2025.

    Core Changes:

    • Type Simplification: Many methods that previously accepted Stringable|string now only accept string. You must explicitly cast Stringable objects to strings.
    • Security: Sensitive data (passwords, JWTs, API keys) now uses the #[SensitiveParameter] attribute to prevent exposure in stack traces.
    • Realtime Database: Value objects are now final and readonly.
    • Dependency Changes: psr/log is now a development dependency. If your application code relies on PSR Log interfaces, you must add psr/log to your own composer.json.
  10. Authenticate with limited privileges using auth variable overrides

    8.x

    To follow the principle of least privilege, you can use withDatabaseAuthVariableOverride() when creating your database instance. This allows you to simulate a specific uid in your Security Rules, effectively downscoping the Admin SDK's permissions to match a specific service identity defined in your rules.

    To act as an unauthenticated client, pass null to the override method.

    use Kreait\Firebase\Factory;
    
    $factory = (new Factory)
        ->withServiceAccount('/path/to/firebase_credentials.json')
        ->withDatabaseUri('https://my-project-default-rtdb.firebaseio.com');
    
    // Access as a specific service user defined in rules
    $database = $factory
        ->withDatabaseAuthVariableOverride('my-service-worker')
        ->createDatabase();
    
    // Access as an unauthenticated client (public access only)
    $database = $factory
        ->withDatabaseAuthVariableOverride(null)
        ->createDatabase();