Send Push Notification to Android Using PHP And Firebase
Basically, we have used GCM(Google Cloud Messaging) for sending push notification to Android devices.
Recently Google has been launched Firebase Cloud Messaging (FCM), the latest version of GCM (Google Cloud Messaging) with more properties.
This article is useful for the PHP developers who want to send push notifications by using PHP with FCM(Firebase Cloud Messaging).
Push notification was a viral protocol which gives bloom to business in Today’s digital world. Here we will explain to you about, What is Push Notification? How to create a Push Notification using different platforms/services like PHP (Hypertext Preprocessor ), GCM (Google Cloud Messaging) and FCM (Firebase Cloud Messaging)? Let’s start
What is Push Notification?
In general, Push notifications are the message / Notifications you will receive in Android. This makes the customers engage with the clients on digital platforms. This service can be initiated in either way form users or from clients. This makes the basic difference and leads to subdivisions of protocol into two forms. The first one is User registration and the next one is Client broadcasting.
In User registration, the user will send the request for the service from the clients, through GCM/FCM in a messaging format. Then the cloud server will initiate a token with the unique information to connect the user with the client. This token id of the user will be stored in a remote database. Then the connection between the user and client will be open.
In Client Broadcasting, the client will raise the request for the external user. This request will have a unique Authorization key and Device token for a list of users. The cloud service ( FCM/GCM ) accepts the request and broadcasts the message to all users on the list. The user will get a notification on Android App.
You can send push notification to android using php. here are the steps, lets, check it out.
How to Send a Push Notification Using PHP?
Prerequisite:
- Authorization key (Server Key)
- Device Token
You can get device token at the time of registering by the android users using API.
Lets Create PHP Files
- Goto your WAMP/XAMPP directory and create a new folder named notification inside htdocs or www.
- Create a file named fcm.php and add the below push notification php code. Here we define the Firebase Server API Key to send a request to firebase.
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 |
<?php class FCM { function __construct() { } /** * Sending Push Notification */ public function send_notification($registatoin_ids, $notification,$device_type) { $url = 'https://fcm.googleapis.com/fcm/send'; if($device_type == "Android"){ $fields = array( 'to' => $registatoin_ids, 'data' => $notification ); } else { $fields = array( 'to' => $registatoin_ids, 'notification' => $notification ); } // Firebase API Key $headers = array('Authorization:key=Your Firebase Server API Key Here','Content-Type:application/json'); // Open connection $ch = curl_init(); // Set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Disabling SSL Certificate support temporarly curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); } } ?> |
- Be sure to replace the Your Firebase Server API Key Here with a proper one from the Google API’s Console page.
3. Finally, create an index.php and add the below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $regId ="Your Device Token"; // INCLUDE YOUR FCM FILE include_once 'fcm.php'; $notification = array(); $arrNotification= array(); $arrData = array(); $arrNotification["body"] ="Test by Vijay."; $arrNotification["title"] = "PHP ADVICES"; $arrNotification["sound"] = "default"; $arrNotification["type"] = 1; $fcm = new FCM(); $result = $fcm->send_notification($regId, $arrNotification,"Android"); ?> |
Before testing please replace Your Device Token with your real device token.
Send Push Notification to IOS Using PHP
You just need to change “Android” to “IOS” in your index.php file. like below…
1 |
$result=$fcm->send_notification($regId,$arrNotification,"Android"); |
To
1 |
$result=$fcm->send_notification($regId, $arrNotification,"IOS"); |
Hope it helped you in an easy way to send push notification to android using php. Please let us know in the comment section if you have any concern.
You can also share with your friends, who need to send push notification to android and IOS using PHP.
Thanks for your time, to know about me.
Hello I Am Vijay Poshiya. 🙂
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming. I can give you a cake walkthrough platform where a complex program can make it easier for you. I will also provide you with the rare collections of task sets over the internet.
I hope you will find your solutions in better understanding shape within my blog.
You can read more about PHPAdvices at the “About” page.
Thank you so much, this is just what I needed!
Most Welcome Sir
hi
nice, does it still works in 2021, or any changes.
plz let me know how to send image in notification.
Thanks
I am not getting notification !
Hi Varinder,
Can you please print results like below and send the printed result here so, I will figure out where is the problem.
$result = curl_exec($ch);
print_r($result);
Thank You!
how i get device token
regarding, get device token, i will post separate post asap.
Thank you!
how to get the device token from my smartphone?
Same. Not getting any notification
Hi Rahul Saini,
Can you please print results like below and send the printed result here so, I will figure out where is the problem.
$result = curl_exec($ch);
print_r($result);
Thank You!
$result = curl_exec($ch);
print_r($result);
output
{“multicast_id”:3085328206339615988,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1590928332987446%7d276763f9fd7ecd”}]}
Success = 1, looks like the message is getting delivered successfully.
Bug on the android side. does android dev has added proper code for receive notification?
Are you able to run the app on a test device and see if the message is being delivered?
Change data to notification, and it will work
if($device_type == “Android”){
$fields = array(
‘to’ => $registatoin_ids,
‘notification’ => $notification
);
}
Hello, I also don’t receive a notification.
Debug shows “success” though:
{“multicast_id”:1302051421407238304,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1591228917053827%ba3ddd67f9fd7ecd”}]}
I’m testing on bluestacks emulator right now, that should usually be able to show notifications,
please help!
Success = 1, looks like the message is getting delivered successfully.
Bug on the android side. does android dev has added proper code for receive notification?
Are you able to run the app on a test device and see if the message is being delivered?
Change data to notification, and it will work
if($device_type == “Android”){
$fields = array(
‘to’ => $registatoin_ids,
‘notification’ => $notification
);
}
How to send at a time morethen 100 device to notification
You can pass multiple device tokens like below.
$registration_ids = array(‘Device Token 1’, ‘Device Token 2’);
Thank you Vijay Poshiya, Your article is very helpful, good luck always .., can I also send to multiple devices? how is the implementation?
You can pass multiple device tokens like below.
$registration_ids = array(‘Device Token 1’, ‘Device Token 2’);
Thank You!
can i send this push notification to >1000 devices
Yes, You can send this notification to 1000+ devices.
Hi Vijay,
Can you please guide on how I can send Device Token from android app to mysql database.
Does this work in my local (i mean i have not uploaded on playstore) ?
If so then it is not working for me. I will be wrong some where .
I did (created fcm.php , index.php) as you described .
Thank you
how to send group notification using php
multiple device notification added index.php or fcm.php?
Field “to” must be a JSON string: [“‘eTc6DSWqTr-
Can i send $notification[‘click_action’] = ‘FLUTTER_NOTIFICATION_CLICK’;?
Great article! Learned a lot!
To send push notification i faced this issue. How can I fix it?
{“multicast_id”:1717314576814712738,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”MismatchSenderId”}]}
Wrong code it is not working in laravel .
The request was missing an Authentication Key. Please, refer to section “Authentication” of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.
Error 401
awesome tutorial, the above code saved my many frustrating hours..
Thank You! 🙂
can i send notification to web browser using it?
No, You can not send notification to web browser
Are there any limitations to send the notifications at one instance?
no limit
Under a project. Need to know any option to create an android app and get google-services.json file from PHP?
Thanks so much. I can’t get a notification with sound! although the android default has a sound. Can you explain how to activate sound?
Hello
How do I get a Device Token(s)?
Thx!
regarding, get device token, i will post separate post asap.
Thank you!
how to send push notification to all device without knowing any Device Tokens
Without device token we can not send push notification.
Hi, Vijay I have this resault and I dont know where is the mistake: {“multicast_id”:2245946065295581409,”success”:0,”failure”:1,”canonical_ids”:0,”results”:[{“error”:”InvalidRegistration”}]}
Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with Firebase Notifications.
Hi if i run a command from terminal to get the notification i am able to get the notification on my device. but if it try your code to get notification it is not working if though i am getting success 1. What might be the issue.?
sir, your coding working properly, i want to ask u can we send notification to multiple android devices?
Yes, we can send push notification to multiple devices like this
‘registration_ids’ => array(“device_token_1”, “device_token_2”)
Hi, I got success “success”:1,”failure”:0 , but notification not get in mobile also the firebase cloud message section too
i can received the notification , but without any sound, any idea why?
Did you use the notificaiton array like this? :
“notification”:{
“body”:”PHP Advices”,
“title”:”Push notification using php”,
“sound”:”default”
}
I have checked and working fine for me.
In 2020 I used the following syntax:
$fields = array(
‘registration_ids’ => $telefono,
‘data’=> $message
);
I received the push, both in the background and in the front.
But now it doesn’t work.
If I change ‘data’ to ‘notification’ and I receive the push only in bacground, in front it does nothing, and if I click it in the notification it takes me to the app but it does not execute the ‘push.on (‘notification’, function (data) {…}’.
¿¿??
Thanks
I got it with Android Studio 4.1.2. and using:
$fields = array(
‘registration_ids’ => $telefono,
‘data’=> $message
);
But with Android Studio Bumblebee 2021.1.1 do not work.
Thanks
Is there a way i can schedule notification from Google’s End?
I don’t want to use cron etc.