Skip to content

Instantly share code, notes, and snippets.

@pratikbutani
Created October 24, 2018 11:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save pratikbutani/0105fd8cb7678f3e4b7fef2cb313db0a to your computer and use it in GitHub Desktop.
Save pratikbutani/0105fd8cb7678f3e4b7fef2cb313db0a to your computer and use it in GitHub Desktop.
Send Firebase Notification to more than 1000 users at a time from PHP
<?php
/**
* Created By : Pratik Butani
* Created Date : 24/10/2018
*/
// Database Connection
include "conn.php";
// Get Records from Table
$sql = "SELECT * from fcm";
// Check Results
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row in Array
$array = [];
while($row = mysqli_fetch_assoc($result)) {
$array[] = $row["fcm_token"];
}
// Chunk of Array with 999 Records, I have not taken risk for 1000 users :D
$final_array = array_chunk($array, 999);
// Loop for Every Sub Array and Send to FCM Server
foreach($final_array as $array_of_chunk) {
#API access key from Google API's Console
# Kindly Replace it with Your API key and Token
define( 'API_ACCESS_KEY', 'AIzaSyCY6U_vT_bA-J__RuOApClcm7VbFWYuadfa');
$registrationIds = $array_of_chunk;
#prep the bundle
$msg = array
(
'title' => mysqli_real_escape_string($conn, $_POST['title']),
'description' => mysqli_real_escape_string($conn, $_POST['description']),
'url' => mysqli_real_escape_string($conn, $_POST['url']),
'admin' => mysqli_real_escape_string($conn, $_POST['admin'])
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $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, 'https://fcm.googleapis.com/fcm/send' );
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 );
}
$result_final = array("result" => true, "message" => "Data Fetch Successfully.");
echo $result_final;
} else {
$result_final = array("result" => false, "message" => "Error in Fetching Data.");
echo json_encode($result_final);
}
?>
@prashant202
Copy link

not working

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