Integrate Firebase With PHP and Optimize Your Real Time Communication

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:

What is Firebase

Setup Firebase and generate API keys.

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:

Create a Project in Firebase

Setup read and write rules for users

Move to user and permissions to generate API keys

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 versionavailable 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.

1

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:

1

2

3

4

5

6

7

8

9

{

"require":{

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

}

}

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

1

2

3

<?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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?php

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

useKreait\Firebase\Factory;

useKreait\Firebase\ServiceAccount;

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

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

1

2

3

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.

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

1

$users=newUsers();

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

1

2

3

4

5

6

7

8

9

10

11

$users=newUsers();

//var_dump($users->insert([

// '1' => 'John',

// '2' => 'Doe',

// '3' => 'Smith'

//]));

Similarly you can get or delete data like this:

1

2

3

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.

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:

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

<?php

require __DIR__.

'/vendor/autoload.php';

require'Users.php';

useKreait\Firebase\Factory;

useKreait\Firebase\ServiceAccount;

$users=newUsers();

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

$name=$_POST['name'];

$email=$_POST['email'];

$message=$_POST['message'];

$users->insert([

'name'=>$name,

'email'=>$email,

'message'=>$message

]);

}

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.

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