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;
}

30 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
  2. Get your favourite garden sheds and all the household items in Auckland Newzealand on a single click. We provide you quality products and Bed with mattress nz lowest price.

    ReplyDelete
  3. Crypto-currency as a modern form of the digital asset has received a worldwide acclaim for easy and faster financial transactions and its awareness among people have allowed them to take more interest in the field thus opening up new and advanced ways of making payments. Crypto.com Referral Code with the growing demand of this global phenomenon more,new traders and business owners are now willing to invest in this currency platform despite its fluctuating prices however it is quite difficult to choose the best one when the market is full. In the list of crypto-currencies bit-coins is one of the oldest and more popular Crypto.com Referral Code for the last few years. It is basically used for trading goods and services and has become the part of the so-called computerized block-chain system allowing anyone to use it thus increasing the craze among the public, Crypto.com Referral Code.

    Common people who are willing to purchase BTC can use an online wallet system for buying them safely in exchange of cash or credit cards and in a comfortable way from the thousands of BTC foundations around the world and keep them as assets for the future. Due to its popularity, many corporate investors are now accepting them as cross-border payments and the rise is unstoppable. With the advent of the internet and mobile devices,information gathering has become quite easy as a result the BTC financial transactions are accessible and its price is set in accordance with people’s choice and preferences thus leading to a profitable investment with Crypto.com Referral Code. Recent surveys have also proved that instability is good for BTC exchange as if there is instability and political unrest in the country due to which banks suffer then investing in BTC can surely be a better option. Again bit-coin transaction fees are pretty cheaper and a more convenient technology for making contracts thus attracting the crowd. The BTC can also be converted into different fiat currencies and is used for trading of securities, for land titles, document stamping, public rewards and vice versa.

    Another advanced block-chain project is Ethereumor the ETH which has served much more than just a digital form of crypto-currency Crypto.com Referral Code and its popularity in the last few decades have allowed billions of people to hold wallets for them. With the ease of the online world,the ETH have allowed the retailers and business organizations to accept them for trading purposes, therefore, can serve as the future of the financial system.

    ReplyDelete
  4. Percentage of Internet Users Spending More TimeUsing Each Device: April 2020 II-6Marketing Strategies as Companies Face Economic Hardships II-6Digital and Personalized Experience Gain Prominence II-7Digital Marketing: A Prelude II-7Digital Marketing Channels II-8Exhibit 5: Global Advertising Spending through Platform: 2020 II-9Comparison of Different Advertising Media Based on VariedParameters II-10Digital Marketing Software: An Introduction II-10Key Trends within the Digital Marketing Software Market II-11Various Advertising Media & their Corresponding Benefits II-12Outlook II-12Cloud Computing Dominates the Market II-13By End-Use II-13By Region II-13Market Challenges II-13By Component II-14Competition II-14Exhibit https://buymorefollower.com/buy-instagram-followers-singapore

    ReplyDelete
  5. Crystal online pharmacy is a trusted online drug store with a wide range of products to suit the needs of our clients. Buy Levitra or Vardenafil online Crystal Pharmacy do strive to offer the best service and ship products world wide. All the products listed on our website are Ava in stock. Expect your order to be processed Immediately when you send us your request. We deal with varieties of drugs for our customers satisfaction. We cross barriers with our products and struggle hard to meet human satisfaction. When shopping with us, Be safe and secured and you will realize how swift we are with our services.

    ReplyDelete
  6. Universal Gun sales is a trusted Firearm company base in Los Angeles California USA. It is one of the top Firearms Company in this part of the country. Buy gun case online They do offer the best firearms deal in the USA and to over 25 countries in the world. You can always visit their shop in Los Angeles using the address on their website. Place your order and get served by the best Firearm Company in the planet. Have fun.

    ReplyDelete
  7. 국내 최고 스포츠 토토, 바카라, 우리카지노, 바이너리 옵션 등 검증완료된 메이져 온라인게임 사이트 추천해 드립니다. 공식인증업체, 먹튀 검증 완료된 오라인 사이트만 한 곳에 모아 추천해 드립니다 - 카지노 사이트 - 바카라 사이트 - 안전 놀이터 - 사설 토토 - 카지노 솔루션.

    온라인 카지노, 바카라, 스포츠 토토, 바이너리 옵션 등 온라인 게임의 최신 정보를 제공해 드립니다.

    탑 카지노 게임즈에서는 이용자 분들의 안전한 이용을 약속드리며 100% 신뢰할 수 있고 엄선된 바카라, 스포츠 토토, 온라인 카지노, 바이너리 옵션 게임 사이트 만을 추천해 드립니다.

    ReplyDelete
  8. Oferecemos os melhores serviços para seguidores, curtidas, comentários e visualizações no Instagram. Os serviços são entregues de forma rápida, segura e por um preço honesto e barato.
    Todos os serviços são iniciados de forma automática e você pode fazer um teste grátis de seguidores, curtidas e visualizações no Instagram.

    O Go Followers surgiu em 2015 e durante alguns anos foi o melhor e maior site para comprar seguidores, curtidas e comentários no instagram. Com o passar dos anos evoluímos e em 2021 lançamos um novo site simples e intuitivo para aumentar a experiência dos mais de 150.000 clientes atendidos.

    Nossa ferramenta envia seguidores brasileiros reais e ativos em sua grande maioria para qualquer perfil do Instagram. Escolha o melhor pacote para comprar seguidores instagram de alta qualidade. Você poderá escolher alguns pacotes como seguidores com curtidas, seguidores masculinos, seguidores femininos e seguidores automáticos.
    Todos os pedidos são feitos de forma automática e iniciam em poucos minutos após a compra, tá esperando o que?

    ReplyDelete
  9. I really appreciate this great post that you have provided us. I guarantee this will benefit most people and myself. thank you very much!
    hancom office editor
    time4learning
    how to take a screenshot on samsung tablet
    gogoanime
    how many cm in a meter
    Smartjailmail
    mymedicalme
    roblox error code 524

    ReplyDelete
  10. The majority of golf clubs are sophisticated and modern and have clubhouses that are often with a bar or food outlets inside. This makes them an ideal spot to spend the afternoon by yourself or in the company of others. What better way to brighten up your golf course with an illuminated sign welcoming your guests? The appropriate neon sign will aid in directing guests to the first tee and even to the bar following.https://neonsignshistory.blogspot.com/2021/09/the-golden-age-of-neon.html

    ReplyDelete
  11. LED technology offers more control and flexibility in lighting colors, temperatures and light intensity. Intelligent controls permit lighting systems with LEDs to be set to create a space of peace and tranquility and energizing focus. dim light for presentation software, with the twist of a knob or the click of the keypad. This can help educators to create the ideal environment to learn for a range of activities throughout the day.https://homedesigns.tumblr.com/post/664156305232150528/how-long-do-neon-signs-last

    ReplyDelete
  12. I'm a Certified Social Media Manager, Strategist, Keynote Speaker, Organic Specialist, and Marketer! Blogging services as a creative outlet for me. Running, hiking, and skiing are some of my favourite ways to unwind. My always-present orange glasses, a tribute to my Dutch origin, will help you distinguish me on stage and online.https://neonvibesuk.weebly.com

    ReplyDelete
  13. Utilizing the identical flooring in the different areas or rooms in your home is a simple way to make the room seem larger than it actually is. If you have big open-plan spaces, you can use rug to break the flow and separate the space according to usage. This creates the illusion of distinct dining and sitting spaces that are still able to work as a part of the bigger total. https://www.newtimezone.com/8-neon-wall-art-ideas-your-customers-will-love/

    ReplyDelete
  14. Crie conteúdo que corresponda às palavras de seus concorrentes no topo do ranking. No entanto, você deve fazer seu curto o suficiente para não dominar os leitores. Escreva textos mais longos que podem ser promovidos em outros canais, como redes sociais. Escreva artigos mais longos que irão aumentar a duração das métricas do site https://justpaste.it/3qv5a

    ReplyDelete
  15. 토토사이트 이용을 하다 보면 먹튀 피해에 대한 두려움이 갑자기 생기거나 두려움을 가지고 이용하는 경우가 대반사입니다. 토토마추자는 그러한 두려움을 없애드리기 위해 만들어진 먹튀검증커뮤니티 입니다. 다양한 검증 활동을 통하여 축적된 데이터로 방문해 주시는 모든 회원님들께 무료로 제공해드리고 있습니다. 토토사이트를 이용 하는 회원님들은 메이저사이트를 이용하고 싶은 마음이 크다는 걸 알 수 있습니다. 하지만 해당 토토사이트가 메이저인지 아닌지 확인할 방법은 민간인에게 어려움이 있다는 걸 알 수 있습니다. 이용전 꼭 토토마추자를 통하여 먹튀검증 서비스를 받아보시기 바랍니다안전놀이터.
    국내에 합법 토토사이트는 배트맨토토 에서 발매하는 정식서비스만 이용을 할 수 있으나 배팅금액 제한이 있기에 우후죽순 사설토토사이트가 생겨나고 있습니다. 대체적으로 이를 방지를 하려면 배트맨토토 자체에서 배팅금액 한도를 늘리는 수밖에 없다고 생각됩니다.

    ReplyDelete
  16. Choose a Design
    The design you select for your neon sign ought to be closely structured on a specific theme that you have in mind. So, it may be worth remembering the place your neon signal will grasp as soon as it’s ready; will it go with the relaxation of the room? Will it in shape the theme perfectly?

    You can add a printed heritage to your neon sign with a favored picture or brand, which will supply it a extra private touch. Neon signs and symptoms have also been utilized to synthetic plant life backings and bushes panels, giving your sketch an extra wow appeal. Let them comprehend if you have a specialist history you'll desire to employ.
    https://site-6893872-4145-5097.mystrikingly.com/

    ReplyDelete
  17. You need to moreover deploy it in such a place that is past the obtain of kids and pets. The latter can additionally go thru grave injury if they crash into a neon sign via accident. If you are getting one personalized sign for a bar, installation it in such a manner so that your customers do no longer bump into it or knock it over. Additionally, you moreover get a protective cover.


    https://www.joinarticles.com/how-to-decorate-your-indoors-with-a-neon-sign/

    ReplyDelete
  18. It's essential to keep sensitive conversations using private channels or direct messages. Don't request private or confidential information from the public aspect of your online social network profile and if users do share the information away without being encouraged you should either hide or remove the post. However be sure to let the user know why you've taken this step to protect their privacy.


    https://kwirmedia.com/click-here-2/

    ReplyDelete
  19. Just 99 Web Design offers affordable web design packages for every business, from basic one-page websites to full eCommerce website design services. low cost website designing

    ReplyDelete
  20. Avantajlý ve kaliteli bir dünyaya Superbetin ile giriþ yapýn. süperbetin global ölçekte bahis ve casino hizmet veren bir þirkettir. Kullanýcýlar kaliteli bir hizmet sunmakta. Bahsedeceklerimizden ziyade sizlerde Superbetin giriþ yaparak hizmetleri görebilirsiniz. Makalemizde sizlere Superbetin güvenilir mi? Süperbetin giriþ bilgileri gibi konularda bahsedeceðiz. Ayrýca Superbetin kayýt ol sayesinde özel bonuslara ulaþýn. Sizlerde süperbetin sayesinde avantajlý bir bahis ve casino hizmeti ulaþýn.
    Süperbetin sunduðu hizmetler hakkýnda detaylý bilgiler vereceðiz. Lakin öncelikle sitenin güvenilirliðinden bahsedelim. Ýlk olarak güvenilir olmayan bir site sektörde uzun yýllar hizmet veremez. Dolandýrýcý siteler zaten en fazla 3 ay hizmet verebilmiþtir. Superbetin ise sektörde 10 yýlý aþkýn zamandýr hizmet vermekte. Lisansýný bahis ve casino sektörünün en göze lisans kurumu olan çuraçao hükümetinden almýþtýr. Superbetin oyunlarý bahis ve casino oyunlarýndan saðladýklarý kazançlarýný sorun yaþamadan çekebilmekte.
    Superbetin
    Süperbetin giriþ yaparak sizlerde avantajlý bir bahis ve casino hizmetine ulaþabilirsiniz. Türkiye’deki kullanýcýlar güncel giriþ adresine sayfamýzda her zaman ulaþabilmekte. Avantajlý bir bahis ve casino hizmetine doðru siteyi tercih ederek ulaþýn. Hesabý olmayan kullanýcýlar Süperbetin kayýt iþlemini kolay bir þekilde yapabilmekte. Hiçbir ek belge göndermeden ve ayrýca kimlik bilgisi vermeden kolay bir þekilde hesabýnýzý oluþturun. Ayrýca yeni üyelere özel bonuslar bulunmakta. Deneme bonusu ve hoþgeldin bonusu yeni üyelere özeldir.
    Süperbetin bahis bölümünde geniþ bir bahis bülteni canlý olarak iddaa oynayabilirsiniz. Ayrýca tek maç üzerinden canlý bahisler oynanabilmekte. Binlere farklý müsabakaya yüksek oranlardan canlý bahis oynayabileceðiniz bir hizmet sizleri beklemekte. Sadece spor bahisleri de deðil. E-sports bahisleri, sanal bahisleri gibi farklý bahis seçenekleri de bulunmakta.
    Superbetin sayesinde gerçek bir casino hizmetine de ulaþabilirsiniz. Gerçek casino salonlarýndan canlý kurpiyerlerin sunumlarýyla 4K görüntü kalitesi üzerinden hizmet alýn. Canlý casino oyunlarý ve binlerce farklý slot oyunlarý sizleri beklemekte.
    Süperbetin bahis ve casino oyunlarýndan saðladýðýnýz kazançlarýnýzý sorun yaþamadan çekebilirsiniz. Sonuç olarak istediðiniz finansal yöntem üzerinden para yatýrma ve çekme iþlemlerinizi kolay bir þekilde yapýn.
    Sizlerde Süperbetin giriþ yaparak avantajlý bahis ve casino dünyasýna giriþ yapabilirsiniz.
    Süperbetin kullanýcýlarý para yatýrma ve çekme iþlemlerinizi yapabilirsiniz. Sonuç olarak BTC, usdt gibi coinler üzerinden finansal iþlem sunan sitelerden birisidir.
    Geniþ bir iddaa bülteni üzerinden binlerce farklý müsabakaya ayrýca yüksek oranlardan canlý iddaa oynayýn.
    Gerçek casino salonlarýndan özel olarak bir hizmete ulaþýn. Canlý casino oyunlarý ve slot oyunlarý superbetin dünyasýnda sizleri beklemekte.

    ReplyDelete
  21. Ýnternet üzerinden gerçek bir casino hizmetine ulaþabilirsiniz. Gerçek casino salonlarýndan canlý casino hizmeti veren özel siteleri bulunmakta. Canlý casino siteleri gerçek casino salonlarýndan kullanýcýlarýna gerçek paralar üzerinden casino oyunlarý sunmakta canlı casino. Oyuncular internete baðlý olduklarý her yerden casino oyunlarý oynayabilmekte. Lakin bahsettiðimiz ve bahsedeceðimiz hizmetleri almak için doðru casino siteleri seçmeniz gerekmekte. Doðru siteleri yani güvenilir casino siteleri tercih ederek hem gerçek bir hizmet alýn hem de kazançlarýnýzý sorunsuz bir þekilde çekin.
    Sektörün en gözde casino þirketleri sayfamýzda paylaþýlmakta. Casino siteleri giriþ butonlarý üzerinden sitelere ulaþabilirsiniz. Sizlere sitelerin hizmetleri hakkýnda bilgiler vereceðiz. Sitelerin sunduklarý hizmetleri, bonuslarý ve finansal araçlarý hakkýnda bilgileri sizlere sunacaðýnýz. En iyi canlı casino sayfamýzdan ulaþabilirsiniz.
    Canlý casino
    Paylaþtýðýmýz siteler oyuncularýna gerçek casino salonlarýndan hizmet sunmakta. Oyuncular BlackJack, rulet, poker gibi casino masa oyunlarýný 4K görüntü kalitesi üzerinden gerçek casino salonlarýndan oynamakta. Ayrýca masa oyunlarý yanýnda özel oyunlarda bulunmakta. Canlý olarak sunulan oyunlar 4K görüntü kalitesi üzerinden oyunculara aktarýlmakta. Oyunlarýn sunumlarý canlý kurpiyerlerin sunumlarýyla yapýlmakta. Canlý casino oyunlarý kurpiyerlerin sunumlarýyla oynanmakta. Ayrýca masalarda bulunan herkes sizler gibi gerçek oyuncudur. Asla sitelerde bot hesaplarý bulunmaz. Herkes gerçek oyuncudur. Ayrýca odalarda sohbet bölümleri bulunmakta. Canlý casino
    oyunlarý oynanýrken ayný zamanda diðer oyuncular ile sohbet edebilirsiniz.
    Sitelerde poker, blackjack, rulet gibi onlarca farklý casino masa oyunlarý. Özel olarak hazýrlanan crayz time gibi canlý casino oyunlarý. Aviator, zeplin gibi popüler oyunlar ve binlerce farklý slot oyunlarý bulunmakta. Oyuncular istedikleri oyunlarý istedikleri bet üzerinden oynayabilmekte. Casino siteleri gerçek kumarhanelerdeki oyunlarý ve hatta daha fazlasýný kullanýcýlarýna sunmakta canlı casino.
    Lakin unutmayýn bahsettiðimiz hizmetleri en iyi casino siteleri için geçerli. Her canlý casino sitesi ayný hizmeti vermemekte. Bundan dolayý önünüze gelen her casino sitesi giriþ yapmayýn. Güvenilir casino siteleri giriþ yaparak gerçek bir hizmete ulaþýn.
    Oyuncular casino oyunlarýndan saðladýklarý kazançlarýný sorun yaþamadan çekebilmekte. Ayrýca istedikleri finansal yöntemi kullanarak seçebilmekte. Siteler oyuncular onlarca farklý finansal araç sunmakta. Kullanýcýlar istedikleri yöntemleri kullanarak para yatýrma ve çekme iþlemlerini kolay bir þekilde canlı casino yapabilmekte.
    Casino siteleri onlarca farklý bonus da vermekte. Yeni kayýt olan kullanýcýlar deneme bonusu ve free spin alarak bedava casino oyunlarý oynama fýrsatý yakalamakta. Ýlk yatýrýmlarýna özel casino hoþgeldin bonusu. Her yatýrýmlarýna özel casino yatýrým bonusu. Þansýz günlerinde ise casino kayýp bonusu alabilmekte. Ayrýca bahsettiðimiz bonuslar dýþýnda farklý casino bonuslarý da bulunmakta canlı casino.
    Deneme bonusu veren casino siteleri sayesinde kayýt olarak yatýrým yapamadan bedava casino oyunlarý oynayabilirsiniz. Siteler yeni üyelerine özel olarak bedava bonus vermekte.
    Bonusu alan kullanýcýlar bedava bir þekilde casino oyunlarý oynayarak ayrýca kazançlarýnýzý çekebilirsiniz.
    Güvenilir canlý casino siteleri sayesinde avantajlý bir hizmete ulaþýn.

    ReplyDelete