This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

Integrate Firebase With PHP and Optimize Your Real Time Communication

Updated on December 13, 2021

8 Min Read
php firebase

Real-time data management and transactions are the latest mode of communication these days. People need quick data flow while using mobile and web applications. There are alot of services available on internet for creating real-time databases and communication systems. For instance Pusher, Onesignal, and Google’s Firebase are famous tools for that. Previously, you’ve learned how to integrate Firebase in Laravel and covered the following topics:

  1. Setup Firebase and generate API keys.
  2. Integrate in Laravel

In this PHP Firebase example, i’ll give you a little recap of previous article and will show you how to Integrate Firebase in PHP 7.x, creating a simple CRUD functions with which you can perform database manipulation.

A Little Recap of Firebase

Firebase is a real-time communication service providing real-time data flow for chat, mobile and web applications. It provides several real time services including Cloud messaging, auth systems, Firebase PHP database, Notification systems, Storage and Firebase Hosting, making its platform a complete plethora of tools and services for developing high quality apps.

In this article, I will cover brief detailing of Firebase database. Actually, Firebase provides a PHP real time database and backend as a service. The service provides developers an API that allows application data synchronization across clients stored on Firebase cloud. This eliminates the need of any relational database system on your hosting server like MySQL and others.

What is Firebase Used For?

When the user wants to create, generate or fetch data at a very fast pace from database, Firebase real-time services gives them ease to perform operations like live streaming, chatting function and more. It is a perfect tool for the applications that has large databases such as Lyft, Shazam, Alibaba etc.

Some major features of Firebase are:

  • No extra money for backend server
  • Quick display of data in the server
  • NoSQL which means it faster
  • Analytics
  • Secured and fast hosting
  • Machine Learning Kit
  • Authentication service for user security
  • Cloud Storage
  • Rapid synchronization of data

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

Firebase VS MySQL

Firebase is literally different than traditional databases like MySQL and stores data in the form of documents. These documents can be manipulated in real-time in cross platform mediums. MySQL is a relational database which works with key->value concept and create relations with different set of data.

These relations are then used for data transactions. MySQL lacks the real-time data transition concept and requires so many work to create REST APIs.

On the other hand Firebase database provides different platforms like Android, iOS and Web for creating quick APIs. Basically Firebase is a hierarchical data structure i.e it’s just like a JSON tree in the cloud.

Firebase has the concept of keys, which are the names of the nodes that you store data under. You could somehow compare them to the primary keys of a relational database but there is no concept of a managed foreign key in it.

Get Your VueJS Handbook Now

Simple enter your email address and get the download link in your Inbox.

Thank You

Your Ebook is on it’s Way to Your Inbox.

Pros and Cons of Firebase

Recently I came across the Stack Exchange Question about pro’s and con’s of Firebase and it explains them very well.

Pro’s

  • If your app does run on a centralized DB, and is updated by a lot of users then it’s more than capable of handling the real-time data updates between devices.
  • Stored in the cloud so readily available everywhere.
  • Cross Platform API (If you are using this DB with an App)
  • They host the data – Meaning if you are storing a lot of data, you don’t have to worry about hardware.

Con’s:

  • Unless your app runs on one centralized database updated by a vast quantity of users, it’s a major overkill.
  • Storage format is entirely different to that of SQL (Firebase uses JSON). So you wouldn’t be able to migrate that easily.
  • Reporting tools are not anywhere near to the ones of standard SQL.
  • Costs – Limited to 50 Connections and 100mb of Storage.
  • You don’t host the data, Firebase does. Depending on which server you get, viewing there up time seems to be a lot of disruption lately.

Setting Up Firebase In Console

As I’ve mentioned above that the previous article has covered all the steps to setup Firebase database in console, you can simply follow that article for a quick recap. The points you need to follow for setting up Firebase are:

  1. Create a Project in Firebase
  2. Setup read and write rules for users
  3. Move to user and permissions to generate API keys
  4. Download secret Json file and save inside your project

Now, You are ready to integrate PHP with Firebase.  

Setup PHP Server at Cloudways

Since Cloudways is already providing PHP 7.x version on its hosting for PHP websites, you just need to signup and launch a server and all the rest comes premade on the platform. The application will setup along with the server and you can access it via URL in access details page

You need to take care of few things before running Firebase on PHP servers, that you must have PHP >= 7.0 version available with mbstring PHP extension.

You Might Also Like: How to Host PHP on Amazon AWS EC2

Integrate PHP With Firebase

Firebase has an awesome API which supports implementation in different languages. For using PHP with Firebase, it provides a complete PHP package which you can integrate for working with Firebase. In this application, i will use kreait/firebase-php which is recommended by Firebase also.

The recommended way to install the Firebase Admin SDK is with Composer. Composer is a dependency management tool for PHP that allows you to declare the dependencies your project needs and installs them into your project.

composer require kreait/firebase-php ^4.17.0

Alternatively, you can specify the Firebase Admin SDK as a dependency in your project’s existing composer.json file:

{

  "require": {

     "kreait/firebase-php": "^4.17.0"

  }

}

After installing, you need to require Composer’s autoloader:

<?php

require __DIR__.'/vendor/autoload.php';

Create Connection With Firebase

Once completing the package installation and adding the autolader to the PHP file, you can then create a connection with Firebase using the secret file downloaded from the console. You need to pass out the URL of that file in ServiceAccount::fromJsonFile() method. Secondly, find the Firebase application URL.

<?php

require __DIR__.'/vendor/autoload.php';



use Kreait\Firebase\Factory;

use Kreait\Firebase\ServiceAccount;



// This assumes that you have placed the Firebase credentials in the same directory

// as this PHP file.

$serviceAccount = ServiceAccount::fromJsonFile(__DIR__ . '/secret/php-firebase-7f39e-c654ccd32aba.json');



$firebase = (new Factory)

   ->withServiceAccount($serviceAccount)

   ->withDatabaseUri('https://my-project.firebaseio.com')

   ->create();



$database = $firebase->getDatabase();

Now at this time when you do var_dump($database); you will see the complete database object returned by the Firebase on your browser screen.

Create User Class in Users.php

The next thing I will do is the creation of new file called Users.php and declare a User class in it. The class will contain a constructor in which i will create a connection of PHP with Firebase API and initialize it. After that I’ll get the database created in firebase.

public function __construct(){

       $acc = ServiceAccount::fromJsonFile(__DIR__ . '/secret/php-firebase-7f39e-c654ccd32aba.json');

       $firebase = (new Factory)->withServiceAccount($acc)->create();

       $this->database = $firebase->getDatabase();

   }

Now to create PHP CRUD functions to manipulate database, I’ll create separate methods for each use case. But first let’s create two more properties outside of the constructor which contains the database name

protected $database;

   protected $dbname = 'users';

Now let’s create a get() method to retrieve the data. It will contain the userID to fetch specific user record. The method will also check if the userID is not available or set, in case of that will return false. While if founds the ID to be appropriately set, will retrieve the value successfully.

public function get(int $userID = NULL){    

       if (empty($userID) || !isset($userID)) { return FALSE; }

       if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){

           return $this->database->getReference($this->dbname)->getChild($userID)->getValue();

       } else {

           return FALSE;

       }

   }

Inside the insert() method, I’ll pass the array of data because it can contain single or multiple data. While if the data is already available for the specific userID, it will update the existing one.

public function insert(array $data) {

       if (empty($data) || !isset($data)) { return FALSE; }

       foreach ($data as $key => $value){

           $this->database->getReference()->getChild($this->dbname)->getChild($key)->set($value);

       }

       return TRUE;

   }

Now i’ll create a delete() function which will have userID as a parameter. The ID will be validated if is set, then remove() method will remove the data.

public function delete(int $userID) {

       if (empty($userID) || !isset($userID)) { return FALSE; }

       if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){

           $this->database->getReference($this->dbname)->getChild($userID)->remove();

           return TRUE;

       } else {

           return FALSE;

       }

   }

The complete User class will be as follows:

<?php

require_once './vendor/autoload.php';



use Kreait\Firebase\Factory;

use Kreait\Firebase\ServiceAccount;



class Users {

   protected $database;

   protected $dbname = 'users';

   public function __construct(){

       $acc = ServiceAccount::fromJsonFile(__DIR__ . '/secret/php-firebase-7f39e-c654ccd32aba.json');

       $firebase = (new Factory)->withServiceAccount($acc)->create();

       $this->database = $firebase->getDatabase();

   }



   public function get(int $userID = NULL){    

       if (empty($userID) || !isset($userID)) { return FALSE; }

       if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){

           return $this->database->getReference($this->dbname)->getChild($userID)->getValue();

       } else {

           return FALSE;

       }

   }



   public function insert(array $data) {

       if (empty($data) || !isset($data)) { return FALSE; }

       foreach ($data as $key => $value){

           $this->database->getReference()->getChild($this->dbname)->getChild($key)->set($value);

       }

       return TRUE;

   }



   public function delete(int $userID) {

       if (empty($userID) || !isset($userID)) { return FALSE; }

       if ($this->database->getReference($this->dbname)->getSnapshot()->hasChild($userID)){

           $this->database->getReference($this->dbname)->getChild($userID)->remove();

           return TRUE;

       } else {

           return FALSE;

       }

   }

}



?>

Now let’s test the class. Try to apply methods and check the Firebase database that it updates or not. First initialize the class:

$users = new Users();

Now let’s insert some data via insert() method:

$users = new Users();

//var_dump($users->insert([

//    '1' => 'John',

//    '2' => 'Doe',

//    '3' => 'Smith'

//]));

Similarly you can get or delete data like this:

var_dump($users->get(1));

var_dump($users->delete(2));

So you can see how I built a basic CRUD application using PHP and Firebase by creating a simple class. Obviously you can extend it and can create something exciting as per the requirements.

Keep Your Apps Secure on Cloud

Cloudways offers 2FA, free SSL, and more advanced security features on managed servers that keep your application safe.

Connect Firebase With PHP Contact Form

Contact form is a one essential component of any website as it gathers users messages and queries. Let’s create a simple PHP contact form and connect it with Firebase to receive messages. This will comprise on basic coding as it will just give you an idea how to connect it. I’ll use the same class User.php and its insert() function:

Contact form design code will be the following:

<!DOCTYPE html>

<html>



<head>

   <title>Page Title</title>

</head>



<body>



   <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

   <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>

   <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

   <!-- Include the above in your HEAD tag -->



   <div class="container">

       <div class="row">

           <div class="col-md-6 col-md-offset-3">

               <div class="well well-sm">

                   <form class="form-horizontal" action="" method="post">

                       <fieldset>

                           <legend class="text-center">Contact us</legend>



                           <!-- Name input-->

                           <div class="form-group">

                               <label class="col-md-3 control-label" for="name">Name</label>

                               <div class="col-md-9">

                                   <input id="name" name="name" type="text" placeholder="Your name" class="form-control">

                               </div>

                           </div>



                           <!-- Email input-->

                           <div class="form-group">

                               <label class="col-md-3 control-label" for="email">Your E-mail</label>

                               <div class="col-md-9">

                                   <input id="email" name="email" type="text" placeholder="Your email" class="form-control">

                               </div>

                           </div>



                           <!-- Message body -->

                           <div class="form-group">

                               <label class="col-md-3 control-label" for="message">Your message</label>

                               <div class="col-md-9">

                                   <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>

                               </div>

                           </div>



                           <!-- Form actions -->

                           <div class="form-group">

                               <div class="col-md-12 text-right">

                                   <button type="submit" name="submit" class="btn btn-primary btn-lg">Submit</button>

                               </div>

                           </div>

                       </fieldset>

                   </form>

               </div>

           </div>

       </div>

   </div>



</body>



</html>

Now in PHP file you can initialize the namespaces and User class. After that, simply catch the inputs and send them to the insert() method of Firebase. Also this is a basic code, you can extend it as per your requirements and validation rules:

< ? php



require __DIR__.

'/vendor/autoload.php';

require 'Users.php';


use Kreait\ Firebase\ Factory;

use Kreait\ Firebase\ ServiceAccount;


$users = new Users();


if (isset($_POST['submit'])) {


   $name = $_POST['name'];

   $email = $_POST['email'];

   $message = $_POST['message'];


   $users - > insert([

       'name' => $name,

       'email' => $email,

       'message' => $message

   ]);



}

Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%

Final Words

Technology is evolving at a rapid pace. In order to be competitive and stay in the race, you have to update yourself with the changing ones. Similarly databases are also evolving frequently and we can see a lot of services today providing real-time database, processing data in nick of time.

In this Firebase PHP example, I’ve demonstrated you how to integrate PHP with Firebase and connect it with a contact form with simple class. Once connecting successfully, you can create more complex use-cases to utilize Firebase services. I’ll be also writing more about Firebase with PHP later.

Q: Can I use Firebase with PHP?

A: Yes, Firebase provides a comprehensive API for integrating the platform with your PHP projects.

Q: Can I host PHP on Firebase?

A: No, Firebase only supports static hosting and as such, you cannot host PHP scripts on Firebase.

Q: How can I get data from a Firebase database using PHP?

To get the Firebase data, you need to go to the project folder and run the command:

php composer.phar require kreait/firebase-php

Next, a new index.php to the project folder and add the following line to the top of index.php:

require DIR.'/vendor/autoload.php';

Next, create a JSON file in the folder

Edit the index.php and create a connection to the database.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now