Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active April 7, 2016 11:22
Show Gist options
  • Save kristopherjohnson/af6b45dcd3bf1df0f72a to your computer and use it in GitHub Desktop.
Save kristopherjohnson/af6b45dcd3bf1df0f72a to your computer and use it in GitHub Desktop.
Simple PHP script to send a push notification to an Android device via GCM
#!/usr/bin/php
<?php
// This script sends a Google Cloud Messaging message to an Android smartphone.
// It is intended to mimic what the server does.
//
// To use it, set the API access key and the registration ID ("device token")
// for the target device(s).
//
// Credit: http://stackoverflow.com/questions/22168819/android-test-push-notification-online
// API access key from Google API Console <https://console.developers.google.com/project>
define( 'API_ACCESS_KEY', 'PASTE-API-KEY-HERE' );
// Registration ID obtained by registering client with GCM server
$registrationIds = array("PASTE-REGISTRATION-ID-HERE" );
// prep the bundle
$msg = array
(
'alertText' => 'This is the alert text',
"otherInfo" => 'This is other text',
"collapse_key" => "do_not_collapse"
);
$fields = array
(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array
(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/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 );
echo $result;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment