Android Question Send Google Cloud Message With PHP

SpinBower

Member
Licensed User
Longtime User
Hi, I have an app that uses the GCM framework and for it to work the way I want, I want to use my website to send notifications via php scripts. Could someone direct me to a script to do this? I've seen others but they don't include the board file url so I was thinking they wouldn't work and they don't. Could someone help?
 
Last edited:

aaronk

Well-Known Member
Licensed User
Longtime User
You may need to tweak a few things but this should help you out.. I have used this and it works (after doing some tweaks)

Start off using Erels tutorial to register the device to the GCM server:
http://www.b4x.com/android/forum/threads/android-push-notification-gcm-framework-and-tutorial.19226/

Then follow this from around step 4 (which will help you send the message to devices using PHP):
http://androidexample.com/Android_P...php?view=article_discription&aid=119&aaid=139

There might be other ways in doing this, but I know a little while back I used this and it worked fine.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
PHP:
function send_gcm_notify($Ticker, $message) {
	global $db, $file_handle;
	
	$url = 'https://android.googleapis.com/gcm/send';

	$dbname  = "xxxx";	$dbuser  = "xxxx";	$dbpass  = "xxxx";	$dbhost  = "xxxxx";
	$db2=new Database($dbhost,$dbname,$dbuser,$dbpass);

  $regIDs = array();
  $sql = "SELECT * FROM c2dm WHERE name<>'' AND notification=1;";
	$queue = $db->getRows($sql);
	if (sizeof($queue) > 0){
		foreach($queue AS $q){
			$regIDs[] = $q["id"];
		}
	}
	$queue = $db->getRow($sql);
  $fields = array(
      'registration_ids'  => $regIDs,
      'data'              => array( "message" => $message, 'tickerText' => $Ticker, 'contentTitle' => "Title", "contentText" => "ContentText" ),
  );

  $headers = array(
      'Authorization: key=' . "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
      'Content-Type: application/json'
  );

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  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);
	fwrite($file_handle, date("d.m.Y H:i:s", time()).": Curl-Result: ".$result."\r\n");
  if ($result === FALSE) {
		fwrite($file_handle, date("d.m.Y H:i:s", time()).": Error: ".curl_error($ch)."\r\n");
    //die('Problem occurred: ' . curl_error($ch));
  }
  curl_close($ch);
}
 
Upvote 0

mitobobo

Member
Licensed User
Longtime User
I do this way(you should adapt it to your needs):

GCMSEND1.PHP:

B4X:
<?php
include_once './gcmsend.php';
$message = "test";
$regId = "123456789012365sdds";

$gcm = new GCM();
    $registatoin_ids = array($regId);
    $message = array("data" => $message);
    $result = $gcm->send_notification($registatoin_ids, $message);

?>

GCMSEND.PHP:

B4X:
<?php
class GCM {
    //put your code here
    // constructor
    function __construct() {
    
    }
    /**
    * Sending Push Notification
    */
    public function send_notification($registatoin_ids, $message) {
        // Set POST variables
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registatoin_ids,
            'data' => $message,
        );
        $headers = array(
            'Authorization: key=AAAAA_BBBBB_CCC512', // Auth key
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        // Close connection
        curl_close($ch);
        echo $result;
    }
}
?>
 
Upvote 0

SpinBower

Member
Licensed User
Longtime User
PHP:
function send_gcm_notify($Ticker, $message) {
    global $db, $file_handle;
   
    $url = 'https://android.googleapis.com/gcm/send';

    $dbname  = "xxxx";    $dbuser  = "xxxx";    $dbpass  = "xxxx";    $dbhost  = "xxxxx";
    $db2=new Database($dbhost,$dbname,$dbuser,$dbpass);

  $regIDs = array();
  $sql = "SELECT * FROM c2dm WHERE name<>'' AND notification=1;";
    $queue = $db->getRows($sql);
    if (sizeof($queue) > 0){
        foreach($queue AS $q){
            $regIDs[] = $q["id"];
        }
    }
    $queue = $db->getRow($sql);
  $fields = array(
      'registration_ids'  => $regIDs,
      'data'              => array( "message" => $message, 'tickerText' => $Ticker, 'contentTitle' => "Title", "contentText" => "ContentText" ),
  );

  $headers = array(
      'Authorization: key=' . "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
      'Content-Type: application/json'
  );

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  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);
    fwrite($file_handle, date("d.m.Y H:i:s", time()).": Curl-Result: ".$result."\r\n");
  if ($result === FALSE) {
        fwrite($file_handle, date("d.m.Y H:i:s", time()).": Error: ".curl_error($ch)."\r\n");
    //die('Problem occurred: ' . curl_error($ch));
  }
  curl_close($ch);
}

When I try to run this with all of the fields corrected, I get this: Fatal error: Class 'Database' not found in /home/masonmilby/public_html/gcmsend.php on line 8
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
use your own database-class

But i can give you the class i´m using...

B4X:
<?php
/*
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
####                                       ####
####    Gopi - M                           ####
####    Date   : 31-Dec-2008               ####
####                                       ####
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
*/

class Database{
	/*
	*	Class Members:
	*	$db - Data base connection
	*	$dbname - Database name
	*	$rowColl - rows collection
	*	$host - server path
	*	$user -  User name
	*	$password  - Password
	*/

	public $db, $dbname, $rowCol;
	public $host, $user, $password;

	/*
	*   Initialize the class members
	*
	*   $t_host - House server
	*   $t_dbname - Databse Name
	*   $t_user - User Name
	*   $t_pass - User Password
	*/
	
	function __construct($t_host, $t_dbname, $t_user, $t_pass){
		$this->db = false;
		$this->dbname = $t_dbname;
		$this->host = $t_host;
		$this->user = $t_user;
		$this->password = $t_pass;
	}

	/*
	*   Make a connection for default settings
	*        and
	*   Select the Database
	*/

	function connect(){
		$this->db = mysql_connect($this->host, $this->user, $this->password) or die("Database Connection Access Error..".mysql_error());
		if($this->db == false) return false;
		mysql_select_db($this->dbname, $this->db);
	}

	/*
	*   Connection Closed
	*/

	function close()	{
		mysql_close($this->db) or die ("Database Access Error...".mysql_error());
		$this->db = false;
	}

	/*
	*   variable:
	*       $sql - (string ) Select query
	*
	*        - if data exist this function return data in associate array format
      *        - else reutrn empty array
	*/
	
	function getRows($sql){
		if(!is_resource($this->db)) $this->connect();			
		//echo $sql."<br>";
		$res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
		
		$rows  = array();
		
		while ($row = mysql_fetch_array($res)){
			$rows[] = $row;
		}
		return $rows;
	}
	
	function getRow($sql){
		if(!is_resource($this->db)) $this->connect();			
		//echo $sql."<br>";
		$res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
		return mysql_fetch_array($res);
	}

	function qry($sql){
		if(!is_resource($this->db)) $this->connect();			
		//echo $sql."<br>";
		$res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
		return $res;
	}

	function escape($string){
		if(!is_resource($this->db)) $this->connect();			
		//echo $string."<br>";
		$res = mysql_real_escape_string($string);
		return $res;
	}
	/*
	*   variable:
	*       $sql - (string) Insert query
	*
	*/

	function putRows($sql){
		if(!is_resource($this->db)) $this->connect();
		mysql_query($sql,$this->db) or die("Qry : " . $sql . "Insertion/Updation Error...." . mysql_error());
	}
}
?>
 
Upvote 0

SpinBower

Member
Licensed User
Longtime User
use your own database-class

But i can give you the class i´m using...

B4X:
<?php
/*
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
####                                       ####
####    Gopi - M                           ####
####    Date   : 31-Dec-2008               ####
####                                       ####
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
*/

class Database{
    /*
    *    Class Members:
    *    $db - Data base connection
    *    $dbname - Database name
    *    $rowColl - rows collection
    *    $host - server path
    *    $user -  User name
    *    $password  - Password
    */

    public $db, $dbname, $rowCol;
    public $host, $user, $password;

    /*
    *   Initialize the class members
    *
    *   $t_host - House server
    *   $t_dbname - Databse Name
    *   $t_user - User Name
    *   $t_pass - User Password
    */
   
    function __construct($t_host, $t_dbname, $t_user, $t_pass){
        $this->db = false;
        $this->dbname = $t_dbname;
        $this->host = $t_host;
        $this->user = $t_user;
        $this->password = $t_pass;
    }

    /*
    *   Make a connection for default settings
    *        and
    *   Select the Database
    */

    function connect(){
        $this->db = mysql_connect($this->host, $this->user, $this->password) or die("Database Connection Access Error..".mysql_error());
        if($this->db == false) return false;
        mysql_select_db($this->dbname, $this->db);
    }

    /*
    *   Connection Closed
    */

    function close()    {
        mysql_close($this->db) or die ("Database Access Error...".mysql_error());
        $this->db = false;
    }

    /*
    *   variable:
    *       $sql - (string ) Select query
    *
    *        - if data exist this function return data in associate array format
      *        - else reutrn empty array
    */
   
    function getRows($sql){
        if(!is_resource($this->db)) $this->connect();           
        //echo $sql."<br>";
        $res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
       
        $rows  = array();
       
        while ($row = mysql_fetch_array($res)){
            $rows[] = $row;
        }
        return $rows;
    }
   
    function getRow($sql){
        if(!is_resource($this->db)) $this->connect();           
        //echo $sql."<br>";
        $res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
        return mysql_fetch_array($res);
    }

    function qry($sql){
        if(!is_resource($this->db)) $this->connect();           
        //echo $sql."<br>";
        $res = mysql_query($sql) or die("Error : ".mysql_error()."<br>SQL: ".$sql);
        return $res;
    }

    function escape($string){
        if(!is_resource($this->db)) $this->connect();           
        //echo $string."<br>";
        $res = mysql_real_escape_string($string);
        return $res;
    }
    /*
    *   variable:
    *       $sql - (string) Insert query
    *
    */

    function putRows($sql){
        if(!is_resource($this->db)) $this->connect();
        mysql_query($sql,$this->db) or die("Qry : " . $sql . "Insertion/Updation Error...." . mysql_error());
    }
}
?>

So I made a class and I need help on the auth key. For this field do I need a browser key or server key?
'Authorization: key=' . "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
 
Upvote 0
Top