Firebase Cloud Messaging (FCM) Server Side Implementation. (FCM PHP Backend)

In my last post I wrote about FCM Setup in Android, in this post I includes the server side (PHP) implementation to send message notification from the backend server to the Android device.

In this example I am not using all the properties of sending message from server. For a complete list of targets,options and payloads available to send message from server refer this link.

Here are some of the basic properties required to the send downstream messages.

  • to – Type String – (Optional) [Recipient of a message]
    The value must be a single registration token, notification key, or topic. Do not set this field when sending to multiple topics
  • registration_ids – Type String array – (Optional) [Recipients of a message]
    Multiple registration tokens, min 1 max 1000.
  • priority– Type String – (Optional) [ default normal]
    Allowed values normal and high.

    Normal priority optimizes the client app’s battery consumption and the app may receive the message with unspecified delay.

    High priority sends the message immediately, and the app can wake a sleeping device and open a network connection to the server.

  • delay_while_idle – Type boolean – (Optional) [default value false]
    true indicates that the message should not be sent until the device becomes active.
  • time_to_live – Type JSON number – (Optional) [default value 4 week maximum 4 week]
    This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline
  • data – Type JSON Object
    Specifies the custom key-value pairs of the message’s payload.
    eg. {“post_id”:”1234″,”post_title”:”A Blog Post Title”}

    In Android you can receive it in onMessageReceived() as Map data…

We direct all the HTTP requests to

OK Lets start coding… For easy implementation I created a function named sendMessage with two parameters data and target. here is the function.

Pass Array as the data parameter and pass String or Array as the target parameter. To send message to multiple ids use Array as the target parameter or use String if send to single id or a Topic. All other things are well commented in the function. Let me know if you have any trouble.

In the sendMessage function replace PASTE_YOUR_SERVER_KEY_HERE with your secret Server Key. To get the Server Key …

1. Go to Firebase Console
2. Select Your Project … then click on the gear icon next to project name and click on Project settings then move on to CLOUD MESSAGING tab.





39 thoughts on “Firebase Cloud Messaging (FCM) Server Side Implementation. (FCM PHP Backend)

    1. For icon you can try the optional parameter ‘icon’. (Indicates notification icon. Set value to ‘myicon’ for drawable resource myicon.) In my first test it isn’t worked. If not working for you better notify in ‘onMessageReceived’ using custom code, in that case you can use any icon as you wish.

    1. Ok, I’ve figured out. I had syntax error in $data array.
      But still got a little problem, script does nothing (result is a blank page) because I don’t know where to get token to $target so my $target is empty.
      I’d like to send notification to all devices. I’ve implemented FCM into my android app as you explained in your previous tutorial.

      1. assign token you received in onTokenRefresh to the $target variable. You can use single or multiple tokens. in case of multiple token assign an index array to target.

  1. Hello sab,

    i have try this code, but my devices don’t receive notify/push 🙁

    If i send notify with Firebase Console i receive it, but with this script no.. why?

    Help me please :\

    P.s.: I have only change $fields array with —>

    $fields = array(
    ‘registration_ids’ => $target, //in this case $target is an array of tokens
    ‘priority’ => “high”,
    ‘notification’ => array (“title” => $title, “body” => $message,
    ‘data’ => array (“message” => $message, “image” => $img_url)

    And on function parameters pass ($target, $title, $message, $img_url) where have set $img_url to “”.

    Is this my problem??

    1. May be you are missing something. I am using the same code in my recent projects and all works well…. echo the $result variable and check what it returns… also double check the $server_key.

      1. $server_key is right. I have try to echo $result and it print this error:


        But registration id that i pass to $target is right.. so how fix this error?

        Help me please 🙁

        1. The response InvalidRegistration indicates the registration id is wrong (The id you get from app)… Are you saving the registration id to database?

          1. Yes, i have registration ids into Database, but i have also control token that create method on app with token that i have into Database, and are equals..

            So, why ids are wrong?

  2. Do you know which is the best approach to manage the tokens on your server?
    1- How to know which are still valid in order to delete the ones that have been replaced? (My first guess was to send a “heart-beat” but the device can be off at that time).

    2- In relation to question 1, Is there any way you can ask the FCM server to invalidate a token and to generate a new one on the device (this ending up in a call to onTokenRefresh() on the device)?

  3. I have implemented your code but I’m not receiving any oush notifications.
    The $result value is {“multicast_id”:5824575693024907205,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1480970564006919%580ace7df9fd7ecd”}]} which I believe means that the code has worked correctly.

    1. there are 3 type of FCM messages, Notification, Data(payload), and both Notification and Data.
      You didn’t receive any notification, because the message type is data, you should add notification message to trigger the notification on your client app, and make sure your app is in background when you send the message to FCM.

  4. I have same issue like others, I don’t get any notification in my device using PHP code, If I sent it through console then I got the notification.

    My result also display the success 1, Can anyone help me?
    My return result :-

    1. You can try this, it worked for me after series of troubleshooting:

      static function sendMessage($message, $target, $title = ‘App Name’){
      $url = ‘’;

      $fields = array();
      $fields[‘priority’] = “high”;
      $fields[‘notification’] = [‘title’ => $title, ‘body’ => $message, ‘data’ => [‘message’ => $message]];
      if (is_array($target)){
      $fields[‘registration_ids’] = $target;
      } else{
      $fields[‘to’] = $target;

      $headers = array(
      ‘Authorization:key=’ . FIREBASE_SERVER_KEY

      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
      $result = curl_exec($ch);
      if ($result === FALSE) {
      die(‘FCM Send Error: ‘ . curl_error($ch));
      return $result;

  5. my code was woking good but after i have change target id it gives “NotRegistered” as an error but i can receive message from firebase console please help

  6. I used same code and its working fine on development server but once i moved on live server(ssl enabled) its given error:
    Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.
    Error 401

  7. Sometimes there is a delay in delivering message to client , I set priority: “high” but delay is between 10 min – 1 s .
    Why is the message not be delivered immediately?

  8. I want the FCM PHP web server to be able to receive message from the Android app. May I know how to do it?

    Thanks in advance

  9. If anyone gets the problem where they see the result as successful (echo result and you should get something like {“multicast_id”:someSeriesOfNumbers,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”SomeMessageID”})

    try adding the following somewhere before $ch = curl_init(); and commenting out the reference to $fields[‘data’]

    $notif = array();
    $notif[‘title’] = “My Title”;
    $notif[‘body’] = “This is the body of the notification”;
    $fields[‘notification’] = $notif;

  10. Hello. My problem is my notifications work fine when I send it from local system. but when I host the project to live server it gives the exception
    “The remote name could not be resolved: ‘'”

    Can you resolve ?

  11. I want to send notification to android device and want use time limit. that’s why i provided tag “time_to_live”:”10s” but it is not working.

    can anyone will help me.

    Thank You

  12. Hi,

    i want to remove firebase id’s from my database if device id or firebase id not registered then how can i do?

    thanks in advance

Leave a Reply

Your email address will not be published. Required fields are marked *

twenty − 9 =