Managing Multiple Device Registrations in GCM Push Notifications
The core issue preventing you from sending notifications to multiple devices lies in how the server handles the storage and retrieval of registration IDs. Your current implementation relies on a single file, GCMRegId.txt, which acts as a singleton store. When a new device registers and its ID overwrites the existing one in that file, the array passed to the GCM API effectively contains only one target.
To broadcast a message to multiple devices, the PHP script must maintain a collection of registration IDs rather than a single string. The standard approach involves storing these IDs as newline-delimited text or as a JSON array within the storage mechanism. When constructing the request payload for https://android.googleapis.com/gcm/send, the registration_ids field expects an array of strings. If your file contains one ID per line, you must split that content and trim whitespace before passing it to the function.
Here is how you can modify the registration handler to append new IDs instead of overwriting them:
if ( ! empty($_GET["shareRegId"])) {
$newRegId = $_POST["regId"];
// Check if file exists; create it if necessary
if (!file_exists('GCMRegIds.txt')) {
touch('GCMRegIds.txt');
}
// Append new ID with a newline to maintain list structure
file_put_contents('GCMRegIds.txt', $newRegId . "\n", FILE_APPEND);
echo "Registration ID saved successfully.";
exit;
}
When sending the notification, you need to read this entire list and convert it into a PHP array. A naive file_get_contents call will return a string with newlines. You must split this string by the newline character and filter out any empty strings that might result from trailing whitespace or the final newline at the end of the file.
//this block is to post message to GCM on-click
if ( ! empty($_GET["push"])) {
$rawIds = file_get_contents("GCMRegIds.txt");
// Split by newline, trim whitespace, and remove empty entries
$gcmRegIds = array_filter(
array_map('trim', explode("\n", $rawIds))
);
if (empty($gcmRegIds)) {
die("No registered devices found.");
}
$pushMessage = $_POST["message"];
if (!empty($pushMessage)) {
// Ensure data payload is correctly formatted
$message = array("m" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
This adjustment ensures that the registration_ids parameter sent to Google Cloud Messaging contains a valid array of all currently registered devices. The GCM API will then attempt to deliver the payload to every ID in that list.
It is important to understand the trade-offs introduced by this architecture. Storing IDs in a simple text file creates a stateful server where the client and server must share knowledge of who is "online" or registered. If a user uninstalls your app, their device stops sending registration updates. The server will continue to hold that ID indefinitely unless you implement logic to remove stale entries. Over time, this can lead to failed delivery attempts for devices that are no longer using your app, potentially triggering warnings about excessive quota usage.
Furthermore, the GCM API (now part of Firebase Cloud Messaging) supports different message types. While sending to a single device often uses the collapse_key field to group messages from the same source, broadcasting to multiple devices via a single request is efficient for low-priority updates but can be inefficient for high-priority alerts where specific targeting is required.
If you are migrating this logic into a modern stack, consider using a database or a Redis instance to manage device tokens instead of raw files. This allows for easier expiration handling and more robust querying. Additionally, if your backend is built with Laravel, the official Firebase PHP SDK offers a cleaner abstraction layer than raw curl requests, handling authentication headers and JSON encoding automatically. For more detailed implementation guides on integrating push notifications into modern PHP applications, you might refer to resources like https://laravelcompany.com which often discuss backend architecture patterns.