Skip to content

Instantly share code, notes, and snippets.

@thatisusama
Created April 14, 2017 11:49
Show Gist options
  • Save thatisusama/9c9462fc41a49b30e759b04ea37a6d93 to your computer and use it in GitHub Desktop.
Save thatisusama/9c9462fc41a49b30e759b04ea37a6d93 to your computer and use it in GitHub Desktop.
FCM php sample code
// function creation
public function sendMessage($data,$target)
{
//FCM api URL
$url = 'https://fcm.googleapis.com/fcm/send';
//api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
$server_key = 'Your-Server-Key';
$fields = array();
$fields['data'] = $data;
if(is_array($target)){
$fields['registration_ids'] = $target;
}else{
$fields['to'] = $target;
}
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$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));
}
curl_close($ch);
//return $result;
}
}
// function calling example
if($result == true) {
// this is my custom fuction which is getting fcms ids from db and storing into array named target you can use your logic to get fcm ids from database
$res = $db->getFCMbyConnections('Variable', 'Table_Name');
$target = array();
if(mysql_num_rows($res) > 0 ){
while ($row = mysql_fetch_assoc($res)) {
$target[] = $row["FCM"];
}
}
$data = array('key'=>'Value','key2'=>'value2');
$db->sendMessage($data, $target);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment