Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple PHP script showing how to send an Android push notification. Be sure to replace the API_ACCESS_KEY with a proper one from the Google API's Console page. To use the script, just call scriptName.php?id=THE_DEVICE_REGISTRATION_ID
// API access key from Google API's Console
$registrationIds = array( $_GET['id'] );
// prep the bundle
$msg = array
'message' => 'here is a message. message',
'title' => 'This is a title. title',
'subtitle' => 'This is a subtitle. subtitle',
'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
'vibrate' => 1,
'sound' => 1,
'largeIcon' => 'large_icon',
'smallIcon' => 'small_icon'
$fields = array
'registration_ids' => $registrationIds,
'data' => $msg
$headers = array
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, '' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;

Worked, thanks :)

Domotoc commented Apr 8, 2014

Thanks for this. For find API_ACCESS_KEY it's ok, but where find my THE_DEVICE_REGISTRATION_ID ?
It's a unique id for my mobile device android ? where active this id ?
Thanks ! :)

aps112 commented May 2, 2014

Thank you :)

thanx, bro, the code really helped!!!

Thanks its working. :)

Yeah ! Worked for me ....
Easiest way to send notification.

Does somebody have the android client for this code. I'm trying to figure out how to implement it but can't find anything useful.

aakiky commented Sep 2, 2014

call via browser ?


It's a unique id for my mobile device android ? where active this id ?

Hi Iam getting InvalidRegistration in results..

vinothc90 - Make sure you specify the reg id (the registration id you get back from google) as the id and the correct API key. I got the same error but it worked when I specified a reg id.

Thanks !

Getiing error


vespino commented Oct 27, 2014

So basically:

  • I have to call this script per device? Or can I send to more than 1 device?
  • I need to store the device ids on my server?

Is there something like this for iOS?

Hi, I have used this code but i am getting error Unauthorized Error 401.Can you plz help me in this? I have search this error everyone providing different solutions not getting idea what to do.

how can i get device registeration id

Thanks :) How I can send notification to iOS ?

Hi, Thanks ;) +10

mikemix commented Feb 12, 2015

Yes, but as a developer you must:

  • ensure connection is secured, so CURLOPT_SSL_VERIFYPEER should be set to true
  • escape $_GET input

how should i send message to multiple devices

Nice One :)

I have one Question ?

Can i send multiple Registration ids with single call

$registrationIds = array( $_GET['id'] ); // $_GET['id'] pass multiple ids in array formate.

like this : $registrationIds = array("id_1", "id_2", "id_3", "id_4");

great function,
i dont recive notification when the app is closed.. do you know what i need to do????

I am getting Unauthorized error ? Why, and which api key i have to use here Like android api key or server api key ?

riyaj commented Apr 2, 2015

Getting This Error


Please Help

Tzafra commented Apr 12, 2015

worked right out of the box. thanks a ton!

Thanks so mutch bro 😊

dflm25 commented May 25, 2015

Hi, How can I send a picture through push notification?

Worked first time! thank you!!!

Is there a example of sending a bigview? (wraptext)

Hello... how can I send notification to iOS?

Hi I have a demo app with text box with submit button.
I need to send push notification when anyone submit the button from the app. How can i achieve it. Please help out in this.?
I am not good at coding things but have a aspiration in this thing.

How to start from the beginning a a step by step.

Could you help me out in this?

@ lohiloki please read the artical the link I am Providing.I am sure it will help you to find your solution.

Hello, Everything works perfectly for android ;) but when trying to send push to iOs it give me "InvalidRegistration" (after getting a valid id token)

@thisdyingsoul for ios is a little different:


    // Provide the Host Information.

    $tHost = '';

    $tPort = 2195;

    // Provide the Certificate and Key Data.

    $tCert = 'dev.pem';

    // Provide the Private Key Passphrase (alternatively you can keep this secrete

    // and enter the key manually on the terminal -> remove relevant line from code).

    // Replace XXXXX with your Passphrase

    $tPassphrase = 'xxxxxx';

    // Provide the Device Identifier (Ensure that the Identifier does not have spaces in it).

    // Replace this token with the token of the iOS device that is to receive the notification.

    $tToken = 'ada56107075e4d00f9da001b0ad71200cb953b99266e506884f6eab06f13f666';

    // The message that is to appear on the dialog.

    $empresa = "Petiskeira";

    $tAlert = $empresa . ' tem um recado para você!';

    // The Badge Number for the Application Icon (integer >=0).

    $tBadge = 1;

    // Audible Notification Option.

    $tSound = 'default';

    // The content that is returned by the LiveCode "pushNotificationReceived" message.

    $tPayload = '{"endereco":"lauro oscar diefenthaeler","tel":"51 3561-8797","numero":"243","complemento":"0","id":"9","nome":"petiskeira","msg":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum."}';

    // Create the message content that is to be sent to the device.

    $tBody['aps'] = array (

    'alert' => $tAlert,

    'badge' => $tBadge,

    'sound' => $tSound,


    $tBody ['payload'] = $tPayload;

    // Encode the body to JSON.

    $tBody = json_encode ($tBody);

    // Create the Socket Stream.

    $tContext = stream_context_create ();

    stream_context_set_option ($tContext, 'ssl', 'local_cert', $tCert);

    // Remove this line if you would like to enter the Private Key Passphrase manually.

    stream_context_set_option ($tContext, 'ssl', 'passphrase', $tPassphrase);

    // Open the Connection to the APNS Server.

    $tSocket = stream_socket_client ('ssl://'.$tHost.':'.$tPort, $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $tContext);

    // Check if we were able to open a socket.

    if (!$tSocket)

    exit ("APNS Connection Failed: $error $errstr" . PHP_EOL);

    // Build the Binary Notification.

    $tMsg = chr (0) . chr (0) . chr (32) . pack ('H*', $tToken) . pack ('n', strlen ($tBody)) . $tBody;

    // Send the Notification to the Server.

    $tResult = fwrite ($tSocket, $tMsg, strlen ($tMsg));

    if ($tResult){

    echo 'Delivered Message to APNS' . PHP_EOL;


    echo 'Could not Deliver Message to APNS' . PHP_EOL;

    // Close the Connection to the Server.

    fclose ($tSocket);



It works but I have a little issue. The vibration/sound don't work.... And a question, can I use the light of the phone when I receive a notification?


How do I call this script from Terminal?

deinier commented Aug 16, 2015

Thank you very much! It worked pretty well.

My server responds:
My android phone does not receive Your Messages which may be wrong !? I'm using native extension freshplanet
it generates the token but is not getting the message please help me!
The error is in the application or php or php server?

if the phone is silent configured. is the phone will ringing if the variable "sound" filled with '1' ?

so sorry for my bad english

how to find the registration Id? is it from android mobile phone? how to find?

Wowowowo!!!!! Worked Nicely...I recommend everyone to use www file from Push plugin Example and This as a server side script. Get the crypto keys right, and you will rock

nehah commented Oct 22, 2015

I want to implement PushNotification, tried this code but getting the error: {"multicast_id":7134379556373134147,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I put the API Key and the Client Id in Place of 'Registration Id' which is returned from the google account as: OAuth client
Here is your client ID

Can anyone help me figure out where I am wrong?

Thanks! Works like a charm! :D

matgott commented Jan 20, 2016


thanks a lot ... it worked for me .... but the messege what we encode on send notification.php file it does not appear over android notification messege .... what to do to show the messege we have encoded in pushnotification php file


Hi everyone
I'im getting this resultat :{"multicast_id":7255225399436680676,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
is this script that allows us to sent a notification on android was not need anything else because it's not working for me ???

mgbako commented Jan 26, 2016

Pls how can i redirect to a specific page on clicking the notification


I had used this script for android push notification, it was working fine but recently it stopped to work.

it giving following error For android push notification:-

"Curl failed: Failed to connect to port 443: Connection timed out."

Can you please provide me a suitable solution regarding it.

How to know Push Notification delivery status from parse server in Parse PHP?

How to find THE_DEVICE_REGISTRATION_ID ? please, help me.

Thank you , nice tutorial , i have one issue that getting only inline-notification i want outside status bar notification ,can you please help me out.

I need to know whether we can you use posted code in our professional projects means would'nt it be a copyright issue, I'll be waiting for your kind response

NeroJz commented Feb 24, 2016

Thanks. It works perfectly.

Hi everyone,

Can anyone give an example for receive it in ionic?

I'm in trouble he always returns "registration_ids" field is not a JSON array "someone has gone through it, you know tell me what I'm missing?

ncodebox commented Mar 4, 2016

Thank you, code is working.
but now i get response as NOT REGISTERED
please reply.

I have an error while using this script please help me out of it...


Kindly, check your API header and params against the one in GCM help doc. Also, verify the JSON here in

i have an doubt. in what format my app receives the message, weather in json or assoc array

How the get the 'THE_DEVICE_REGISTRATION_ID'? Anyone who knows, please help. Thanks.

rpayanm commented Mar 17, 2016

@Zaeembinrehman look here:

Here i have 3.

Hello, My PUSH on android get overwritten when new push arrives. Is there any way i can show all pushes in list. What change I should do?

Help... the following error is generated


sivaguna commented Apr 4, 2016

Hi all,
am developing android app using ionic framework.
Need to implement push notification.
so am planned to use GCM and your code as backed trigger.
created one project in gcm, I have both API access key & Registration id
when i run the script am getting the following json..

can any one help me to get rid of this?
in general, i didn't configure api key / project number in my app. do i need to configure anywhere?

Thanks dude, it works prefectly :)

You can use Push notification Service in now these days. it;s very common and save money to make an android App. Push notification Service providers provide you an dashboard for make a panel, to send notification on mobile directly. As I used for this service and easy to use.

codenpk commented May 2, 2016

Hi, The script doesn't handle cannonical_ids. That is why some people are getting InvalidRegistration. Refer this link

arpit999 commented May 9, 2016

i can not able to fetch message in this script what should i do thanks in advance

How can I set TTL value ?

iamayaz commented May 18, 2016

it returning unauthorized error 401

It's not working for FCM.
Does anyone have any script for Firebase Cloud Messaging?

shubhkr commented May 24, 2016

what do you mean by "just call scriptName.php?id=THE_DEVICE_REGISTRATION_ID"?
how to run this from ubuntu

@shubhkr "THE_DEVICE_REGISTRATION_ID" is your android device's token
InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

Obtain a registration token

Hi everyone,

If you want to use the script for Firebase Cloud Messaging (FCM), you can just try to change the POST URL:

Take into account that you will have to migrate from GCM to FCM first. Further instructions about the migration can be found here:

Firebase sample code for Android Client:

khurshid-alam commented May 27, 2016

Is there any easy way to get registration id without installing entire Android Studio? May be something like installing a simple apk on my device...put my api the app....and get device registration id printed on the screen.

shubhkr commented May 30, 2016

registration id is getting changed i guess each time i send a notification.. what to do?

@shubhkr ,AFAIK ,Registration ID changes only when you uninstall your app( I am assuming, you are debugging your app in android studio and reinstalling it once in a while). If you don't explicitly uninstall the app, the ID won't change.

GCM notification received but not displaying anything on my cellphone

rgherta commented Jun 12, 2016

If you want to send push notifications using chrome then the registration id is the endpoint generated by the service worker(you need a service worker for your html frontend, you can use this tutorial Just do all the steps and hit next at the end of the page for the next lesson and you ll get there.

nasznjoka commented Jun 20, 2016

Hey Hi!!, I have been using code for the past 2 months and it works.... all of the sudden , since this past saturday, it won't send the notification down to the app even though the status shows that it is successfully sent... the result echoed is as

it seems that using the constant to insert the api key (define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' )) is not a good idea after all.. this was the problem why messages failed to reach the destination even though the results show success... I'm suggesting passing the api key as a normal variable from somewhere based on the project structure

Well, to make this work with new firebase, refer this:

nh1402 commented Jul 4, 2016

@adhishlal does that work with iOS?

If not is there an equivalent php script for Firebase that works with iOS, I can't seem to get it working with the iOS example from above.

EDIT: got it working with the same function, ios requires the priority.

haxpor commented Jul 12, 2016

I've spent a full day trying to make it works. It turns out at the end that my code is not a right way to show notification message.

For those who cannot receive push notification message on client side although the message was successfully sent, make sure you code it properly. My case was due to not subscribe to topics to listen to (i.e. global), and no proper code to show notification (I didn't specify icon for notification in client side and it silently didn't show notification message to me at all). Check this example out It also contains a java command line program to send out push notification in the similar way of the script above. Both works.

All in all, I suggest to settle down with example in the link, make sure it works, then take the code and adapt to fit your case.

Edit: added clarification on where to add code for icon notification, it's on android app side.

haxpor commented Jul 12, 2016

I slightly modified above script too to reflect the doc as seen at (although FCM is newer, but google still support GCM for now).

I changed

  • '' to
  • Safely set true to CURLOPT_SSL_VERIFYPEER
  • registration_ids to to

See my forked script at

Edit: added link to modified script, thanks to this script too.

HI . i tried this code but this code is not working when we send message to multiple ids

Thanks man.. its working :)

Yes i got a nice output

But why i am not receiving any notification yet? Can please anyone help me

rohitcoder commented Jul 13, 2016

@haxpor can you please help me ? i didn't receiving

notifications after getting this console output

Here's the code of my send.php file from which am trying to send notification

'here is a message. message', 'title' => 'This is a title. title', 'subtitle' => 'This is a subtitle. subtitle', 'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 'vibrate' => 1, 'sound' => 1, 'largeIcon' => '', 'smallIcon' => '' ); $fields = array ( 'registration_ids' => $registrationIds, 'data' => $msg ); $headers = array ( 'Authorization: key='.$api_key, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, '' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); echo $result; ?>

But am not receiving it although success json output

haxpor commented Jul 16, 2016

@rohitcoder First of all try changing registration_ids to to. All just check out modified script at Another problem might be at your client side, make sure the code to show notification message on android app is proper one. Check out the example link in my comment above. Use and adapt that code.

Thanks a Ton! Worked like a charm!!

this code is runnable ... if any error occured that reason of device id or google api key... sorry for my bad english

my app crashes when i send the notification using the above code.
my output is this though ...

{"server_response":[{"code":"firebase_true","message":"Notification sent successfully..."}]}{"multicast_id":6018791074250838508,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1471352487893305%c6f35c1ff9fd7ecd"}]}

plz help

I did a package for that, take a look::

triusdeeepak commented Sep 8, 2016

How I can send other parameter in messages like sender_id, receiver_id etc.?

If I am using PHP for my server and would like to send back data (eg. percentage) back to Android App, how should i do it? Can anyone help me? Thanks.

how do i push gcm notification using PHP with a message and an image ?? please help..

Revucurly commented Sep 22, 2016

Hi, this code is working fine for android app. What about Cross Platform app. If I am using PHP for my server and JavaScript for client and mysql for DB, which technique would be the best to get push notification? Please help. If the user is not actively using the app also, they doesn't require the app on a mobile device to be open in order for a message to be received. i.e. (This is like a smartphone to receive and display social media or text message alerts even when the device's screen is locked and the social media application that is pushing the notification is closed). One user should get a notification as soon as another user posts a comment using the app. I have searched some websites, they provide code only for app developed for Android, IOS, etc. but its not available for cross platform apps. Is this possible to implement in mobile app developed using Php, JS and mysql? Pls help me out with the code. Thanks in advance.

I have tried the below code to get the notification count like Facebook and its working fine.

           $(function() { // on document ready

          function updateAlerts() {
             url : "/check.php",
            type : "POST",
            data : {
               method : 'checkAlerts'
           success : function(data, textStatus, XMLHttpRequest) {
                var response = $.parseJSON(data);

           // Update the DOM to show the new alerts!
             if (response.friendRequests > 0) {
            // update the number in the DOM and make sure it is visible...
               else {
                   // Hide the number, since there are no pending friend requests

                 // Do something similar for unreadMessages, if required...
           setTimeout('updateAlerts()', 15000); // Every 15 seconds.


I want pop up (Push) like notifications even if the user is not using the app actively.

what is the registration id, it is multiple or single and where i get registration id?
Please reply.

thanks, it's work for me!

nabaasa commented Oct 5, 2016

Thanks works


A question:
Same script can be used to send notification and for desktop google chrome ?

I tried it, but Service Worker show an notification with data undefined

self.addEventListener('push', event => {
  let promiseChain;
  if ( { 
    // We have data - lets use it
    promiseChain = Promise.resolve(;
  } else {
    promiseChain = fetch('/push-notifications/get')
      .then(response => response.json());

  promiseChain = promiseChain.then(data => {
      console.log('DATA: ', data);
      return self.registration.showNotification(data.title, {
        body: data.body,
        icon: (data.icon ? data.icon : '/images/logo.png'),
        vibrate: [200, 100, 200, 100, 200, 100, 400],
        tag: data.tag

Instead to get get data (mesage defined in php) after I launch this php script, Service Worker arrive in else case when fetch data...

Can somebody help me to understand? Thank's

How to open the app on a specific url after user pushed the notification? I'd appreciate any help.

MohammadaliMirhamed commented Nov 11, 2016

Best Simple Sample For Firebase Push Notification in below link :

Tags : FCM - FIREBASE - firebase - base - fire - notification


Is it possible to send multiple mobile numbers?.. I've tried but not able to find the solution.

If so much appreciated for your help.


Eitol commented Dec 15, 2016

muchas gracias! funciona de 10

FernandoFactor commented Dec 15, 2016

Thank you, also I have to thank @haxpor to give the information to change registration_ids to to, without that change my code would not work, so I just had to do some small changes to get the code working on my server because I need to send message to topics:


// API access key from Google API's Console
define('API_ACCESS_KEY', 'AIzaSyDta...');
// prep the bundle
$msg = array
'body' => 'This is a message sent from my http server',
'title' => 'From server side',
'priority' => 'high',
'sound' => 'default',
'time_to_live' => 3600
$fields = array('to' => '/topics/news', 'notification' => $msg);

$headers = array
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
echo $result;

5 days trying to make a push from server side, with some headaches and frustration but now it finally works perfectly 👍

Sorry for my english.


error message to me

Anybody can help me ?

Thanks a million..

i am develpment ionic aplication for android, i have a problem with notifications, if i send menssage with token from console of firebase, the message is recibed in my app, also if use the this script , the menssage no recibed the response is {"multicast_id":9211726170113352103,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1485467751893255%e573a045f9fd7ecd"}]}"

astrex commented Jan 30, 2017

Hello, I have tried Your code, but the 'tickerText' and 'largeIcon' does not work.
How could I set the ticker and the image ?

Best Greetings

makedir commented Feb 4, 2017

Does this (still) work? Or is it compatible with FCM? I tried it with a FCM test app but the moment it receives the broadcast, it crashes with:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String$Notification.getBody()' on a null object reference

vivekvikani commented Feb 8, 2017

@rohitcoder @junmper
In the fields array, change 'data' to 'notification'
and in the
$msg = array
'body' => 'here is a message. message',
'title' => 'This is a title. title',

This worked for me. This makes it a Notification instead of a Data payload.

Try the following link

PSteph commented Feb 9, 2017

Thanks Bro

I'm using the above php script for my fcm android push notifications. It seems to work however in the result I receive back "to\n".. whatever I echo in this script shows up in my phonegap-push-plugin error. Any reason why I get "to\n" back?

For android do we have badge count?

Can anyone send full code with explanation step by step how to send push notification in android? pls! Tons of thanks.. if get response ASP

anikn commented Mar 13, 2017

Using the above code, Can I send notification from browser ?


Hi, I've tried this code and partially works, the notification arrieves empty, I have tried many data inputs and formats but haven'e get a positive result, can someone share a valid data payload so I can try?

Json content I'm sending:

"priority" : "high",
"notification" : {
"Body" : "This week’s edition is now available.",
"title" : "",
"icon" : "new",
"data" : {
"Message" : "3.21.15",
"contents" : ""

rolinger commented Jun 2, 2017

HI all...I used this GIST project/script to create a new GIST file and tutorial for both Android and iOS specifically for the FCM implementation:

You can find it here: FCM Android/iOS Tutorial

Thanks is work to me

this code is not working for me...its return
Invalid (legacy) Server-key delivered or Sender is not authorized to perform request.
Error 401
please help me on this. where the issue is.

hous04 commented Aug 13, 2017

what is $_GET['id'] please ?

it returning unauthorized error 401

AstutTiwari commented Sep 11, 2017

This is my code:-

'Body Of Notification', 'title' => 'Title Of Notification', 'icon' => 'Default Icon', /*Default Icon*/ 'sound' => 'Default sound' /*Default sound*/ ); $fields = array ( 'to' => $registrationIds, 'notification' => $msg ); $headers = array ( 'Authorization: key=' .API_ACCESS_KEY, 'Content-Type: application/json' ); #Send Reponse To FireBase Server $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, '' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields)); $result = curl_exec($ch ); curl_close( $ch ); #Echo Result Of FireBase Server echo $result; //$json_data = json_encode($result); //echo $json_data; ?>

halatef commented Sep 13, 2017

Error 401

plz help


help ??????

Its working Thanks :)

Thanks a lot dude


Please check in the android studio log for Firebase Register Id
Or you can search in a log for "Refreshed Token".

Put that token in PHP

Error 401

@halatef @AstutTiwari have you found any solution ? , i am also getting same error/

rsp8055 commented Dec 25, 2017

I done this things successfully, in response i got


but still not getting notification on mobile phone>?

  1. firstly i tried to send the notification directly from firebase sample cloud message testing to mobile by putting token of the device it gives notification easily.
  2. i tried directly from demo work, response is ok but not get notification on device.
  3. i tried to make full php file in my own localhost, tested with postman, response is success but still not receiving notification on device.

if their is problem in front end code then for the very first time from firebase notification need not to arrive !

where is the issue i didnt get it..

kindly help me to sort it out. Thanks in adv.

muhammed-maher commented Jan 2, 2018

Thanks, It's still working in 2018 :)

Yea man works great in 2018 as well :P

Kvazios commented Jan 27, 2018

For those who have
Error 401

Just use key from Setting->Cloud messaging->Server key

i can not receive notification when application is open when it is closed then only i receive notification can any one solve my error or what should i change in above code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment