PART II: How to implement GCM PhP Push Server for android

In PART I: How to implement GCM PhP Push Server for android, I have concluded with a function to send a push notification to a single device.
This part only describes the function that may be used to send to multiple devices the same push message.

Batch push is very useful for many applications that require the delivery of certain messages to multiple uses. With the introduction of GCM, there is no more need to find hacks in order to get a decent delivery speed for your push message. I was previously able to achieve speeds of 6 seconds per 10k devices, which is relatively fast when compared to sending a single request for each of these devices.

Anyway, with the new GCM, sending to multiple devices is a piece of cake. Just prepare your tokens in an array and use the following function. Keep in mind that you can specify up to 1000 receiver in one request: That is your limit now. For the sake of completeness, pushing to 10k (10 thousand) devices would require now 10 requests which would take on an average 10Mb connection less than a second. Here is the code:

function sendMessageToPhones($deviceTokens, $collapseKey, $messageText, $yourKey)
{
    $headers = array('Authorization:key=' . $yourKey,
            'Content-Type:application/json');
    $data = array('message' => $messageText);
    $data = array(
        "registration_ids" => $deviceTokens,
        "collapse_key" => (string)$collapseKey,
        "data" => $data);
    $data_string = json_encode($data);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, "https://android.googleapis.com/gcm/send");
    if ($headers)
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

    $response = curl_exec($ch);
    echo "\n";
    echo "RESPONSE LENGTH: " . strlen($response) . "\n";
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (curl_errno($ch))
    {
        //request failed
        return false; //probably you want to return false
    }
    if ($httpCode != 200)
    {
        //request failed
        return false; //probably you want to return false
    }
    curl_close($ch);
    return $response;
}

2 comments:

  1. curl returns Unauthorized Error 401

    ReplyDelete
    Replies
    1. i am also getting the same error please let me know how to solve that problem .

      Delete