Can php connect to firebase?

Using the lib is very easy, when you just look at the source code of the tests.

There are two kinds of tests:

  • a real functionality test, which uses cURL requests to the server and therefore is slow during testing with PHPUnit
  • a mocked functionality test (stub), which simulates the connection to and the response from the server, which is faster during testing

Now, in order to use firebase-php, you would simply do the same things as in the real functionality test. Include the lib, prepare the connection object with login credentials and then call the method you want. The interface describes, which methods you can expect in the firebaseLib class - or just look at the lib source itself.

This piece of code should get you started:

require '/path/to/libs/firebase-php/firebaseLib.php';
$url = '...';
$token = '...';
$firebase = new Firebase($url, $token);
$firebase->get('something/from/somewhere');

If you fetch the library via composer, you might declare an autoloading classmap, too. The author hasn't done this, yet.

{
    "autoload": {
        "classmap": ["vendor/ktamas77/firebase-php/firebaseLib.php"]
    }
}

Then simply require Composer's Autoloader with require "vendor/autoload.php"; and new Firebase to autoload the class.


How to get the auth token

  • open your firebase console
  • go to project settings
  • go to the database
  • then copy the secret key

Can php connect to firebase?

Step to start :

  1. Create firebase account for web app

https://firebase.google.com/products/ as per this guideline create cloud storage and create your Firebase account

2. Then create service account for configuration JSON parameters

follow this installation guide

https://firebase-php.readthedocs.io/en/stable/setup.html#setup

https://developers.google.com/identity/protocols/OAuth2ServiceAccount

Can php connect to firebase?

Download JSON file name will like “api-project-1075484619737–3371fe5240c8.json”. Keep this file this will use in step 3 while doing configuration in project

Can php connect to firebase?

3. Install firebase in your machine using composer

https://firebase-php.readthedocs.io/en/stable/overview.html#installation

Note : PHP 7.X is recommend for this.

then

Overview - Firebase Admin SDK for PHP Documentation

Edit description

firebase-php.readthedocs.io

4. Installation complete! Enjoy. Next blog will cover fetching record from database.

Firebase Admin SDK for PHP

Google Service Account¶

In order to access a Firebase project using a server SDK, you must authenticate your requests to Firebase with Service Account credentials.

To authenticate a service account and authorize it to access Firebase services, you must generate a private key file in JSON format.

To generate a private key file for your service account:

  1. Open https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk and select the project you want to generate a private key file for.
  2. Click Generate New Private Key, then confirm by clicking Generate Key
  3. Securely store the JSON file containing the key.

Note

You should store the JSON file outside of your code repository to avoid accidentally exposing it to the outside world.

You can then configure the SDK to use this Service Account:

With the SDK

use Kreait\Firebase\Factory;

$factory = (new Factory)->withServiceAccount('/path/to/firebase_credentials.json');

With the Symfony Bundle

Please see https://github.com/kreait/firebase-bundle#configuration

With the Laravel/Lumen Package

Please see https://github.com/kreait/laravel-firebase#configuration

With autodiscovery¶

The SDK is able to auto-discover the Service Account for your project in the following conditions:

  1. Your application runs on Google Cloud Engine.
  2. The path to the JSON key file is defined in one of the following environment variables
    • GOOGLE_APPLICATION_CREDENTIALS
  3. The JSON Key file is located in Google’s “well known path”
    • on Linux/MacOS: $HOME/.config/gcloud/application_default_credentials.json
    • on Windows: $APPDATA/gcloud/application_default_credentials.json

If you want to use autodiscovery, a Service Account must not be explicitly configured.

Project ID¶

Service Account credentials include the ID of the Google Cloud Project your Firebase project belongs to.

If you use another type of credential, it might be necessary to provide it manually to the Firebase Factory.

use Kreait\Firebase\Factory;

$factory = (new Factory())
    ->withProjectId('my-project')
    ->withDatabaseUri('https://my-project.firebaseio.com');

You can also set a GOOGLE_CLOUD_PROJECT= environment variable before calling the factory.

Realtime Database URI¶

Note

You can find the URI for your Realtime Database at https://console.firebase.google.com/project/_/database. For recently created Firebase projects the default database URI usually has the format https://-default-rtdb.firebaseio.com. Databases in projects created before September 2020 had the default database URI https://.firebaseio.com.

For backward compatibility reasons, if you don’t specify a database URI, the SDK will use the project ID defined in the Service Account JSON file to automatically generate it.

use Kreait\Firebase\Factory;

$factory = (new Factory())
    ->withDatabaseUri('https://my-project.firebaseio.com');

Caching¶

Authentication tokens¶

Before connecting to the Firebase APIs, the SDK fetches an authentication token for your credentials. This authentication token is cached in-memory so that it can be re-used during the same process.

If you want to cache authentication tokens more effectively, you can provide any implementation of psr/cache to the Firebase factory when creating your Firebase instance.

Note

Authentication tokens are cached in-memory by default. For Symfony and Laravel, the Framework’s cache will automatically be used.

For Symfony and Laravel, the Framework’s cache will automatically be used.

Here is an example using the Symfony Cache Component:

use Symfony\Component\Cache\Simple\FilesystemCache;

$factory = $factory->withAuthTokenCache(new FilesystemCache());

ID Token Verification¶

In order to verify ID tokens, the verifier makes a call to fetch Firebase’s currently available public keys. The keys are cached in memory by default.

If you want to cache the public keys more effectively, you can provide any implementation of psr/simple-cache to the Firebase factory when creating your Firebase instance.

Note

Public keys tokens are cached in-memory by default. For Symfony and Laravel, the Framework’s cache will automatically be used.

Here is an example using the Symfony Cache Component:

use Symfony\Component\Cache\Simple\FilesystemCache;

$factory = $factory->withVerifierCache(new FilesystemCache());

End User Credentials¶

Note

While theoretically possible, it’s not recommended to use end user credentials in the context of a Server-to-Server backend application.

When using End User Credentials (for example if you set you application default credentials locally with gcloud auth application-default login), you need to provide the ID of the project you want to access directly and suppress warnings triggered by the Google Auth Component:

use Kreait\Firebase\Factory;

putenv('SUPPRESS_GCLOUD_CREDS_WARNING=true');

// This will use the project defined in the Service Account
// credentials files by default
$base = (new Factory())->withProjectId('firebase-project-id');

HTTP Client Options¶

You can configure the behavior of the HTTP Client performing the API requests by passing an instance of KreaitFirebaseHttpHttpClientOptions to the factory before creating a service.

use Kreait\Firebase\Http\HttpClientOptions;

$options = HttpClientOptions::default();

// Set the maximum amount of seconds (float) that can pass before
// a request is considered timed out
// (default: indefinitely)
$options = $options->withTimeOut(3.5);

// Use a proxy that all API requests should be passed through.
// (default: none)
$options = $options->withProxy('tcp://:');

$factory = $factory->withHttpClientOptions($options);

// Newly created services will now use the new HTTP options
$realtimeDatabase = $factory->createDatabase();

Logging¶

In order to log API requests to the Firebase APIs, you can provide the factory with loggers implementing Psr\Log\LoggerInterface.

The following examples use the Monolog logger, but work with any PSR-3 log implementation.

use GuzzleHttp\MessageFormatter;
use Kreait\Firebase\Factory;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$httpLogger = new Logger('firebase_http_logs');
$httpLogger->pushHandler(new StreamHandler('path/to/firebase_api.log', Logger::INFO));

// Without further arguments, requests and responses will be logged with basic
// request and response information. Successful responses will be logged with
// the 'info' log level, failures (Status code >= 400) with 'notice'
$factory = $factory->withHttpLogger($httpLogger);

// You can configure the message format and log levels individually
$messageFormatter = new MessageFormatter(MessageFormatter::SHORT);
$factory = $factory->withHttpLogger(
    $httpLogger, $messageFormatter, $successes = 'debug', $errors = 'warning'
);

// You can provide a separate logger for detailed HTTP message logs
$httpDebugLogger = new Logger('firebase_http_debug_logs');
$httpDebugLogger->pushHandler(
    new StreamHandler('path/to/firebase_api_debug.log',
    Logger::DEBUG)
);

// Logs will include the full request and response headers and bodies
$factory = $factory->withHttpDebugLogger($httpDebugLogger)

How can I get data from Firebase database using PHP?

CD into projects folder and run: php composer.phar require kreait/firebase-php..
Create a new index.php on the project to test..
Add to the top of index. php: require DIR. '/vendor/autoload. php';.
Inside Fibase project overview, create a service account and save the FriendlyChat-1f226af19083. json to the project folder..

How do I upload a PHP site to Firebase?

Check your Apache httpd.conf file (or /extra/mod_php.conf) and add/uncomment AddType application/x-httpd-php .php. ... .
Firebase hosting is for static files only - no PHP or other server-side processing. ... .
Cross-post: groups.google.com/forum/#!topic/firebase-talk/m-m1eVPQ7OA..

Can I use Firebase with MySQL?

With Firebase MySQL Integration, you can use the flexible, powerful, and simple UI of Firebase with a reliable database like MySQL, all in one package.

Can I use Laravel with Firebase?

To access Firebase in Laravel, you will first have to configure Laravel to support it. This is done by installing a Firebase package for Laravel, such as kreait/firebase-php, which also supports Lumen projects. To install the package, run the command below.