Firebase is making lots of buzz lately, thanks to the amazing features provided by Firebase API. Firebase is a cloud service provider and BaaS (Backend as a Service) company it was recently acquired by Google. Firebase is a competitor to Facebook’s Parse.com. In today’s tutorial we will learn how to work with Firebase API using PHP cURL.
Firebase is a realtime time database which has it’s own API which allows developers to leverage it’s different features. It stores data in the JSON key-value form. It is extremely fast and an effective tool for writing webservices.
Firebase API allows us to provides various features it can allow us to Read, write, update, delete data. In order to make HTTP request all you need is to make request to your app URL which ends with .json extension. This way you can extract data or even override existing data, isn’t that amazing?
So lets get on with the Firebase API tutorial 🙂
Firebase API tutorial with PHP cURL
Firstly create an account and setup your app. Once you are done with this you can visit your app in the dashboard, once you select manage my app you will be able to add your data. In my case I will create simple mobile price database. It consists of only one Table Devices and it has one row which consists of name and value, I have added iPhone and it’s price.
Note: Firebase is not a RDBMS.
For the sake of simplicity we will say Devices is key and it has values which again has key and value which is identified by (iPhone:500). Here iPhone is key and 500 is value.
Now my data is sitting safely on firebase, in future if I have to get values I will make HTTP GET request and use it. There might be also need to alter data in future price may reduce so we need to update it we will need to use PATCH request to make that happen. To read more about REST API.
Lets check the code example
To Update the price I will use PATCH, it will update database realtime.
<?php $url = 'https://brilliant-torch-967.firebaseio.com/Devices.json'; $arr = array("Devices" =>array("iPhone"=>500)); $data_string = json_encode($arr); $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); echo $result = curl_exec($ch); ?>
Check out how to create PHP Login system using Sessions.
After running the script on live server or local host it will update the price realtime. This way you can update your data. I hope this firebase API tutorial was easy to understand. You can try out various method. Also Check How to get JSON Data using PHP.