Chat with us, powered by LiveChat

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.

Say hello to redesigned Cloudways, an empowering Startup Program, enhanced Staging, a new Let’s Encrypt Wildcard SSL certificate feature, and more. GET STARTED

Integrate Firebase With PHP and Optimize Your Real Time Communication

Updated on November 6, 2018

7 Min Read
php firebase
Reading Time: 7 minutes

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. What is Firebase
  2. Setup Firebase and generate API keys.
  3. 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.

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.

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.

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.

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

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

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.

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.

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

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.

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.

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.

The complete User class will be as follows:

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

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

Similarly you can get or delete data like this:

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.

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:

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:

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.

Till then if you have any questions please comment below.

Share your opinion in the comment section. COMMENT NOW

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com

Create PHP websites without the worry of server management.

Deploy your PHP app on optimized PHP hosting servers.

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

THERE’S MORE TO READ.