Google Cloud Messaging allows you send lightweight messages from the backend server to all the devices whenever there is new data available. This saves lot of user’s battery by avoiding poll request to server for new data. Using GCM you can build powerful multi platform (iOS, Android & Web) apps like real time chat, news feed, cloud storage and lot more. On top of everything, GCM is completely free and there are no limitations.

As parse.com announced their shutdown recently, GCM is the only best option even though it won’t comes with an admin interface. But don’t worry, we’ll build a simple admin panel in this article.

android realtime chat app using gcm php mysql

As this article is pretty lengthy, I have divided it into 3 parts. Each part covers a unique part in building the final realtime chat app.

Part 1: Covers building the REST API for chat app including the GCM server app.

Part 2: Explains integrating GCM into your android app including a test message.

Part 3: Building Simple Realtime Chat App.

1. Google Cloud Messaging

Typically GCM implementation involves three components. Google cloud messaging server, the app server and the client app. We should take care of writing the app server and the client app. In order to make calls from the app server to GCM server, you can follow HTTP or XMPP protocol. HTTP supports downstream (gcm to client) messages only. XMPP supports both downstream and upstream (device to gcm, then from gcm to server) messages.

Below is the pictorial representation of the overall architecture.

android-google-cloud-messaging-architecture

1. First the app connects to GCM server and register itself.

2. Upon successful registration, GCM issues gcm registration token to device. This registration token uniquely identifies each device.

3. The device sends the registration token to our server to store it in MySQL.

4. Whenever app server wants to send push notification, it sends a request to GCM server sending the push message along with the registration token.

5. GCM server identifies the device using the registration token and initiates the push message.

6. The device receives the push messages and further action takes place.

2. Obtaining Google API Key

Google API key is necessary to interact with GCM server. GCM uses this key to identify your server app. Follow the below steps to obtain your API key. Note that the developer console interface is changing more frequently. So, the below steps may vary in future.

1. Goto Google developers console and create a new app. If you have already created one, select the app.

2. Give a name to your new project. Once the project is created, goto project’s dashboard and click on Use Google APIs

3. Under Mobile APIs, click on Cloud Messaging for Android and enable the API by clicking on top enable API button.

4. Once enabled, click on Credentials on the left. You will be asked to create new credentials by showing multiple options. Choose API Key and then Server Key.

5. After choosing Server Key, your API key will be displayed on the dashboard. Note down the API key as we need to use it in our PHP project.

3. Building Simple Realtime Chat App

In this article, we are going to learn how to create a simple realtime chat app by using Android, GCM, PHP, MySQL, HTML & CSS. We use HTML & CSS to build the admin panel for the server app.

Below are the screens of the android app.

android-simple-chat-app-using-gcm-php-mysql

And the server app comes with the option of choosing the user(s) / topic and send the push notification.

android-php-mysql-gcm-chat-app-admin-panel

This part of the article involves building the server app including designing the MySQL database, REST API for mobile app and an admin panel to send push notifications. I am using Netbeans IDE to develop the PHP code and WAMP / MAMP server to create the php, mysql environment.

Now let’s start designing the database first.

4. Designing MySQL Database

For this app we need only three tables. users, chat rooms and messages.

users – This table holds the user information like name, email and other profile information along with gcm registration id.

chat_rooms – Contains the chat room information.

messages – Contains the messages sent in the chat rooms.

android-simple-chat-app-mysql-database

Open phpmyadmin and execute the below sql query to create the required database and tables.

CREATE DATABASE gcm_chat;

CREATE TABLE `chat_rooms` (
  `chat_room_id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `messages` (
  `message_id` int(11) NOT NULL,
  `chat_room_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `message` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `gcm_registration_id` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `chat_rooms`
  ADD PRIMARY KEY (`chat_room_id`);

ALTER TABLE `messages`
  ADD PRIMARY KEY (`message_id`),
  ADD KEY `chat_room_id` (`chat_room_id`),
  ADD KEY `user_id` (`user_id`),
  ADD KEY `chat_room_id_2` (`chat_room_id`);

ALTER TABLE `users`
  ADD PRIMARY KEY (`user_id`),
  ADD UNIQUE KEY `email` (`email`);

ALTER TABLE `messages`
  ADD CONSTRAINT `messages_ibfk_3` FOREIGN KEY (`chat_room_id`) REFERENCES `chat_rooms` (`chat_room_id`),
  ADD CONSTRAINT `messages_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

5. Creating PHP REST API

I am using Slim framework to create the REST endpoints. If you are not aware of PHP Slim, refer my previous tutorial REST API for Android app using PHP, Slim and MySQL to understand how easily you can create the REST API endpoints for your android app.

Below is the project structure of the PHP app. You have to make sure that you are following same structure while following the further steps.

gcm-simple-chat-app-php-mysql-project

include – Contains the database classes to perform CRUD operations on the database.

libs – Contains the libraries needed for the app (slim, gcm)

v1 – Root directory of the REST API

index.php, demo.php, styles.css – Required to create the admin interface.

1. Goto your WAMP/MAMP installation location and open the web directory. On windows, it will be c:/wamp/www directory. On Mac, the path will be /Applications/MAMP/htdocs.

2. Inside the web directory (www or htdocs), create a directory named gcm_chat. This will be the root directory of our project.

3. Inside gcm_chat folder, create the remaining directories as shown in the above image. Create folders named include, libs and v1. Inside libs, create another folder named gcm.

4. Download Slim framework and paste it inside libs folder.

5. Create a file named config.php in include. This file contains the app configuration like database credentials, google API Key and other information.

Replace GOOGLE_API_KEY with your API Key which you obtained in 2nd section. Also keep the correct database credentials.

<?php
/**
 * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', 'root');
define('DB_HOST', 'localhost');
define('DB_NAME', 'gcm_chat');

define("GOOGLE_API_KEY", "AIzaSyDKk_Ew7Vi4FZnMzu6GCY5PLb4xZG8muvX");

// push notification flags
define('PUSH_FLAG_CHATROOM', 1);
define('PUSH_FLAG_USER', 2);

?>

6. Create a file named db_connect.php inside include folder. This class takes care of database connection.

<?php

/**
 * Handling database connection
 *
 */
class DbConnect {

    private $conn;

    function __construct() {        
    }

    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect() {
        include_once dirname(__FILE__) . '/config.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        // returing connection resource
        return $this->conn;
    }
}
?>

7. Create another file named db_handler.php inside include folder. This file contains all the necessary functions to interact with database tables.

<?php

/**
 * Class to handle all db operations
 * This class will have CRUD methods for database tables
 *
 * @author Ravi Tamada
 */
class DbHandler {

    private $conn;

    function __construct() {
        require_once dirname(__FILE__) . '/db_connect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    // creating new user if not existed
    public function createUser($name, $email) {
        $response = array();

        // First check if user already existed in db
        if (!$this->isUserExists($email)) {
            // insert query
            $stmt = $this->conn->prepare("INSERT INTO users(name, email) values(?, ?)");
            $stmt->bind_param("ss", $name, $email);

            $result = $stmt->execute();

            $stmt->close();

            // Check for successful insertion
            if ($result) {
                // User successfully inserted
                $response["error"] = false;
                $response["user"] = $this->getUserByEmail($email);
            } else {
                // Failed to create user
                $response["error"] = true;
                $response["message"] = "Oops! An error occurred while registereing";
            }
        } else {
            // User with same email already existed in the db
            $response["error"] = false;
            $response["user"] = $this->getUserByEmail($email);
        }

        return $response;
    }

    // updating user GCM registration ID
    public function updateGcmID($user_id, $gcm_registration_id) {
        $response = array();
        $stmt = $this->conn->prepare("UPDATE users SET gcm_registration_id = ? WHERE user_id = ?");
        $stmt->bind_param("si", $gcm_registration_id, $user_id);

        if ($stmt->execute()) {
            // User successfully updated
            $response["error"] = false;
            $response["message"] = 'GCM registration ID updated successfully';
        } else {
            // Failed to update user
            $response["error"] = true;
            $response["message"] = "Failed to update GCM registration ID";
            $stmt->error;
        }
        $stmt->close();

        return $response;
    }

    // fetching single user by id
    public function getUser($user_id) {
        $stmt = $this->conn->prepare("SELECT user_id, name, email, gcm_registration_id, created_at FROM users WHERE user_id = ?");
        $stmt->bind_param("s", $user_id);
        if ($stmt->execute()) {
            // $user = $stmt->get_result()->fetch_assoc();
            $stmt->bind_result($user_id, $name, $email, $gcm_registration_id, $created_at);
            $stmt->fetch();
            $user = array();
            $user["user_id"] = $user_id;
            $user["name"] = $name;
            $user["email"] = $email;
            $user["gcm_registration_id"] = $gcm_registration_id;
            $user["created_at"] = $created_at;
            $stmt->close();
            return $user;
        } else {
            return NULL;
        }
    }

    // fetching multiple users by ids
    public function getUsers($user_ids) {

        $users = array();
        if (sizeof($user_ids) > 0) {
            $query = "SELECT user_id, name, email, gcm_registration_id, created_at FROM users WHERE user_id IN (";

            foreach ($user_ids as $user_id) {
                $query .= $user_id . ',';
            }

            $query = substr($query, 0, strlen($query) - 1);
            $query .= ')';

            $stmt = $this->conn->prepare($query);
            $stmt->execute();
            $result = $stmt->get_result();

            while ($user = $result->fetch_assoc()) {
                $tmp = array();
                $tmp["user_id"] = $user['user_id'];
                $tmp["name"] = $user['name'];
                $tmp["email"] = $user['email'];
                $tmp["gcm_registration_id"] = $user['gcm_registration_id'];
                $tmp["created_at"] = $user['created_at'];
                array_push($users, $tmp);
            }
        }

        return $users;
    }

    // messaging in a chat room / to persional message
    public function addMessage($user_id, $chat_room_id, $message) {
        $response = array();

        $stmt = $this->conn->prepare("INSERT INTO messages (chat_room_id, user_id, message) values(?, ?, ?)");
        $stmt->bind_param("iis", $chat_room_id, $user_id, $message);

        $result = $stmt->execute();

        if ($result) {
            $response['error'] = false;

            // get the message
            $message_id = $this->conn->insert_id;
            $stmt = $this->conn->prepare("SELECT message_id, user_id, chat_room_id, message, created_at FROM messages WHERE message_id = ?");
            $stmt->bind_param("i", $message_id);
            if ($stmt->execute()) {
                $stmt->bind_result($message_id, $user_id, $chat_room_id, $message, $created_at);
                $stmt->fetch();
                $tmp = array();
                $tmp['message_id'] = $message_id;
                $tmp['chat_room_id'] = $chat_room_id;
                $tmp['message'] = $message;
                $tmp['created_at'] = $created_at;
                $response['message'] = $tmp;
            }
        } else {
            $response['error'] = true;
            $response['message'] = 'Failed send message';
        }

        return $response;
    }

    // fetching all chat rooms
    public function getAllChatrooms() {
        $stmt = $this->conn->prepare("SELECT * FROM chat_rooms");
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

    // fetching single chat room by id
    function getChatRoom($chat_room_id) {
        $stmt = $this->conn->prepare("SELECT cr.chat_room_id, cr.name, cr.created_at as chat_room_created_at, u.name as username, c.* FROM chat_rooms cr LEFT JOIN messages c ON c.chat_room_id = cr.chat_room_id LEFT JOIN users u ON u.user_id = c.user_id WHERE cr.chat_room_id = ?");
        $stmt->bind_param("i", $chat_room_id);
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

    /**
     * Checking for duplicate user by email address
     * @param String $email email to check in db
     * @return boolean
     */
    private function isUserExists($email) {
        $stmt = $this->conn->prepare("SELECT user_id from users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();
        return $num_rows > 0;
    }

    /**
     * Fetching user by email
     * @param String $email User email id
     */
    public function getUserByEmail($email) {
        $stmt = $this->conn->prepare("SELECT user_id, name, email, created_at FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        if ($stmt->execute()) {
            // $user = $stmt->get_result()->fetch_assoc();
            $stmt->bind_result($user_id, $name, $email, $created_at);
            $stmt->fetch();
            $user = array();
            $user["user_id"] = $user_id;
            $user["name"] = $name;
            $user["email"] = $email;
            $user["created_at"] = $created_at;
            $stmt->close();
            return $user;
        } else {
            return NULL;
        }
    }

}

?>

8. Now let’s start creating the files required for GCM. Create a file named gcm.php inside libs ⇒ gcm folder. This file contains necessary functions required to interact with GCM server. These functions basically makes a CURL request to GCM server by passing required parameters in order to invoke a push notification.

send() – Function sends push notification to a single user

sendToTopic() – Sends push notification to a topic

sendToMultiple() – Send push notification to multiple users

<?php
class GCM {

    // constructor
    function __construct() {
        
    }

    // sending push message to single user by gcm registration id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // Sending message to a topic by topic id
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // sending push message to multiple users by gcm registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    // function makes curl request to gcm servers
    private function sendPushNotification($fields) {

        // include config
        include_once __DIR__ . '/../../include/config.php';

        // Set POST variables
        $url = 'https://gcm-http.googleapis.com/gcm/send';

        $headers = array(
            'Authorization: key=' . GOOGLE_API_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);

        return $result;
    }

}

?>

9. Under libs ⇒ gcm, create another file named push.php. This class prepares the required json format that is transferred as a push message to device. If you want to add additional fields to json, you need to add them in this class.

<?php
/**
 * @author Ravi Tamada
 * @link URL Tutorial link
 */

class Push{
    // push message title
    private $title;
    
    // push message payload
    private $data;
    
    // flag indicating background task on push received
    private $is_background;
    
    // flag to indicate the type of notification
    private $flag;
    
    function __construct() {
        
    }
    
    public function setTitle($title){
        $this->title = $title;
    }
    
    public function setData($data){
        $this->data = $data;
    }
    
    public function setIsBackground($is_background){
        $this->is_background = $is_background;
    }
    
    public function setFlag($flag){
        $this->flag = $flag;
    }
    
    public function getPush(){
        $res = array();
        $res['title'] = $this->title;
        $res['is_background'] = $this->is_background;
        $res['flag'] = $this->flag;
        $res['data'] = $this->data;
        
        return $res;
    }
}

10. At this stage, we have all the necessary functions ready. Let’s start preparing the REST API endpoints for the android app. Create a file named .htaccess inside v1 folder and add below rules.

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]

11. Create index.php inside v1 folder. All the rest api requests will be handled by this file only.

<?php

error_reporting(-1);
ini_set('display_errors', 'On');

require_once '../include/db_handler.php';
require '.././libs/Slim/Slim.php';

\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

// User login
$app->post('/user/login', function() use ($app) {
    // check for required params
    verifyRequiredParams(array('name', 'email'));

    // reading post params
    $name = $app->request->post('name');
    $email = $app->request->post('email');

    // validating email address
    validateEmail($email);

    $db = new DbHandler();
    $response = $db->createUser($name, $email);

    // echo json response
    echoRespnse(200, $response);
});


/* * *
 * Updating user
 *  we use this url to update user's gcm registration id
 */
$app->put('/user/:id', function($user_id) use ($app) {
    global $app;

    verifyRequiredParams(array('gcm_registration_id'));

    $gcm_registration_id = $app->request->put('gcm_registration_id');

    $db = new DbHandler();
    $response = $db->updateGcmID($user_id, $gcm_registration_id);

    echoRespnse(200, $response);
});

/* * *
 * fetching all chat rooms
 */
$app->get('/chat_rooms', function() {
    $response = array();
    $db = new DbHandler();

    // fetching all user tasks
    $result = $db->getAllChatrooms();

    $response["error"] = false;
    $response["chat_rooms"] = array();

    // pushing single chat room into array
    while ($chat_room = $result->fetch_assoc()) {
        $tmp = array();
        $tmp["chat_room_id"] = $chat_room["chat_room_id"];
        $tmp["name"] = $chat_room["name"];
        $tmp["created_at"] = $chat_room["created_at"];
        array_push($response["chat_rooms"], $tmp);
    }

    echoRespnse(200, $response);
});

/**
 * Messaging in a chat room
 * Will send push notification using Topic Messaging
 *  */
$app->post('/chat_rooms/:id/message', function($chat_room_id) {
    global $app;
    $db = new DbHandler();

    verifyRequiredParams(array('user_id', 'message'));

    $user_id = $app->request->post('user_id');
    $message = $app->request->post('message');

    $response = $db->addMessage($user_id, $chat_room_id, $message);

    if ($response['error'] == false) {
        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';
        $gcm = new GCM();
        $push = new Push();

        // get the user using userid
        $user = $db->getUser($user_id);

        $data = array();
        $data['user'] = $user;
        $data['message'] = $response['message'];
        $data['chat_room_id'] = $chat_room_id;

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_CHATROOM);
        $push->setData($data);
        
        // echo json_encode($push->getPush());exit;

        // sending push message to a topic
        $gcm->sendToTopic('topic_' . $chat_room_id, $push->getPush());

        $response['user'] = $user;
        $response['error'] = false;
    }

    echoRespnse(200, $response);
});


/**
 * Sending push notification to a single user
 * We use user's gcm registration id to send the message
 * * */
$app->post('/users/:id/message', function($to_user_id) {
    global $app;
    $db = new DbHandler();

    verifyRequiredParams(array('message'));

    $from_user_id = $app->request->post('user_id');
    $message = $app->request->post('message');

    $response = $db->addMessage($from_user_id, $to_user_id, $message);

    if ($response['error'] == false) {
        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';
        $gcm = new GCM();
        $push = new Push();

        $user = $db->getUser($to_user_id);

        $data = array();
        $data['user'] = $user;
        $data['message'] = $response['message'];
        $data['image'] = '';

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_USER);
        $push->setData($data);

        // sending push message to single user
        $gcm->send($user['gcm_registration_id'], $push->getPush());

        $response['user'] = $user;
        $response['error'] = false;
    }

    echoRespnse(200, $response);
});


/**
 * Sending push notification to multiple users
 * We use gcm registration ids to send notification message
 * At max you can send message to 1000 recipients
 * * */
$app->post('/users/message', function() use ($app) {

    $response = array();
    verifyRequiredParams(array('user_id', 'to', 'message'));

    require_once __DIR__ . '/../libs/gcm/gcm.php';
    require_once __DIR__ . '/../libs/gcm/push.php';

    $db = new DbHandler();

    $user_id = $app->request->post('user_id');
    $to_user_ids = array_filter(explode(',', $app->request->post('to')));
    $message = $app->request->post('message');

    $user = $db->getUser($user_id);
    $users = $db->getUsers($to_user_ids);

    $registration_ids = array();

    // preparing gcm registration ids array
    foreach ($users as $u) {
        array_push($registration_ids, $u['gcm_registration_id']);
    }

    // insert messages in db
    // send push to multiple users
    $gcm = new GCM();
    $push = new Push();

    // creating tmp message, skipping database insertion
    $msg = array();
    $msg['message'] = $message;
    $msg['message_id'] = '';
    $msg['chat_room_id'] = '';
    $msg['created_at'] = date('Y-m-d G:i:s');

    $data = array();
    $data['user'] = $user;
    $data['message'] = $msg;
    $data['image'] = '';

    $push->setTitle("Google Cloud Messaging");
    $push->setIsBackground(FALSE);
    $push->setFlag(PUSH_FLAG_USER);
    $push->setData($data);

    // sending push message to multiple users
    $gcm->sendMultiple($registration_ids, $push->getPush());

    $response['error'] = false;

    echoRespnse(200, $response);
});

$app->post('/users/send_to_all', function() use ($app) {

    $response = array();
    verifyRequiredParams(array('user_id', 'message'));

    require_once __DIR__ . '/../libs/gcm/gcm.php';
    require_once __DIR__ . '/../libs/gcm/push.php';

    $db = new DbHandler();

    $user_id = $app->request->post('user_id');
    $message = $app->request->post('message');

    require_once __DIR__ . '/../libs/gcm/gcm.php';
    require_once __DIR__ . '/../libs/gcm/push.php';
    $gcm = new GCM();
    $push = new Push();

    // get the user using userid
    $user = $db->getUser($user_id);
    
    // creating tmp message, skipping database insertion
    $msg = array();
    $msg['message'] = $message;
    $msg['message_id'] = '';
    $msg['chat_room_id'] = '';
    $msg['created_at'] = date('Y-m-d G:i:s');

    $data = array();
    $data['user'] = $user;
    $data['message'] = $msg;
    $data['image'] = 'https://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png';

    $push->setTitle("Google Cloud Messaging");
    $push->setIsBackground(FALSE);
    $push->setFlag(PUSH_FLAG_USER);
    $push->setData($data);

    // sending message to topic `global`
    // On the device every user should subscribe to `global` topic
    $gcm->sendToTopic('global', $push->getPush());

    $response['user'] = $user;
    $response['error'] = false;

    echoRespnse(200, $response);
});

/**
 * Fetching single chat room including all the chat messages
 *  */
$app->get('/chat_rooms/:id', function($chat_room_id) {
    global $app;
    $db = new DbHandler();

    $result = $db->getChatRoom($chat_room_id);

    $response["error"] = false;
    $response["messages"] = array();
    $response['chat_room'] = array();

    $i = 0;
    // looping through result and preparing tasks array
    while ($chat_room = $result->fetch_assoc()) {
        // adding chat room node
        if ($i == 0) {
            $tmp = array();
            $tmp["chat_room_id"] = $chat_room["chat_room_id"];
            $tmp["name"] = $chat_room["name"];
            $tmp["created_at"] = $chat_room["chat_room_created_at"];
            $response['chat_room'] = $tmp;
        }

        if ($chat_room['user_id'] != NULL) {
            // message node
            $cmt = array();
            $cmt["message"] = $chat_room["message"];
            $cmt["message_id"] = $chat_room["message_id"];
            $cmt["created_at"] = $chat_room["created_at"];

            // user node
            $user = array();
            $user['user_id'] = $chat_room['user_id'];
            $user['username'] = $chat_room['username'];
            $cmt['user'] = $user;

            array_push($response["messages"], $cmt);
        }
    }

    echoRespnse(200, $response);
});

/**
 * Verifying required params posted or not
 */
function verifyRequiredParams($required_fields) {
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
    if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
        $app = \Slim\Slim::getInstance();
        parse_str($app->request()->getBody(), $request_params);
    }
    foreach ($required_fields as $field) {
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
            $error = true;
            $error_fields .= $field . ', ';
        }
    }

    if ($error) {
        // Required field(s) are missing or empty
        // echo error json and stop the app
        $response = array();
        $app = \Slim\Slim::getInstance();
        $response["error"] = true;
        $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
        echoRespnse(400, $response);
        $app->stop();
    }
}

/**
 * Validating email address
 */
function validateEmail($email) {
    $app = \Slim\Slim::getInstance();
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response["error"] = true;
        $response["message"] = 'Email address is not valid';
        echoRespnse(400, $response);
        $app->stop();
    }
}

function IsNullOrEmptyString($str) {
    return (!isset($str) || trim($str) === '');
}

/**
 * Echoing json response to client
 * @param String $status_code Http response code
 * @param Int $response Json response
 */
function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    // Http response code
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

$app->run();
?>

REST API Endpoints

The index.php inside v1 folder providers the below endpoints.

Base URL: http://localhost/gcm_chat/v1

Endpoint Params Method Description
/user/login name, email POST User login or registration
/user/:id gcm_registration_id PUT Updates user’s gcm registration id in database
/chat_rooms GET Fetches all chat rooms
/chat_rooms/:id replace :id with actual chat room id GET Fetches single chat room messages
/chat_rooms/:id/message replace :id with actual chat room id POST Posting a message in a chat room
/users/:id/message replace :id with actual user id POST Sending a message to user
/users/message user_id, to, message
`to` – param is user ids separated by comma (,)
POST Sending a message to multiple users
/users/send_to_all user_id, message POST Sending a message to all the users subscribed to `global` topic

6. Testing the REST API

Before starting the android project, make sure that the php project is running without any errors. Follow the below steps to test the API.

1. Enable apache mod_rewrite module (link)

2. Enable curl extension. This allows php to make http requests from the backend (link).

3. Install Postman Chrome REST API extension. You can use any other rest api clients too.

The below video takes you through testing the API using Postman.

7. Building the Admin Panel

I created very simple admin panel using PHP, HTML, CSS & jQuery. This admin panel might not be used in production stage, but gives you necessary functions to build a better one.

1. Create a file named demo.php in the root directory of gcm_chat. This class contains function for the admin panel.

<?php

/**
 * Class to handle all db operations
 * This class will have CRUD methods for database tables
 *
 * @author Ravi Tamada
 */
class Demo {

    private $conn;

    function __construct() {
        require_once dirname(__FILE__) . '/include/db_connect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    public function getAllChatRooms() {
        $stmt = $this->conn->prepare("SELECT * FROM chat_rooms");
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

    public function getAllUsers() {
        $stmt = $this->conn->prepare("SELECT * FROM users");
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;
    }

    public function getDemoUser() {
        $name = 'AndroidHive';
        $email = 'admin@androidhive.info';
        
        $stmt = $this->conn->prepare("SELECT user_id from users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        if ($num_rows > 0) {
            $stmt->bind_result($user_id);
            $stmt->fetch();
            return $user_id;
        } else {
            $stmt = $this->conn->prepare("INSERT INTO users(name, email) values(?, ?)");
            $stmt->bind_param("ss", $name, $email);
            $result = $stmt->execute();
            $user_id = $stmt->insert_id;
            $stmt->close();
            return $user_id;
        }
    }
}
?>

2. Create a style sheet named style.css in the root directory.

/* 
    Created on : 22 Jan, 2016, 10:12:06 PM
    Author     : Ravi Tamada
*/

body{
    width: 100%;
    margin: 0;
    padding: 0;   
    font-family: 'Raleway', sans-serif;
}
.container_body{
    width: 1000px;
    margin: 0 auto;
}
.header{
    padding: 100px 0;
    text-align: center;
    color: #fff;
    background: -moz-radial-gradient(center, ellipse cover, rgba(227,71,73,1) 0%, rgba(186,27,31,1) 100%); /* ff3.6+ */
    background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%, rgba(227,71,73,1)), color-stop(100%, rgba(186,27,31,1))); /* safari4+,chrome */
    background:-webkit-radial-gradient(center, ellipse cover, rgba(227,71,73,1) 0%, rgba(186,27,31,1) 100%); /* safari5.1+,chrome10+ */
    background: -o-radial-gradient(center, ellipse cover, rgba(227,71,73,1) 0%, rgba(186,27,31,1) 100%); /* opera 11.10+ */
    background: -ms-radial-gradient(center, ellipse cover, rgba(227,71,73,1) 0%, rgba(186,27,31,1) 100%); /* ie10+ */
    background:radial-gradient(ellipse at center, rgba(227,71,73,1) 0%, rgba(186,27,31,1) 100%); /* w3c */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e34749', endColorstr='#ba1b1f',GradientType=1 ); /* ie6-9 */
}
.header .logo{
    font-weight: bold;
    font-size: 30px;
    display: block;
    margin: 10px 0;
    letter-spacing: 3px;
}
.header h2{
    display: block;
    font-size: 50px;
    font-weight: 100;
    line-height: 10px;
}
.header h2.small{
    font-size: 25px;
    font-weight: 300;
    padding-top: 20px;
    letter-spacing: 1px;
}
.topics{
    text-align: center;
    padding-top: 50px;
}
.topics h2.heading{
    font-size: 30px;
    color: #666;
    font-weight: 400;
    display: block;
}
.box{
    width: 900px;
    margin: 40px auto;
    border: 1px solid #dedede;
    background: #f2f4f8;
    position: relative;
}
.box .usr_container,
.box .msg_container{
    float: left;
    height: 600px;
    overflow-x: hidden;
    overflow-y: auto;
}
.box .usr_container{
    width: 350px;
    border-right: 1px solid #dedede;
    background: #fff;
}
.box .msg_container{
    width: 548px;
    position: relative;
}
.box ul{
    margin: 0;
    padding: 0;
}
.box ul li{
    margin: 0;
    padding: 0;
    list-style: none;
    text-align: left;
    cursor: pointer;
}

.box .usr_container ul li{
    padding: 20px 10px;
    background: #fff;
    border-bottom: 1px solid #dedede;
}
.box .usr_container ul li label{
    display: block;
    width: 100%;
    font-family: arial;
    font-weight: 400;
    color: #333;
    font-size: 18px;
    margin-bottom: 5px;
}
.box .usr_container ul li label:hover{
    cursor: pointer;
}
.box .usr_container ul li span{
    color: #777;
    font-family: arial;
    font-size: 14px;
    font-style: italic;
}
.box .usr_container ul li.selected{
    background: #f2f4f8;
}
.box .usr_container ul li.selected label{
    color: #e34749;
}
.box .usr_container ul li.selected span{
    color: #000;
}
.box .usr_container ul li:hover{
    background: #dedede;
    cursor: pointer;
}
.box .msg_container ul{
    padding: 10px 0;
    margin-bottom: 75px;
}
.box .msg_container li{
    padding: 10px 0;
}
.box .msg_container li.others{
    cursor: auto;
    text-align: left;
    padding-left: 20px;
}
.box .msg_container li.self{
    text-align: right;
    cursor: auto;
    padding-right: 20px;
}
.box .msg_container li.self label{
    float: right;
}
.box .msg_container li .message{
    background: #fff;
    border-radius: 3px;
    padding: 15px;
    max-width: 400px;
    font-size: 15px;
    font-family: arial;
    float: left;
    line-height: 20px;
    margin: 5px 0 10px 0;
}
.box .msg_container li label{
    float: left;
    display: block;
    width: 100%;
    font-size: 12px;
    color: #777;
    font-family: arial;
}
.box .msg_container li.others .message{

}
.box .msg_container li.self .message{
    background: #dee2ef;
    float: right;
    display: inline-block;
}
.clear{
    clear:both;
}
.send_container{
    border-top: 1px solid #dedede;
    background: #f7f9fd;
    position: absolute;
    bottom: 0;
    height:75px;
    right: 0;
}
.send_container textarea{
    background: #f7f9fd;
    height: 30px;
    width: 550px;
    font-size: 15px;
    text-align: left;
    padding: 20px;
    border: none;
    resize: none;
    outline: none;
}
.send_container input[type="button"]{
    position: absolute;
    top: 20px;
    right: 20px;
    padding: 10px;
    background: #e34749;
    outline: none;
    border: none;
    cursor: pointer;
    color: #fff;
    font-weight: bold;
    font-size: 15px;
}
.btn_send{
    padding: 10px;
    background: #e34749;
    outline: none;
    border: none;
    cursor: pointer;
    color: #fff;
    font-weight: bold;
    font-size: 15px;
}
.box .msg_container li label.name{
    display: block;
}
div.container{
    width: 900px;
    margin: 0 auto;
}
select.select_single{
    padding: 10px;
    font-size: 16px;
    width: 400px;
}
select.select_single option{
    font-size: 19px;
}
select.select_multiple{
    font-size: 15px;
    width: 400px;
    height: 200px;
}
select.select_multiple option{
    padding: 5px;
}
textarea.textarea_msg{
    width: 400px;
    height: 120px;
    resize: none;
    margin:20px auto;
    padding: 15px;
    background: #f7f9fd;
    font-size: 15px;
}
.loader{
    display: none;
}
pre{
    width: 800px;
    text-align: left !important;
    font-size: 16px;
    font-family: monospace;
    margin: 0 auto;
    line-height: 20px;
}
.separator{
    width: 100%;
    height: 1px;
    background: #cdcdcd;
    margin: 50px 0;
}

3. Paste the loader.gif image in the same directory.

4. Create index.php in the root directory. Here I have written necessary php, html and jQuery code to build the admin UI.

<?php
error_reporting(-1);
ini_set('display_errors', 'On');
?>

<?php
require_once __DIR__ . '/demo.php';
$demo = new Demo();
$admin_id = $demo->getDemoUser();
?>

<html>
    <head>
        <title>Google Cloud Messaging 3.0 | AndroidHive</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href='https://fonts.googleapis.com/css?family=Raleway:400,800,100' rel='stylesheet' type='text/css'>
        <link href='style.css' rel='stylesheet' type='text/css'>
        <link href='https://api.androidhive.info/gcm/styles/default.css' rel='stylesheet' type='text/css'>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
        <script type="text/javascript">
            var user_id = '<?= $admin_id ?>';
            $(document).ready(function () {

                getChatroomMessages($('#topics li:first').attr('id'));


                $('ul#topics li').on('click', function () {
                    $('ul#topics li').removeClass('selected');
                    $(this).addClass('selected');
                    getChatroomMessages($(this).prop('id'))
                });

                function getChatroomMessages(id) {
                    $.getJSON("v1/chat_rooms/" + id, function (data) {
                        var li = '';
                        $.each(data.messages, function (i, message) {
                            li += '<li class="others"><label class="name">' + message.user.username + '</label><div class="message">' + message.message + '</div><div class="clear"></div></li>';
                        });
                        $('ul#topic_messages').html(li);
                        if (data.messages.length > 0) {
                            scrollToBottom('msg_container_topic');
                        }
                    }).done(function () {

                    }).fail(function () {
                        alert('Sorry! Unable to fetch topic messages');
                    }).always(function () {

                    });

                    // attaching the chatroom id to send button
                    $('#send_to_topic').attr('chat_room', id);
                }

                $('#send_to_topic').on('click', function () {
                    var msg = $('#send_to_topic_message').val();
                    if (msg.trim().length === 0) {
                        alert('Enter a message');
                        return;
                    }

                    $('#send_to_topic_message').val('');
                    $('#loader_topic').show();

                    $.post("v1/chat_rooms/" + $(this).attr('chat_room') + '/message',
                            {user_id: user_id, message: msg},
                    function (data) {
                        if (data.error === false) {
                            var li = '<li class="self" tabindex="1"><label class="name">' + data.user.name + '</label><div class="message">' + data.message.message + '</div><div class="clear"></div></li>';
                            $('ul#topic_messages').append(li);
                            scrollToBottom('msg_container_topic');
                        } else {
                            alert('Sorry! Unable to send message');
                        }
                    }).done(function () {

                    }).fail(function () {
                        alert('Sorry! Unable to send message');
                    }).always(function () {
                        $('#loader_topic').hide();
                    });
                });

                $('input#send_to_single_user').on('click', function () {
                    var msg = $('#send_to_single').val();
                    var to = $('.select_single').val();
                    if (msg.trim().length === 0) {
                        alert('Enter a message');
                        return;
                    }

                    $('#send_to_single').val('');
                    $('#loader_single').show();

                    $.post("v1/users/" + to + '/message',
                            {user_id: user_id, message: msg},
                    function (data) {
                        if (data.error === false) {
                            $('#loader_single').hide();
                            alert('Push notification sent successfully! You should see a Toast message on device.');
                        } else {
                            alert('Sorry! Unable to post message');
                        }
                    }).done(function () {

                    }).fail(function () {
                        alert('Sorry! Unable to send message');
                    }).always(function () {
                        $('#loader_single').hide();
                    });
                });

                $('input#send_to_multiple_users').on('click', function () {
                    var msg = $('#send_to_multiple').val();
                    var to = $('.select_multiple').val();

                    if (to === null) {
                        alert("Please select the users!");
                        return;
                    }

                    if (msg.trim().length === 0) {
                        alert('Enter a message');
                        return;
                    }

                    $('#send_to_multiple').val('');
                    $('#loader_multiple').show();

                    var selMulti = $.map($(".select_multiple option:selected"), function (el, i) {
                        return $(el).val();
                    });

                    to = selMulti.join(",");

                    $.post("v1/users/message",
                            {user_id: user_id, to: to, message: msg},
                    function (data) {
                        if (data.error === false) {
                            $('#loader_multiple').hide();
                            alert('Push notification sent successfully to multiple users');
                        } else {
                            alert('Sorry! Unable to send message');
                        }
                    }).done(function () {

                    }).fail(function () {
                        alert('Sorry! Unable to send message');
                    }).always(function () {
                        $('#loader_multiple').hide();
                    });
                });

                $('input#send_to_multiple_users_with_image').on('click', function () {

                    var msg = $('#send_to_multiple_with_image').val();
                    if (msg.trim().length === 0) {
                        alert('Enter a message');
                        return;
                    }

                    $('#send_to_multiple_with_image').val('');
                    $('#loader_multiple_with_image').show();

                    $.post("v1/users/send_to_all",
                            {user_id: user_id, message: msg},
                    function (data) {
                        if (data.error === false) {
                            $('#loader_multiple_with_image').hide();
                            alert('Push notification sent successfully to multiple users');
                        } else {
                            alert('Sorry! Unable to send message');
                        }
                    }).done(function () {

                    }).fail(function () {
                        alert('Sorry! Unable to send message');
                    }).always(function () {
                        $('#loader_topic_with_image').hide();
                    });
                });

                function scrollToBottom(cls) {
                    $('.' + cls).scrollTop($('.' + cls + ' ul li').last().position().top + $('.' + cls + ' ul li').last().height());
                }
            });
        </script>
    </head>
    <body>
        <div class="header">
            <label class="logo">ANDROIDHIVE</label>
            <h2>Google Cloud Messaging</h2>
            <h2 class="small">Sending push notifications using Android, PHP & MySQL</h2>
        </div>
        <div class="container_body">
            <div class="topics">
                <h2 class="heading">Download & Install the GCM apk</h2>
                Download & Install the Google Cloud Messaging <a href="#">apk</a> before trying the demos. <br/><br/>Once installed, refresh this page 
                to see your name, email in the recipients list.
            </div>

            <div class="topics">
                <div class="separator"></div>
                <h2 class="heading">Sending message to a `topic`</h2>
                Select any of the topics below and send a message.<br/><br/>
                <div class="box">
                    <div class="usr_container">
                        <ul id="topics">
                            <?php
                            $chatrooms = $demo->getAllChatRooms();
                            foreach ($chatrooms as $key => $chatroom) {
                                $cls = $key == 0 ? 'selected' : '';
                                ?>
                                <li id="<?= $chatroom['chat_room_id'] ?>" class="<?= $cls ?>">
                                    <label><?= $chatroom['name'] ?></label>
                                    <span>topic_<?= $chatroom['chat_room_id'] ?></span>
                                </li>
                                <?php
                            }
                            ?>
                        </ul>
                    </div>
                    <div class="msg_container msg_container_topic">
                        <ul id="topic_messages"></ul>
                    </div>
                    <div class="send_container">
                        <textarea placeholder="Type a message here" id="send_to_topic_message"></textarea>
                        <input id="send_to_topic" type="button" value="Send to Topic"/>
                        <img src="loader.gif" id="loader_topic" class="loader"/>
                    </div>
                    <div class="clear"></div>
                </div>
                <br/>
                <div class="separator"></div>
                <h2 class="heading">Sending message to `Single User`</h2>
                Select your name from the below recipients and send a message<br/><br/>

                <div class="container">
                    <select class="select_single">
                        <?php
                        $users = $demo->getAllUsers();
                        foreach ($users as $key => $user) {
                            ?>
                            <option value="<?= $user['user_id'] ?>"><?= $user['name'] ?> (<?= $user['email'] ?>)</option>
                            <?php
                        }
                        ?>
                    </select><br/>
                    <textarea id="send_to_single" class="textarea_msg" placeholder="Type a message"></textarea><br/>
                    <input id="send_to_single_user" type="button" value="Send to single user" class="btn_send"/>
                    <img src="loader.gif" id="loader_single" class="loader"/>
                </div>
                <br/>
                <div class="separator"></div>
                <h2 class="heading">Sending message to `Multiple Users`</h2>
                Select multiple recipients and send a message. You can use ctrl or shift to select multiple users<br/><br/><br/>

                <div class="container">
                    <select multiple class="select_multiple">
                        <?php
                        foreach ($users as $key => $user) {
                            ?>
                            <option value="<?= $user['user_id'] ?>"><?= $user['name'] ?> (<?= $user['email'] ?>)</option>
                            <?php
                        }
                        ?>
                    </select>
                    <br/>
                    <textarea id="send_to_multiple" class="textarea_msg" placeholder="Type a message"></textarea><br/>
                    <input id="send_to_multiple_users" type="button" value="Send to multiple users" class="btn_send"/>
                    <img src="loader.gif" id="loader_multiple" class="loader"/>
                </div>

                <br/>
                <div class="separator"></div>
                <h2 class="heading">Sending push notification with an `Image`</h2>
                A message with an image attachment will be sent to every user. You have to minimize or close the app in order to see
                it in action.<br/><br/>

                <div class="container">
                    <textarea id="send_to_multiple_with_image" class="textarea_msg" placeholder="Type a message"></textarea><br/>
                    <input id="send_to_multiple_users_with_image" type="button" value="Send with image" class="btn_send"/>
                    <img src="loader.gif" id="loader_multiple_with_image" class="loader"/>
                </div>
            </div>
            <br/><br/>
            <br/><br/>
            <br/><br/>
        </div>
    </body>
</html>

5. Finally access the admin panel by going to http://localhost/gcm_chat/ (If your apache is running under a port, add the port number to localhost)

You should able to see the below admin panel which provides options to send the messages to devices from admin panel. Here the Live Demo of the admin app.

android-gcm-chat-app-admin-panel

With this we have completed 1s part of the article, but before moving to 2nd Part, quickly go through below code snippets which are very useful if you want to extend the server app functionality.

7. Quick Code Snippets

Sending Push To Single User

        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';
        $gcm = new GCM();
        $push = new Push();

        $data = array();
        // user node
        $data['user'] = $user;
        // message node
        $data['message'] = $response['message'];
        $data['image'] = '';

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_USER);
        $push->setData($data);

        // Pass the receiver gcm registration token
        $gcm_registration_id = 'fnFAQ_BA7pY:APA91bFOwrCw9LHhJKatfvMx-2XA7-NdUMUMF5c9RS0....';

        // sending push message to single user
        $gcm->send($user['gcm_registration_id'], $push->getPush());

Sending Push To Multiple Users

    require_once __DIR__ . '/../libs/gcm/gcm.php';
    require_once __DIR__ . '/../libs/gcm/push.php';

    $gcm = new GCM();
    $push = new Push();

    $msg = array();
    $msg['message'] = $message;
    $msg['message_id'] = '';
    $msg['chat_room_id'] = '';
    $msg['created_at'] = date('Y-m-d G:i:s');

    $data = array();
    $data['user'] = $user;
    $data['message'] = $msg;
    $data['image'] = '';

    $push->setTitle("Google Cloud Messaging");
    $push->setIsBackground(FALSE);
    $push->setFlag(PUSH_FLAG_USER);
    $push->setData($data);

    // Keep all the recipients gcm tokens in an array 
    $registration_ids = array('fnFAQ_BA7pY:APA91bFOwrCw9LHhJKatfvMx-2XA7-NdUMUMF5c9RS0....', 'fnFAQ_BA7pY:APA91bFOwrCw9LHhJKatfvMx-2XA7-NdUMUMF5c9RS0....');

    // sending push message to multiple users
    $gcm->sendMultiple($registration_ids, $push->getPush());

Sending Push To a Topic

        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';

        $gcm = new GCM();
        $push = new Push();

        $data = array();
        $data['user'] = $user;
        $data['message'] = $response['message'];
        $data['chat_room_id'] = $chat_room_id;

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_CHATROOM);
        $push->setData($data);

        // the topic you want to send notification
        $topic = 'your_topic_name';

        // sending push message to a topic
        $gcm->sendToTopic($topic, $push->getPush());

Sending Push with an Image

        require_once __DIR__ . '/../libs/gcm/gcm.php';
        require_once __DIR__ . '/../libs/gcm/push.php';

        $gcm = new GCM();
        $push = new Push();

        // keep the notification image url here
        $image = 'https://api.androidhive.info/gcm/panda.jpg';

        $data = array();
        $data['user'] = $user;
        $data['message'] = $response['message'];
        $data['image'] = $image;

        $push->setTitle("Google Cloud Messaging");
        $push->setIsBackground(FALSE);
        $push->setFlag(PUSH_FLAG_USER);
        $push->setData($data);

        $gcm_registration_id = 'fnFAQ_BA7pY:APA91bFOwrCw9LHhJKatfvMx-2XA7-NdUMUMF5c9RS0....';

        // sending push message to single user
        $gcm->send($user['gcm_registration_id'], $push->getPush());

By far we have successfully built the proper REST API client and a simple admin panel. Now let’s start building the android app in 2nd Part. If you are facing any issue in this part, please comment in below discussions.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • varun

    Thank you for new tutorial bro..can you post a tutorial with beacons

    • I guess I need to buy a Beacon right?

      • varun

        yes..any app using beacons..how to detect beacon and etc..

  • Anupam Anand

    by impleming first part this is what i am getting can you please check what is wrong in it.
    http://booksasap.in/gcm_chat ca

  • Oussama

    hello
    how can we send as push msg with GCM for free?

  • Rishika Kapur

    Hi Ravi!

    I don’t want to use local development environment (MAMP) instead I want to use Hostgator. Should I follow the exact steps or there are something different need to be done?

    • Yeah you can. But make sure that hostgator is supporting musqlnd. Just download the code, upload it to hostgator and verify.

      • Hamdi wanis

        what if it does not ?

  • Lucky Bhumkar

    Master Piece.. great you have illustrated it in it’s easiest level..!

  • nice tutorial…

  • 박준혁

    Oh my god….This Tutorial is great!I almost certainly love u!

  • daniel dizzy

    Thansk again Ravi, your tutorials are very self explanatory. Am always greatful.

  • Justin Smith

    thanks for your great tutorials

  • Rege

    Hello Ravi,

    I setup and install api. Thank you the tutorial.
    But I have one problem. If I write the messages I don’t see the phone real time… If I open the room i can see after loading the room. What do I do wrong? Thank you your answers.

    • After login check whether gcm registration token is printing in LogCat or not.

  • Nitesh

    I did everything as explained but i am getting error 404 Page Not Found.. I have enabled apache rewrite mod and curl extension. index.php is working fine but when i am adding localhost/gcm_chat/v1 its show page not found. I am using xampp.. Please guide.. Thanks

    • localhost/gcm_chat/v1 always gives 404. You need to access the final endpoint with the correct http method

      localhost/gcm_chat/v1/user/login with POST method.

      • Ricky

        replace ‘localhost’ to your IPAdress. For example
        public static final String BASE_URL = “http://192.168.82.10/gcm_chat/v1”;

    • Rinku Meena

      use url /gcm_chat/v1/index.php/user/login and it will work

  • Thong Le

    Hi Ravi. tks for awesome tut. But I have an error: when I test rest api by postman , I input name and email, the server always respone :{
    “error”: true,
    “message”: “Oops! An error occurred while registereing”
    }

    • Radovan Heldák

      I have the same problem 🙁

      • Make sure you have created the mysql tables correctly and gave the correct database credentials in config file.

        • Thong Le

          thank for your reply, I fixed it by coppy all code MySQL from folder db (downloaded) without copy code from web.

          • Okay. Let me check the website SQL code again. Thanks.

          • M

            SQL codes from this page does not include adding auto_increment in user_id.
            That’s why people can not make a new user because there is always 0 in user_id (primary key, unique as default).

          • Daniele

            so how can we fix this?

    • Rishika Kapur

      I am getting the same error. Can you explain, how did you fix it?

    • Rony Vidaur

      I have still the same issue, even though I’ve try the solution provided here 🙁 any ideas?

  • Yaqoub Alsaadi

    hi Ravi
    i get error
    Volley error:null
    i use locall sever(wamp)

  • siddhant jain

    hello…. how can i delete the chat msgs ..like we do in whatsapp…. & to include touch & select feature for msgs for forwarding it
    & how to change the notification ringtone

  • sankalp bhambri

    Awesome tutorial. Working perfect 🙂

  • Jaija

    Hi Ravi
    I use http: //localhost/gcm_chat/push_test.php
    when pressed send push notification messages are then sorry! unable to send message.

  • WaWaToR

    I am getting an error please help. Thanks

    Fatal error: Call to a member function bind_param() on a non-object in /home/wawawebfep/www/gcm_chat/demo.php on line 42

  • Thandy

    Hi!! Thanks a lot for this tut!!

    i am getting this erro:
    ~
    Type: ErrorException

    Code: 8

    Message: Use of undefined constant PUSH_FLAG_CHATROOM – assumed ‘PUSH_FLAG_CHATROOM’

    File: C:xampphtdocslocalhosthivegcm_chatv1index.php

    Line: 106

    Trace
    #0 C:xampphtdocslocalhosthivegcm_chatv1index.php(106): SlimSlim::handleErrors(8, ‘Use of undefine…’, ‘C:xampphtdocs…’, 106, Array)
    #1 [internal function]: {closure}(‘2’)
    #2 C:xampphtdocslocalhosthivegcm_chatlibsSlimRoute.php(436): call_user_func_array(Object(Closure), Array)
    #3 C:xampphtdocslocalhosthivegcm_chatlibsSlimSlim.php(1307): SlimRoute->dispatch()
    #4 C:xampphtdocslocalhosthivegcm_chatlibsSlimMiddlewareFlash.php(85): SlimSlim->call()
    #5 C:xampphtdocslocalhosthivegcm_chatlibsSlimMiddlewareMethodOverride.php(92): SlimMiddlewareFlash->call()
    #6 C:xampphtdocslocalhosthivegcm_chatlibsSlimMiddlewarePrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
    #7 C:xampphtdocslocalhosthivegcm_chatlibsSlimSlim.php(1254): SlimMiddlewarePrettyExceptions->call()
    #8 C:xampphtdocslocalhosthivegcm_chatv1index.php(453): SlimSlim->run()
    #9 {main}

    • Thandy

      I just solve… it was my mistake…

      Thankssss

  • Khalid S.

    Hi Ravi, this tutorial is incredible. Thank you for your effort in writing it!

    I was testing my REST API with Postman like in your video and everything works fine except for the PUT request.

    I made sure to type in the parameter name very carefully “gcm_registration_id” but it refuses to work and I keep getting this message:

    “error”: true,
    “message”: “Required field(s) gcm_registration_id is missing or empty”

    Do you know why this might be happening?

    • Yeah, in Postman for PUT request choose x-www-form-urlencoded instead of form-data (see there is a radio button)

      • Khalid S.

        You are THE MAN! Thank you 🙂

  • Navas AR

    Hi ravi I have an error
    Fatal error: Call to undefined method mysqli_stmt::get_result() in /localhost/www/gcm_chat/include/db_handler.php on line 164
    json parsing error: <br of type java.lang.String cannot be converted to JSONObject

    • noah

      seconded.

      • Noah

        I fixed this by installing mysqlnd:

        sudo apt-get install php5-mysqlnd
        sudo service apache2 restart

        • Navas AR

          how to install it?

  • Mahesh

    Hi Ravi, How can I get the gcm_registration_id I am new to Android can you please Elobarate

    • Check the part 2 of the article. You can see that I logged the gcm token in Main Activity.

    • Mahesh D

      Thanks Ravi,
      Okay where I can place Project Number (or) sender Id in this..

      • We don’t use project number or sender id anymore like we did for older GCM. Instead we add google-services.json file where all these things will be configured. Check part 2 of this article.

        • Mahesh D

          Thanks,

          Now I got voelly error
          Log cat is

          params: {email=mymailid@gmail.com, name=Mahesh}
          02-21 12:15:24.497 19582-19963/info.androidhive.gcm E/Volley﹕ [162] BasicNetwork.performRequest: Unexpected response code 500 for http://192.168.1.3/cloud_chat/v1/user/login
          02-21 12:15:24.513 19582-19582/info.androidhive.gcm E/LoginActivity﹕ Volley error: null, code: com.android.volley.NetworkResponse@4111964
          02-21 12:15:24.667 19582-19611/info.androidhive.gcm W/EGL_emulation﹕ eglSurfaceAttrib not implemented

          Can you please how can I login into app

          • Mahesh D

            public void addToRequestQueue(Request req) {

            req.setTag(TAG);

            getRequestQueue().add(req);

            } and I debug the param req = I

            [ ] http://192.168.1.3/cloud_chat/v1/user/login 0x355f917 NORMAL null… What I can get instead of 0x355f917

  • Ibrahim Samad

    Thanks for the long awaited tutorial.
    I want to implement this in a web app not an android app. Pls what will be the next step after this first part of the tutorial, Since I probably don’t need the second and third part.

  • Pankaj Lagad

    Hi Ravi,
    When I clicked on login button I got the following errors,
    What will be the reason???

    02-17 01:16:32.970 12507-12507/info.androidhive.googlecloudmessagingexample E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
    02-17 01:16:32.970 12507-12507/info.androidhive.googlecloudmessagingexample E/SpannableStringBuilder: SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
    02-17 01:16:47.441 12507-12821/info.androidhive.googlecloudmessagingexample E/LoginActivity: params: {email=lagadpankaj@gmail.com, name=Pankaj Lagad}
    02-17 01:16:47.480 12507-12821/info.androidhive.googlecloudmessagingexample E/Volley: [1260] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.42.125:80/gcm_chat/v1/user/login
    02-17 01:16:47.481 12507-12821/info.androidhive.googlecloudmessagingexample E/LoginActivity: params: {email=lagadpankaj@gmail.com, name=Pankaj Lagad}
    02-17 01:16:47.495 12507-12821/info.androidhive.googlecloudmessagingexample E/Volley: [1260] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.42.125:80/gcm_chat/v1/user/login
    02-17 01:16:47.502 12507-12507/info.androidhive.googlecloudmessagingexample E/LoginActivity: Volley error: null, code: com.android.volley.NetworkResponse@42d8b0f0

  • noah

    Hey Ravi,

    Your demo at http://demo.androidhive.info/gcm_chat/ has been hacked. Displays porn now… Might want to fix that. This is why we can’t have nice things.

  • gw

    I’m hitting a 404 and am out of ideas. I have ensured that mod_rewrite and curl are enabled. My site can be hit at gcm_chat/ (although i get “Sorry! Unable to fetch topic messages”). When I use postman to GET http://ec2-XX-XXX-XXX-XXX.compute-1.amazonaws.com/gcm_chat/v1/chat_rooms I get

    404 Not Found

    Not Found
    The requested URL /gcm_chat/v1/chat_rooms was not found on this server.

    Apache/2.4.7 (Ubuntu) Server at ec2-XX-XXX-XXX-XXX.compute-1.amazonaws.com Port 80

    I have tried changing permissions of my virtual host… My full dir to the project is /var/www/html/gcm_chat. I am using a default install of apache2. I haven’t been able to observe any php errors.

    Help?

    • Rinku Meena

      use url /gcm_chat/v1/index.php/user/login and it will work

  • Hamdi wanis

    hey ravi i used hostinger to host the server side and i made sure it has mysqlnd enabled but i still get Call to undefined method mysqli_stmt::get_result() ? any ideas?

  • Pankaj Lagad

    Hi ravi I got the following errors,

    //when sent the message from our device to chat room(Material Design)

    02-20 14:02:04.216 26053-26053/? E/ChatRoomActivity: endpoint: http://192.168.42.102/gcm_chat/v1/chat_rooms/1/message
    02-20 14:02:04.261 682-682/? E/RemoteViews: ANR Warning,RemoteViews can only be used once ,if not ,it may cause ANR in hosts such as Laucher,SystemUI. keys for search
    02-20 14:02:04.264 26053-26287/? E/ChatRoomActivity: Params: {message=haha, user_id=20}
    02-20 14:02:04.266 682-682/? E/RemoteViews: ANR Warning,RemoteViews can only be used once ,if not ,it may cause ANR in hosts such as Laucher,SystemUI. keys for search
    02-20 14:02:04.333 26053-26053/? E/ChatRoomActivity: response: {“error”:true,”message”:”Failed send message”}

    whats going wrong… I also can’t sent the massage to single user

    reply soon..

  • Alexandre Queiroz

    thank you, you does a great job

    • You are welcome. Follow the other two parts too.

  • Yaqoub Alsaadi

    brother Ravi Tamada

    thanks aloot
    i need your help to upload php files to 00webhost….

    waiting you brother

    • Hi Yaqoub

      This app won’t work on 000webhost because of the limitations. 000webhost won’t support mysqlnd.

      • Yaqoub Alsaadi

        thank you Ravi
        is there any way to use web server ?

        • Please try to host the services on to 000webhost. Once done you can see the errors in the log when accessing the urls. Then I can tell you what to do exactly.

          • Yaqoub Alsaadi

            now i face this :-
            Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/a1657826/public_html/gcm3/demo.php on line 24

          • Your webhosting is not supporting mysqlnd. You have to convert all the mysqli statements to PDO.

          • Yaqoub Alsaadi

            thanks Ravi
            I have no idea in php…

          • Alankrita

            Instead of get_result(), you could use this method :

            function get_result( $Statement ) {
            $RESULT = array();
            $Statement->store_result();
            for ( $i = 0; $i num_rows; $i++ ) {
            $Metadata = $Statement->result_metadata();
            $PARAMS = array();
            while ( $Field = $Metadata->fetch_field() ) {
            $PARAMS[] = &$RESULT[ $i ][ $Field->name ];
            }
            call_user_func_array( array( $Statement, ‘bind_result’ ), $PARAMS );
            $Statement->fetch();
            }
            return $RESULT;
            }

            And to process the result, instead of $result->fetch_assoc()
            use – array_shift( $RESULT )

          • Yaqoub Alsaadi

            thanks Alankrita
            i did what you said but i get this

            Warning: Invalid argument supplied for foreach() in /home/a1657826/public_html/gcm3/index.php on line 212

            could i contact by your email??

          • Alankrita

            You have to edit three files : demo.php, v1/index.php and db_handler.php

            In demo.php :

            public function getAllChatRooms() {
            $stmt = $this->conn->prepare(“SELECT * FROM chat_rooms”);
            $stmt->execute();
            //$stmt->store_result();
            $RESULT = get_result( $stmt );
            $stmt->close();
            return $RESULT;
            }

            public function getAllUsers() {
            $stmt = $this->conn->prepare(“SELECT * FROM users”);
            $stmt->execute();
            $RESULT = get_result( $stmt );
            //$tasks = $stmt->fetch();
            $stmt->close();
            return $RESULT;
            }

            In db_handler.php

            // fetching all chat rooms
            public function getAllChatrooms() {
            $stmt = $this->conn->prepare(“SELECT * FROM chat_rooms”);
            $stmt->execute();
            // $tasks = $stmt->get_result();
            $tasks = get_result( $stmt );

            $stmt->close();
            return $tasks;
            }

            // fetching single chat room by id
            function getChatRoom($chat_room_id) {
            $stmt = $this->conn->prepare(“SELECT cr.chat_room_id, cr.name, cr.created_at as chat_room_created_at, u.name as username, c.* FROM chat_rooms cr LEFT JOIN messages c ON c.chat_room_id = cr.chat_room_id LEFT JOIN users u ON u.user_id = c.user_id WHERE cr.chat_room_id = ?”);
            $stmt->bind_param(“i”, $chat_room_id);
            $stmt->execute();
            // $tasks = $stmt->get_result();
            $tasks = get_result( $stmt );

            $stmt->close();
            return $tasks;
            }

            // fetching multiple users by ids
            public function getUsers($user_ids) {

            $users = array();
            if (sizeof($user_ids) > 0) {
            $query = “SELECT user_id, name, email, gcm_registration_id, created_at FROM users WHERE user_id IN (“;

            foreach ($user_ids as $user_id) {
            $query .= $user_id . ‘,’;
            }

            $query = substr($query, 0, strlen($query) – 1);
            $query .= ‘)’;

            $stmt = $this->conn->prepare($query);
            $stmt->execute();
            // $result = $stmt->get_result();
            $result = get_result( $stmt );

            while ($user = array_shift( $result )) {
            $tmp = array();
            $tmp[“user_id”] = $user[‘user_id’];
            $tmp[“name”] = $user[‘name’];
            $tmp[“email”] = $user[’email’];
            $tmp[“gcm_registration_id”] = $user[‘gcm_registration_id’];
            $tmp[“created_at”] = $user[‘created_at’];
            array_push($users, $tmp);
            }
            }

            return $users;
            }

            In v1/index.php

            /* * *
            * fetching all chat rooms
            */
            $app->get(‘/chat_rooms’, function() {
            $response = array();
            $db = new DbHandler();

            // fetching all user tasks
            $result = $db->getAllChatrooms();

            $response[“error”] = false;
            $response[“chat_rooms”] = array();

            // pushing single chat room into array
            while ($chat_room = array_shift( $result )) {
            $tmp = array();
            $tmp[“chat_room_id”] = $chat_room[“chat_room_id”];
            $tmp[“name”] = $chat_room[“name”];
            $tmp[“created_at”] = $chat_room[“created_at”];
            array_push($response[“chat_rooms”], $tmp);
            }

            echoRespnse(200, $response);
            });

            /**
            * Fetching single chat room including all the chat messages
            * */
            $app->get(‘/chat_rooms/:id’, function($chat_room_id) {
            global $app;
            $db = new DbHandler();

            $result = $db->getChatRoom($chat_room_id);

            $response[“error”] = false;
            $response[“messages”] = array();
            $response[‘chat_room’] = array();

            $i = 0;
            // looping through result and preparing tasks array
            while ($chat_room = array_shift( $result )) {
            // adding chat room node
            if ($i == 0) {
            $tmp = array();
            $tmp[“chat_room_id”] = $chat_room[“chat_room_id”];
            $tmp[“name”] = $chat_room[“name”];
            $tmp[“created_at”] = $chat_room[“chat_room_created_at”];
            $response[‘chat_room’] = $tmp;
            }

            if ($chat_room[‘user_id’] != NULL) {
            // message node
            $cmt = array();
            $cmt[“message”] = $chat_room[“message”];
            $cmt[“message_id”] = $chat_room[“message_id”];
            $cmt[“created_at”] = $chat_room[“created_at”];

            // user node
            $user = array();
            $user[‘user_id’] = $chat_room[‘user_id’];
            $user[‘username’] = $chat_room[‘username’];
            $cmt[‘user’] = $user;

            array_push($response[“messages”], $cmt);
            }
            }

            echoRespnse(200, $response);
            });

          • jay gandhi

            I can not understand this , you can help me what are the changes in demo.php file

          • CK

            which mysqli statements should i convert to PDO?

  • Brook Bian

    Hi Ravi,

    Chinese mobile phones don’t support google play. What else do you recommend except GCM?

  • Trey Rosius

    Hi Ravi,
    What Sofware did you use to model your database tables?It really looks presentable.

  • Sandeep

    Hi Ravi,
    There is some issue in Live Demo link, please have a look.
    http://demo.androidhive.info/gcm_chat/

    • Hi Sandeep

      What is the issue?. If you are getting some random alert messages, HACKERS … playing with the site. I’ll upload a fresh copy now.

      • Sandeep

        it is showing some alert messages and a porn image in background.

        • Shit.. 🙁 Is it ok now? I guess It should be resolved.

          • Sebastian

            Why not get msg notification when use vmware android image? But on Android Studio works fine, if I use 2 devices on Android Studio then I get only on first device msg notification… can you explain me why?

          • Tomas

            maybe google play services are not installed

          • Sandeep

            Yes, it is resolved now. Thanks.

          • Okay.

  • Marvin Collins

    hey thanks but the api can work for me getting 404

  • Marvin Collins

    come on please still getting 404 error after adding ../v1/index.php/user/login

    • Sebastian

      Use postman or not?

      • Marvin Collins

        yeah but i wanna use it on my browser it working so well with postman

        • Sebastian

          Ravi says “localhost/gcm_chat/v1 always gives 404. You need to access the final endpoint with the correct http method”

        • Browser can make http call only.

  • DON

    Hi Tavi Please i noticed you always use Slim version 2.3.5 I hope its safe to use it also considering that slim is now in version 3.2.1 ? please let me know because i need to built a RESTFUL app and i need to use Version 2.3.5 just like you. How is Srinivas Its been a while…

    • I need to check the latest Slim and verify the code once as there might be lot of function deprecated. Thanks for letting me know.

      • DON

        Ok Ravi please check so i would know which way to go because i notice that to instantiate the slim is now $app = new SlimApp(); instead of $app = new SlimSlim(); in version 2.3.5 So Please Ravi Cross check so that we can know if its safe to continue with the old one or the new one.

  • yog

    are this source codes implement xmpp conncetion ? (for upstream purpose also ? ) i want to build app which sends data from android app to chrome extension is this possible by making some changes in this codes ?

  • Kunal Agrawal

    hi ravi your tutorials are really helpful.i dont know how to code but with your code i made one good app. can u provide the codes for app invites via facebook,whatsapp etc would be very helpful for me i am struggling with it

  • David Evhade

    Ravi..thanks for this tutorial. I am having an error if I type localhost/gcm_chat.. Warning: require_once(../include/db_handler.php): failed to open stream: No such file or directory in /var/www/html/gcm_chat/index.php on line 6

    Fatal error: require_once(): Failed opening required ‘../include/db_handler.php’ (include_path=’.:/usr/share/php:/usr/share/pear’) in /var/www/html/gcm_chat/index.php on line 6. I am using LAMP on ubuntu. Any take?

    • David Evhade

      I have seen my error and have corrected the mistake..I mistakently thought v1/index.php is the same as index.php in the folder

  • FelixM

    Thank you for this work! 🙂
    I’m trying to start app on Debian8 server, but web page don’t show me messages (Sorry! Unable to fetch topic messages), while the rest shows. Can you attach php modules that which are necessary for operation of the application?

    • Lina Yahi

      I’m facing the same problem ” Unable to fech topic messages ” and I’m using Ubuntu. Could you tell me please if you resolved the issue ?

  • Rony Vidaur

    Hi Ravi, awesome tutorial, im still on this 1st part because when i’m trying to test it on postman the only thing that doesnt seem to be working properly is when i try to register a new user and i’ve make sure that i have the right credentials for the db, also i notice in the video when you first create the db theres a user already, it didnt happen with mine, any ideas?

    • Rony Vidaur

      I have solve the issue now but I dont know if this is going to affect the project works later on, what i did is modify on db_handler.php on line 28 to the following:
      $stmt = $this->conn->prepare(” INSERT INTO users (name, email, gcm_registration_id,created_at) values(?, ?,”,CURRENT_TIMESTAMP)”);

      let me know if that is going to give me an error, even thoug gcm_registration_id is going to be updated i assume

      • Kid

        How Did you solve your error? Please?

  • David Evhade

    I get this error while using this tutorial

    404 Not Found

    Not Found

    The requested URL /gcm_chat/v1/user/login was not found on this server.

    Apache/2.4.7 (Ubuntu) Server at localhost Port 80

  • Mohammad Goani

    Hi Ravi, Thanks for the Great tutorial.
    I need a little help regarding ‘demo.php’ file.
    I am getting an error :
    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/a7612275/public_html/chattesting/demo.php on line 18.
    Can u please help me with it ?

    • can

      you have to setup mysqlnd on your server

      • CK

        how do i setup mysqlnd driver on live server. I am using hostinger??

        • dhaval

          Dear
          If you are using Go daddy Hosting service,Than Follow this steps:
          Goto Control Panel > Software > Select PHP Version

          Select Version 5 >

          1. Uncheck mysqli
          2. Check mark nd_mysqli

          • Prajwal L Sirigere

            This helped me man.. 🙂

  • Jamal S

    after adding 1 message , i get this error trying to add another message from same user

    {

    “error”: true,

    “message”: “Failed send message Duplicate entry ‘0’ for key ‘PRIMARY'”

    }

    • mohamed jedidi

      just make all of the ID of database Primer key Auto Increment

      • Jamal S

        Thanks mohamed , that’s just what i did to solve it , but note that u can’t do that to the chat_rooms table primary key (chat_room_id) nor the users table (user_id) since they are both used in foreign key constraint with the messages table

        • mohamed jedidi

          Delete all the users chatroom and the message after that make the id of each table auto increment and creat Again the chatroom and it wel be ok

          • yousra

            can you help me please? iam facing problem

          • Kid

            Have a way around “oops error while registering?”

  • Karthi

    Hai Ravi,

    I implemented as you said above all working good . . .

    but i received the notification from who all r installing your application.i have to stop it,can you help me to do this . . .

    i have changed my own API key but still i received notification from all.

    Thank You 🙂

  • ankit vajpai

    Hi Ravi thanku for the tutorial , I am getting some issue while connecting to MY SQL kindly help me out,

    Error is as follows:
    Warning: mysqli::mysqli(): (HY000/1045): Access denied for user ‘gcm’@’localhost’ (using password: YES) in C:xampphtdocsgcm_chatincludedb_connect.php on line 24

    Failed to connect to MySQL: Access denied for user ‘gcm’@’localhost’ (using password: YES)

    Warning: mysqli::prepare(): Couldn’t fetch mysqli in C:xampphtdocsgcm_chatdemo.php on line 41

    Fatal error: Call to a member function bind_param() on null in C:xampphtdocsgcm_chatdemo.php on line 42

    • can

      hi! your database name and password is not same i think. check againg. you have to control database to php way

    • Murali Venkata Sri Sai Boliset

      check the password in your config file for the db connection. then the problem solved!!

  • can

    hey ravi! thanks for everything this tutorial is my best. gread and educational. i have there is question. yesterday work is great but today i have error: sorry ! unable to send message.what is that ? thank for help.

    • can

      hi guys! i am working on this tutorial. i have error : sorry unable to send mesagge. but my first mesagge work perfectly bur secont mesagge i have error. why it say error i dont understand please help me. i am working only web.

  • can

    please help me!. my first sending message is work perfectly but secont sending is not working. i have error sorry unable to send mesagge!!

  • Mat

    Guys!!!!
    Please recommend me IDE for PHP which is FREE and actually SUPPORTS code completition…
    I have tried NET beans and Eclipse but they don’t. I only managed to use visual studio with php tools but it’s a trial….

    • Use NetBeans

      • Mat

        Thanks for quick answear but it does not complite my code… Like I said only php tools for VS done the job right. Eclipse and NetBeans works fine with java code but I have non suggestions when for example typing ‘db_handler.php’ and trying to close db connection… http://imgur.com/s40MkZZ

      • Mat

        It is not working properly…
        http://imgur.com/a/uILgU

  • Mat

    Here is example: http://imgur.com/s40MkZZ

  • Gizem Gözde

    hi there! i am working in this case but i have an error. i sent firt message perfectly but i again sent later web page says: sorry unable yo send message. what is that ?

    • yousra

      me2 i face the same problem

  • Bey Abaasa

    Hello Ravi,
    Great Tutorial

    How do i solve Fatal error: Uncaught exception ‘InvalidArgumentException’ with message ‘Cannot create LogWriter. Invalid resource handle.’ in C:wampwwwgcm_chatlibsSlimLogWriter.php on line 60

    i get this when i use http://IP-ADDRESS/gcm_chat/v1/chat_rooms in postman

    Thanks

  • Sid Shehxad

    Hey Ravi hows you? Hope you fine!
    This is a great tutorial but I am having an issue when i am going to create user on postman link
    http://localhost/gcm_chat/v1/user/login.
    First time I did not get any error it creates a user but on very next time it gives me an error while registering.

    • Can Talay

      hello sid. i am not understand, where are the user/login code ? i cant find it .

      • Sid Shehxad

        Thank you :)Just done it .

        • Can Talay

          what is the problem ? how did solve this

          • Sid Shehxad

            problem was that i can only be able to create user on 0 index. i make user_id auto increment it solves my problem

  • Megha Patil

    What is chat room, can you give me an
    example

  • Thandy

    Hi Ravi,
    First of all, thanks for helping us! Your articles are the best!

    My question is about the server side: i tested the server code in my localhost (using xamp) and it worked normally then I got a free storage on Amazon, i created a instance of ubuntu 64bits server, i installed apache2, mysql, php5, phpmyadmin, i enabled mod_rewrite (a2enmod rewrite) and installed curl (I am not sure if the curl stuff is ok because i did not find “extension=php_curl.dll” in the “php.ini” am I have no idea where to find it. I already did research for that).

    But I am still getting the 404 error. Please, is there anyway to help me?

    Are you using the same digitalocean that you made a article?

    Thanks,

    • Thandy

      This is my host: http://52.34.80.163/ it already has the database working fine (it is the same that you are using on the example) and it has all the files..

  • Mansoor Jafari

    Hi Ravi
    Can I use asp.net web api instead rest api slim???

    Thank you.

  • Rizwan Khan

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/crazenat/public_html/projects/gcm_chat/demo.php on line 24 sir it will show this error when i upload it to server

  • Russell Esmedilla

    Hi Ravi, this is actually an awesome post. But I am not familiar with PHP. Can you convert the PHP into C#? Looking forward to hear from you.

    • Hi Russell

      Sorry, I am not well in c# 🙁

  • Donald Klaus Tindjiete

    hey Ravi thank you for the great tutorial…really awesome!!! by the way i want to ask is it possible to make a one to one chat this way?

  • vishal

    hello sir ,
    I got some error ,unable to fetch message topic,please resolve my issues

    • Lina Yahi

      Hi could you tell me please is you resolved the issue ? I’m facing the same problem

  • invidia

    hi

    Fatal error: Call to a member function prepare() on a non-object in

    C:xampphtdocsgcm_chatincludedb_handler.php on line

    185

  • Helmi Susanto

    hy, sir

    my project is all work well but,

    i still receive notification from http://demo.androidhive.info/gcm_chat/

    i already change the endpoint app/endpoints,

    how it could be?

    • Ratnanabh

      Hello Susanto

      I am trying to setup this project on windows based shared hosting, but I always get “unable to fetch message topic” can you please let me know what could be the issue?

      • Lina Yahi

        Hi could you tell me please if you resolved the issue ? I’m getting the same alert window “unable to fetch topic messages”

  • justDisqus

    Hi

    I get “Oops! An error occurred while registering”.

    How can this be resolved?
    Thanks

    • Pranav Sharma

      Try changing the User ID from 0 To something else manually from phpmyadmin.
      It seems every user is getting 0 as a default ID and ID being a Primary key has to be unique.

    • Shami

      Hey Just make an entry in table user….Use same username and email for login purpose….There will be no error u will have sucessfull login enjoy 🙂

    • Pranav Sharma

      I had the same problem, and I solved it by allowing NULL values in gcm_registration_id, which will probably solve your error as well. THIS IS BECAUSE WHILE CREATING A NEW USER WE ARE ONLY PROVIDING “NAME” AND “EMAIL”, which means default values for other fields and the TEXT data type doesn’t support default values

  • Ibrahim Samad

    Hi,
    Please where in the android part of the project(java) will I reference the “Google api key”?
    I don’t seem to find it anywhere.

  • suryags

    hi, ravi , when i use Advanced Rest Client in user/login i get right JSON respon but when user/chat_rooms i get 404 not found. can u help me? thanks a lot.

    • Ibrahim Samad

      user/login uses a POST request whiles user/chat_rooms uses a GET request, so check to make sure that you selected GET request in your Advanced Rest Client when using user/chat_rooms instead of POST.
      Also make sure that the spelling is exactly as you used it in the slim routes.

      • suryags

        i`m sure spell correctly. i just got eror when test the REST API in advance rest slient . but in my android studio it run without eror.
        but thank you for reply.

  • VSatya

    Hi, where should I paste these code snippets?

  • VSatya

    ravi mama cheppu konchem 😉 where should I paste these code snippets?

  • prasoon sharma

    Hello @ravi8x:disqus
    i am using PHP (not fully) code to send message on my registered device but not receiving message on device. PHP show result as
    {“multicast_id”:8550022549195779350,”success”:1,”failure”:0,”canonical_ids”:0,”results”:[{“message_id”:”0:1459795352923689%21f96bfff9fd7ecd”}]}
    can you give me an idea ? seems to be success ?

    • From the response I can see the GCM message was sent successfully but the device is not receiving it or you are not parsing it correctly. Check for the LogCat if you are having any errors.

      • prasoon sharma

        yes. you are right, app able to receive message from server as JSON object. Now i need to parse it to get the data to generate the notification. Thanks.
        I more point, when i use ‘com.google.android.gms:play-services-gcm:8.4.0’ in that case i am not able to get gcm_defaultSenderId.

  • nice tutorials

  • suryags

    what is the different between subscribeToGlobalTopic() and subscribeToAllTopics() ?
    and please explain what are “subscribe” mean in this GCM . i really dont get it.
    and how to get user id sender ? can u give me any hint please. thank you.

  • Pradhap PK

    Good job. but I got one error. Sorry! Unable to fetch topic messages
    my error link: http://newworldtechno.com/gcm_chat/intex.php
    please help me.
    please tell me which server & software you using.

    • Pradhap PK

      Dear Team. please help me.

    • Lina Yahi

      Could you tell me please if you resolved the problem ?

  • smit

    Hi ravi,
    I am getting error “n error occurred while registereing”.
    I saw few comments, i tried but didnt solve the issue. Please let me know what are the possible solutions for this error.

    • Shami

      Well i think u r getting this error on login….for login there must be a crossponding entry in database…Create an entry in user table use same email and username then there will be no error enjoy 🙂

  • Visu mani jones vjm

    Sorry Unable To Send The Message –this alert pops up when i click send to Topic What is Wrong Any Help?

  • manish singla

    During testing v1/user/login in postman, i got this error “Email address is not valid” please help

  • Milan Gajera

    Where is login inside the v1 in you directory structure?

  • Amir

    your download page not working. It sends me to login screen and then i try to subscribe . it keeps telling me that it sent an email to confirm while nothing comes to my inbox

  • Tobi

    Hello, i am at the step to test the push notification. I use, like you explain, the push_test.php site. But it does not work. i get the Message ” Sorry! Unable to send message”. If i check that with browser developer tools i saw the error
    jquery-2.2.0.min.js:4 POST http://sitename.com/gcm_chat/v1/users/push_test 404 (Not Found)

    Did you or someone have a hint for help me with that error?
    Hopefully,
    Thank you,
    Tobi

  • Hm, sorry, can’t find method for creating any “chat_rooms” rows in database in backend code. Can you show me or tell where is it?

  • Muhamad Kautsar

    how to make it online?

  • Tobi

    HEllo Ravi,
    any Idea with my problem that i posted 4 days ago? For me it looks like that there is no push_test inside the Rest API.

  • Anna Pikalova

    What’s wrong?I tried everything what was recommended but it is still not working.Please, help me with it!
    “error”: true,

    “message”: “Oops! An error occurred while registereing”

    • Tobi

      are you try it with A REST API Test tool like “Postman”?
      there you should use the url http://your_Server/gmc_chat/v1/user/login
      than you must hand over two keywords “name” and “email” and use POST methode. that should work
      Tobi

      • Anna Pikalova

        Postman gives me this error, when I try to registrate new user. And I’ve done everything what you sad before.

        • Tobi

          in Postman, have you swich to “Body” and there you insert the keywords or did you click on the “Params” Button and hand over the Keys there?
          The Params-Button is the wrong location, thats wy i ask. And i run into the same problem.

          • Anna Pikalova

            I use “Body” and keywords…Do you have any idea what i need to do?

          • Tobi

            when i was still using localhost-environment i got the same problems, after i switch to a webhoster this “registering” Error gone away. What are you using? a WAMP server or comparable or a “real” webhoster?

          • Anna Pikalova

            I’m using WAMP server. So if I want this chat working, I need a webhoster?

          • Tobi

            I feared it. with a local installation i got the same problem and my only solution was to switch to a webhoster. Sorry Anna, i think i cant help you,
            because I was also failed with WAMP.

          • Anna Pikalova

            Thanks, any way. I decided to switch to a webhoster, could you help me if I have problems?

          • Tobi

            hi, i can try to help you. i have additional questions to Ravi because i have also problems and it looks like that Ravi have not enought time to answer all questions. maybe we both can bring that solution to an running one. 🙂

          • Anna Pikalova

            How can I contact you when questions appear?

          • Anna Pikalova

            It starts working, but it didn’t “PUT” a gcm_registration_id while testing in Postman(syntax error). Did you have this problem?

          • Tobi

            Hello Anna,
            for updating the gcm_registration_id you need the id of the user.
            gcm_chat/v1/user/23
            then use body again but there not form-data, for this you must switch to x-www-form-urlencoded

          • Anna Pikalova

            I’ve done this, but it isn’t working.Postman gives “Syntax error”

          • Tobi

            it sounds like there is something wrong with your php files. because syntax error is no feedback from the rest api i think. ok, lets go step by step.
            first you have register a user
            in your database you have an entry for the user, with name, id and an empty gcm_registration_id field
            then you try to update the gcm_registration_id field for this User, using /v1/user/ID and in als key you use “gcm_registration_id” an as value some characters. and then you got the answer from postman “syntax error” ?
            or do you have some more text in this error message?

          • Tobi

            you can contact me directly :tobirobi at gmx dot de

          • Anna Pikalova

            Yes,you are right!Only “Syntax error”

          • Tobi

            Good Morning Anna, maybe it will be helpfull if you send me your files, then i can check it directly?

    • Pranav Sharma

      I had the same problem, and I solved it by allowing NULL values in gcm_registration_id, which will probably solve your error as well. THIS IS BECAUSE WHILE CREATING A NEW USER WE ARE ONLY PROVIDING “NAME” AND “EMAIL”, which means default values for other fields and the TEXT data type doesn’t support default values.

  • Nishit Chhatrala

    Not showing notifications in recyler viee nor
    in notification bar

  • Rana Saqib Manj

    very nice tutorial .. but I have a question….. I have done all work and show my “localhost/gcm_chat” but problem is that when I am open gcm_chat then dialog is open “Sorry ! LocalHost Says ! unable to fetch topic message” why ??
    When I am using Postman… Postman not show me the right language in result ….. show me this
    ” �+z4�ܧ����&��a(����M�*���։O-_��5T�Y�Q�|��3Hv��5�k �,���� �_�%��(-�9
    Ì”
    I am so confused plz help me !!!!!!

    • Lina Yahi

      I’m facing the same problem ” Unable to fech topic messages . Could you tell me please if you resolved the issue ?

      • Rana Saqib Manj

        No Dear !! same issues …….

      • Make sure you have mysqlnd installed

  • Tobi

    hello, can someone tell me how to work with the push_test.php? Even if i try to send a notification to the android app i got an “sorry! unable to send message”. And i dont know where to start with error searching. i hand over the API Key, gcm_registration_id and a message, but every try i got this error.

  • Jesualdo Flores Alvarado

    Thank you, so much. It helps me a lot.

    God bless you.

  • imran

    Uncaught Error: Call to a member function prepare() on null in C:Apache24htdocsgcm_chatdemo.php:34 Stack trace: #0 C:Apache24htdocsgcm_chatindex.php(9): Demo->getDemoUser() #1 {main} thrown in C:Apache24htdocsgcm_chatdemo.php on line 34

    plz help me out

    • Nitendra

      you need to change php.in file in C:xamppphp folder…you get solution on youtube also

  • imran

    Warning: mysqli::__construct(): MySQL server has gone away in C:Apache24htdocsgcm_chatincludedb_connect.php on line 19

  • Rahmi Amalia

    @ravi8x:disqus
    Great tutorial. The code work fine for me and I try to add new chat room but always fail inserting new chat room into database. I’m adding new coloum user_id.
    Here is my code

    public function createChatRoom($name, $user_id) {

    $response = array();

    if (!$this->isRoomExists($name)) {

    $stmt = $this->conn->prepare(“INSERT INTO chat_rooms (name, user_id) values(?, ?)”);

    $stmt->bind_param(“si”, $name, $user_id);

    $result = $stmt->execute();

    $stmt->close();

    if ($result) {

    $response[“error”] = false;

    $response[“chat_rooms”] = $this->getChatRoom($user_id);

    } else {

    $response[“error”] = true;

    $response[“message”] = “Oops! An error occurred while creating chat room”;

    }

    } else {

    // User with same email already existed in the db

    $response[“error”] = false;

    $response[“chat_rooms”] = $this->getChatRoom($user_id);

    }

    Any suggestion?

  • PR_DIMPU

    while registering(user/login) second record am getting an error but if i enter the same email am able to login can anyone please help me

    • Thato Rammoko

      make sure you enable auto increment in your database

      • PR_DIMPU

        Thank you so much @thatorammoko:disqus.Error got resolved

        • Thato Rammoko

          Pleasure Praveen.

      • Sherlock holmes

        auto increment of what ?

  • invidia

    hello, can someone tell me how to work with the push_test.php? Even if i try to send a notification to the android app i got an “sorry! unable to send message”

  • @ravi8x:disqus Hi I am having Host gator and i placed my php files for sending gcm notification there. But i am not able to run the curl , am getting- Curl failed: Failed to connect to android.googleapis.com port 443: Connection timed out. Any idea why?

  • Md. Jannatul Nayeem

    Warning: Unexpected character in input: ” (ASCII=92) state=1 in /var/sites/m/mysubdomin.elishbazar.com/public_html/v1/index.php on line 9

    Warning: Unexpected character in input: ” (ASCII=92) state=1 in /var/sites/m/mysubdomin.elishbazar.com/public_html/v1/index.php on line 9

    Parse error: syntax error, unexpected T_STRING in /var/sites/m/mysubdomin.elishbazar.com/public_html/v1/index.php on line 9

  • Lina Yahi

    Hello can someone tell me why am I having an alert “unable to fetch topic messages ” ?
    Everything works fine with Postman, I don’t understand where the problem is.
    Than you for your help

  • sikandar

    hello sir first of all thank u for the post. but sir my doubt is will it work on real server like hostinger or byethost

    • kamran bhatti

      it worked on local host as well. i have tested it!

      • Aayush Bedi

        I am facing problem in creating a new user. Rest is working fine.

  • Rubin Luiz

    Hi there Ravi!
    Thank you so much for posting this precious material!

    Well, I receive the following error when testing “/chat_rooms”:

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/u465687782/public_html/gcm_chat/include/db_handler.php on line 165

    It seems to be something related to a drive but I’m hostinger.com.

    Help me plz,,

    • You need to install mysqlnd drivers.

      • CK

        Hai Ravi, I have the same isuue. I thought Hostinger already has mysqlnd drivers pre instaled. since it doesnt, how can I install mysqlnd drivers on hostinger? or on webhost? or do you know any free hosts that already supports mysqlnd drivers?

      • I am also having the same problem. Can you please convert it to PDO?

      • Saurabh Bhat

        but when i saw the php info in Hostinger it shows mysqlnd driver is enabled

  • Arijit Nayak

    Hiiii,
    Can any1 help me am facing ds issue “Failed send message Field ‘message_id’ doesn’t have a default value” ”

    Help me plzz !!!!

    • Lia

      Hi Arijit Nayak , I am facing the same issue and even if I tried in multiple ways to fix it i am still not able to do that. Did you find a way to resolve the issue and would you be kind to share it with us? 😀 Thanks!

  • Durgesh Pawar

    Didn’t getting any notification sign and sound on topics???help plzzzz

  • Hi Ravi, thanks a lot for writing this post ! Followed every instruction and step mentioned in the post, works perfectly after executing it !! I request you to please write a post on Implementing GCM Network Manager on Android, it would be really great of you !! https://developers.google.com/cloud-messaging/network-manager

  • Pranav Sharma

    Hey Ravi, Amazing tutorial man, works like a charm EXCEPT FOR A FEW ERRORS……!!!! 🙂 😀
    The ERRORS, I suppose many people encountered the same problems of “An error occured while registering”.
    I finally solved it by allowing NULL values in gcm_registration_id, because mysql doesn’t allow a default value for the TEXT fields, and while registering a user, we are only providing the name and email values, which gives an error.

  • Elvis Chidi-Ezeama

    Thanks a million for this wonderful app, please sir how do get the app to save the chats and not reload them everytime I open a chat room, thanks in anticipation

    • Alejandro Leon Maceda

      did you figure out how ?

  • Pankaj Savaliya

    Hello
    This is simple best way for simple chatting.but if we go through instant send,tying,online,and all function does not handle by GCM,so i hope you have also make it by use of other framework like Xampp.
    Thanks

  • Bogdan Tudorascu

    Nice tutorial. Is this the best approach for instant messaging(online status, files, etc.) or should I look at XMPP? I mean, I really like GCM, it’s simple and straightforward, but is it reliable enough to use as a chat and not only for notifications?

    • Use XMPP.

      • Bogdan Tudorascu

        Should I still keep storing everything in my database and use openfire(XMPP) just for chatting?

        • Yes, you can. Normally a fully functional chat app can be accomplished by combining multiple techs together.

      • mounty 4all

        @Ravi may i ask you the application used in sketching your diagrams? Thanks.

  • Meenakshi

    please guide me if there is any implementation using xmpp protocol.

  • Harpreet Singh

    Hi,Ravi
    I want to know that the server url for registering on gcm would be the exact path where my sevice is kept or only main server url can work??

  • Wysnu

    any idea for fcm?

  • Serhat Ömer RENÇBER

    hi ravi,

    when you send message to anyone, another user is getting message at Any active Windows(rooms)

    i am trying this code. i can not do. getting message should go to correct rooms. we should check chat_room_id

    pls help.

    NotificationUtils.java
    if (activeProcess.equals(context.getPackageName())) {

    // .

    try {
    Method m = activeProcess.getClass().getMethod(“isRoomId”,null);
    Toast.makeText(context.getApplicationContext(), m.toString(), Toast.LENGTH_SHORT).show();

    if (chatRoomId.equals(m.toString()))
    {
    isInBackground = false;

    }
    } catch (NoSuchMethodException e) {
    e.printStackTrace();
    }

    // isInBackground = false;

    }
    }

  • Serhat Ömer RENÇBER

    i added new method at ChatRoomActivity.java
    public String isRoomId()
    {
    return chatRoomId;
    }

  • mufumbo

    Hi Ravi, just a heads up, you might want to update your code to work if the user has multiple devices.

  • mh

    Hi Ravi application work so good you really did perfect job but can i ask you about the notification when i receive it on mobile the title of it above the messages is ” google cloud messaging ” how can i change it i really search a lot but can’t find from where

  • LGL

    Boy this is a lot of code

  • Dnyaneshwar more

    its not working for multiple users for me.can any one help me.is there any special format of array to send the registration ids?

  • Amirhosein barati

    hi , I am getting an error please help. Thanks

    first login (registration) ->
    LoginActivity: params: {email=xxx@xxx.xxx, name=xxx}
    LoginActivity: response:
    Google Cloud Messaging 3.0 | AndroidHive
    ….


    var user_id = ‘0’;$(document).ready(function () {getChatroomMessages($(‘#topics li:first’).attr(‘id’));$(‘ul#topics li’).on(‘click’, function () {$(‘ul#topicsli’).removeClass(‘selected’);$(this).addClass(‘selected’);getChatroomMessages($(this).prop(‘id’))});
    …..

    please help

  • Hi there bro, one question, can I send media files (such as video clips, pdf or jpeg) using this app ?

  • Raja R

    hi, tnk you for this code …i cant login …can u tel me ..pls very urgent ….

  • Alejandro Leon Maceda

    Somebody know whats going on this error?
    Fatal error: Call to a member function bind_param() on boolean in /home/j5000440/public_html/chat/demo.php on line 42

    • Alejandro Leon Maceda

      Forget it, Its Working now http://chat.lecheando.com/

      • Prajwal L

        i have the same issue, how did u clear that?

        • Alejandro Leon Maceda

          The error was in the database connection.

  • Abhi Shewale

    i am unable to import these classes then i how do please tell me…

    InstanceID
    GcmPubSub
    InstanceIDListenerService
    GcmListenerService

    please help me to get out from this problem….

    • Alejandro Leon Maceda

      Get the LATEST android studio

  • Alejandro Leon Maceda

    Thank you so much Ravi Tamada, Your example is working fine in my host: http://chat.lecheando.com/
    The app: http://chat.lecheando.com/app-debug.apk

    COMMENTS:
    Your code-page have some error: Update database file for AUTO-INCREMENT in webpage
    Add ORDER BY message id on sql fetch messages chat room

    • Ronaldo

      How you did this ? Using GCM or FCM ? because there is no more GCM ? how am i supposed to use FCM ? With MySQL ? or Firebase ?

      • You can have your own server with MySQL and use Firebase to send notifications. Check the firebase pricing plans of data storage.

  • Tell me one thing, I can receive message from web.. but when i send msg from mobile to web, It store in db but does not show instantly..

    • Alejandro Leon Maceda

      Because the web version its no a chat real time, its like a dashboard only

  • Raja R

    getting volley error …anybody ..pls tel me ….changed ip address in EndPoint.class also..

  • Raja R

    from last week onwards i m asking ..no one reply?

  • kushagra

    What changes or settings do I have to made for the IIS server ?

  • Test Account

    Hi Ravi,

    i’m unable to register user through this link:

    http://localhost/gcm_chat/v1/user/login

    response is:
    {
    “error”: true,
    “message”: “Oops! An error occurred while registereing”
    }

    i’m new to php and android, i think gcm_registration_id is not passed in php.

    Please help me.

    I have made all changes, now all ids (user_id,message_id and chat_room_id) are auto_increment.
    problem is still existing..
    i guess error may take place at createUser function which is taking only 2 parameters ($name, $email) then what about gcm_registration_id..from where its come from in table?
    please please help.

    • Alejandro Leon Maceda

      Delete table and create again with AUTOINCREMENTAL in ID users, messages, topics etc

      • Test Account

        I have made all changes, now all ids (user_id,message_id and chat_room_id) are auto_increment.
        problem is still existing..
        i guess error may take place at createUser function which is taking only 2 parameters ($name, $email) then what about gcm_registration_id..from where its come from in table?
        please please help.

        • Muhammad Mustafa

          Only user_id in user table is going to be AUTO INCREMENT.. and function takes two parameters only there is no error about this.. http://localhost/gcm_chat/v1/user/login
          go to the following url on postman and write name and email in body tab and gcm_registration_id in header tab…

        • Kid

          Did you solve this one?

      • Kid

        Can you send the source code? for the table, still on the same problem
        Thanks, Leon

  • Test Account

    Hi Ravi,

    i’m unable to register user through this link:

    http://localhost/gcm_chat/v1/user/login

    response is:
    {
    “error”: true,
    “message”: “Oops! An error occurred while registereing”
    }

    i’m new to php and android, i think gcm_registration_id is not passed in php.

    Please help me.

    I have made all changes, now all ids (user_id,message_id and chat_room_id) are auto_increment.
    problem is still existing..
    i
    guess error may take place at createUser function which is taking only 2
    parameters ($name, $email) then what about gcm_registration_id..from
    where its come from in table?
    please please help.

    • Muhammad Mustafa

      Only user_id in user table is going to be AUTO INCREMENT.. and function takes two parameters only there is no error about this.. http://localhost/gcm_chat/v1/user/login
      go to the following url on postman and write name and email in body tab and gcm_registration_id in header tab..

  • Suraj Prajapati

    Thank you!

  • Ashok Kumar

    Volley=null………..error coming , what to do ?

  • Lucas Henrique

    I had a issue.

    the message appears when I was following the video….. “Oops! An error occurred while registereing”.
    What do i have to do?

  • leesang

    Volley=null .error coming , what to do ?

  • Nitendra

    Thanx a lot Mr.Ravi….for this nice project
    i got this error “Volley Error = null” plz help me.when i try to send message this error appear .

    • leesang

      I think Android 6.0 release removes support for the Apache HTTP client.

  • Mehul Vaghela

    sir plzz help me i got these Error : ” Additionally, a 501 Not Implemented error was encountered while trying to use an ErrorDocument to handle the request.”

    any one have idea about these…. help me

  • M R S

    for people who still have error null or the “Oops! An error occurred while registereing” error.
    open EndPoints class inside app package
    just Make sure you add your IP adress (“http://IP adress/gcm_chat/v1”).
    then

    Delete used data base .
    Create new data named gcm_chat.
    then add this query inside the new data(AUTO_INCREMENT and PRIMARY KEY added)

    CREATE TABLE `chat_rooms` (
    `chat_room_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `name` varchar(100) NOT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `messages` (
    `message_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `chat_room_id` int(11) NOT NULL,
    `user_id` int(11) NOT NULL,
    `message` text NOT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    CREATE TABLE `users` (
    `user_id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    `name` varchar(255) NOT NULL,
    `email` varchar(255) NOT NULL,
    `gcm_registration_id` text NOT NULL,
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    ALTER TABLE `messages`
    ADD KEY `chat_room_id` (`chat_room_id`),
    ADD KEY `user_id` (`user_id`),
    ADD KEY `chat_room_id_2` (`chat_room_id`);

    ALTER TABLE `users`
    ADD UNIQUE KEY `email` (`email`);

    ALTER TABLE `messages`
    ADD CONSTRAINT `messages_ibfk_3` FOREIGN KEY (`chat_room_id`) REFERENCES `chat_rooms` (`chat_room_id`),
    ADD CONSTRAINT `messages_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE;

    • Dexter Fury (Kombat Zone)

      Thanks alot it worked

  • Ramose

    Got “Volley error : null”

    • Mehul Vaghela

      Check your connection is established well! did you write

      permission!?

  • Mehul Vaghela

    sir i have problem with getting message. all message will get by particular user they create their own block.. I’m not getting Message Orderwise What to do sir ?help me..!

  • Hello, Ravi
    I love your awesome demo videos.
    I really wonder how to make this demo videos.
    Please let me know what kind of mirroring tool you use.

  • Sarthak

    Can we send customised messages using gcm like a question with 4 options to a group and getting there response to that particular question.?
    In simple terms a real time voting app using gcm

    • Yes, It is upto you what data you send in push notification.

  • Muqshid Mohamed

    Hi,

    What are the changes to be done to migrate from GCM to FCM and if we migrate to FCM is MySQL db is needed ?

  • Ceyhun Mamedov

    Hİ,
    Php gives me error. I did everything but rest api php testing does not work. I tried with Postman application but gives error.

    • What is the error?

      • Ceyhun Mamedov

        Slim Application Error
        body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}

        Slim Application Error
        The application could not run because of the following error:
        Details

        Type: ErrorException

        Code: 2

        Message: mysqli::mysqli(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES)

        File: C:wamp64wwwgcm_chatincludedb_connect.php

        Line: 22

        Trace
        #0 [internal function]: SlimSlim::handleErrors(2, ‘mysqli::mysqli(…’, ‘C:\wamp64\www\g…’, 22, Array)
        #1 C:wamp64wwwgcm_chatincludedb_connect.php(22): mysqli->mysqli(‘localhost’, ‘root’, ‘root’, ‘gcm_chat’)
        #2 C:wamp64wwwgcm_chatincludedb_handler.php(17): DbConnect->connect()
        #3 C:wamp64wwwgcm_chatv1index.php(25): DbHandler->__construct()
        #4 [internal function]: {closure}()
        #5 C:wamp64wwwgcm_chatlibsSlimRoute.php(436): call_user_func_array(Object(Closure), Array)
        #6 C:wamp64wwwgcm_chatlibsSlimSlim.php(1307): SlimRoute->dispatch()
        #7 C:wamp64wwwgcm_chatlibsSlimMiddlewareFlash.php(85): SlimSlim->call()
        #8 C:wamp64wwwgcm_chatlibsSlimMiddlewareMethodOverride.php(92): SlimMiddlewareFlash->call()
        #9 C:wamp64wwwgcm_chatlibsSlimMiddlewarePrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
        #10 C:wamp64wwwgcm_chatlibsSlimSlim.php(1254): SlimMiddlewarePrettyExceptions->call()
        #11 C:wamp64wwwgcm_chatv1index.php(383): SlimSlim->run()
        #12 {main}

        • Check your MySQL username, password and database name.

          • Ceyhun Mamedov

            With your WampServer?

          • You need to keep correct mysql details in config.php

            Check 5. Creating PHP REST API point.

          • Ceyhun Mamedov

            Former errors solved thank you.

  • AI DA

    Hi, i’m having problem on setting up the console using GCM….i’m using XAMP not WAMP can this app still work??

    • AI DA

      Warning: mysqli::__construct(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:xampphtdocsgcm_chatincludedb_connect.php on line 24
      Failed to connect to MySQL: Access denied for user ‘root’@’localhost’ (using password: YES)
      Warning: mysqli::prepare(): Couldn’t fetch mysqli in C:xampphtdocsgcm_chatdemo.php on line 41

      Fatal error: Uncaught Error: Call to a member function bind_param() on null in C:xampphtdocsgcm_chatdemo.php:42 Stack trace: #0 C:xampphtdocsgcm_chatindex.php(9): Demo->getDemoUser() #1 {main} thrown in C:xampphtdocsgcm_chatdemo.php on line 42

      • Wajid Ali

        in the include folder open db_connect.php in notepad.
        replace DB_PASSWORD with ”
        and it would be working fine

        • Dexter Fury (Kombat Zone)

          This didn’t work for me

      • Dexter Fury (Kombat Zone)

        If you find a fix please let me know i have same error

  • VINEET KUMAR

    Hello,

    unable to download the source code
    please help

  • Saad Khan

    i am unable to download slim from your site i.e. api.androidhive.info/Slim.zip. When i import it from github link. I am getting this error. Class ‘SlimExceptionStop’ not found

  • Ahmet ATICI

    Hi Ravi Selamun Aleykum

    I got error this app.. I run with wamp server on localhost but when I create my web server Database and run I got error this code

    function getChatroomMessages(id) {
    $.getJSON(“v1/chat_rooms/” + id, function (data) {
    var li = ”;
    $.each(data.messages, function (i, message) {
    li += ” + message.user.username + ” + message.message + ”;
    });
    $(‘ul#topic_messages’).html(li);
    if (data.messages.length > 0) {
    scrollToBottom(‘msg_container_topic’);
    }
    }).done(function () {

    }).fail(function () {
    alert(‘Sorry! Unable to fetch topic messages’);
    }).always(function () {

    });

    Help me please

  • I am not able to download the source code and in the demo page there is a xss problem…

  • Sabarish Don

    “Failed send message Cannot add or update a child row: a foreign key constraint fails (`gcm_chat`.`messages`, CONSTRAINT `messages_ibfk_3` FOREIGN KEY (`chat_room_id`) REFERENCES `chat_rooms` (`chat_room_id`))” .How to fix this error
    help me

    • Sabarish Don

      reply fast

  • Abhi

    I am getting this error on POST method with “login” command
    Pot “Message” is working but on”login” method the user is not created but I get this error

    “error”: true,
    “message”: “Oops! An error occurred while registereing”

    • Abhi

      Deleted the gcm_chta database.
      created new with auto incremented ID’s
      followed all the below possible routines.
      still the same error

      • SeungJun Jung

        chagne a line in db_handler.php …

        // insert query
        $stmt = $this->conn->prepare(“INSERT INTO users (name, email, gcm_registration_id) VALUES (?, ?, ”)”);
        $stmt->bind_param(“ss”, $name, $email);

        ->It seems mysql.5.x does not automatically handle non-default-set string (which is NOT NULL) to ”

        • Dexter Fury (Kombat Zone)

          What do you we change what in that line? am having same problem

  • bhavin chauhan

    @ravi8x:disqus Hi, I have download code. Integrated with php. When I send data to login API it’s sending part is perfect but return json have some extra warning. I don’t have an experience of php, So Can you please help me to solve this issue.
    Strict Standards: Redefining already defined constructor for class SlimHelperSet in G:wampwwwgcm_chatlibsSlimHelperSet.php on line 72
    Strict Standards: Redefining already defined constructor for class SlimLog in G:wampwwwgcm_chatlibsSlimLog.php on line 304
    {“error”:false,”user”:{“user_id”:35,”name”:”Bhavin”,”email”:”email@gmail.com”,”created_at”:”2016-10-04 16:23:41″}}

    • If you see error_reporting() called in my code, comment it and try.

      • bhavin chauhan

        @ravi8x:disqus Thanks for reply. Now it’s working fine.

  • Shankar Johnny

    Thanks for this tutorial also sir .. completed 1st part successfully and when i launch the project localhost/gcm_chat it opens well and i get error popup saying , sorry!unable to fetch topic messages, is it normal in 1st part sir ? thanks 🙂

    • You might be having some php errors. Enable PHP error reporting and see what errors you are getting.

      • Shankar Johnny

        i got these sir in php_error.log . [05-Oct-2016 15:52:55 UTC] PHP Stack trace:

        [05-Oct-2016 15:52:55 UTC] PHP 1. {main}() C:wamp64wwwgcm_chatv1index.php:0

        [05-Oct-2016 15:52:55 UTC] PHP Fatal error: require(): Failed opening required ‘.././libs/Slim/Slim.php’ (include_path=’.;C:phppear’) in C:wamp64wwwgcm_chatv1index.php on line 7

        [05-Oct-2016 15:52:55 UTC] PHP Stack trace:

        [05-Oct-2016 15:52:55 UTC] PHP 1. {main}() C:wamp64wwwgcm_chatv1index.php:0

      • Shankar Johnny

        Also there is no email id sir on the panel, admin’s email id like that , it is also empty for single, multiple email id message boxes 🙁

  • IGO 247

    Hello sir,
    Thanks for this really nice tutorial. In my app along with the simple chatting i want to add voice calling and video calling feature. Can you suggest what is the best way to do that?

    Thanks…

    • Voice & video calling entirely works on different protocols.

    • Ahana

      As your above comment this tutorial is really work for you ..but i got an error can u please provide me same coding step by step coding on video tutorial ..please provide me with starting at the end .it such a big thing for me ..but provide soon as soon possible on ahanasony8@gmail.com

  • Murthy Varanasi

    @ravi8x:disqus thanks for the code.withou using android can we just use the php code to generate push message to single user or is the device manadatory

    • How will you send message if there is no device. If you want you can support other platform like web too where you can send message to browser.

  • farheen moin

    from where the gcm_registration_id came in table,i failed too understand,please help.

    • If you check 2nd part of this series, in MyInstanceIDListenerService.java the token is sent to server in onTokenRefresh() method using GcmIntentService.class

  • Oberlin Lingga

    hello ravi,
    i am from indonesia.

    after login, i get some error,
    Json parse error : Value < br of type java.lang.String cannot be converted to JSONObject.

    how i can fix it?
    thanx

    • You have errors in php project. Use Chrome Postman to make request to urls and check the errors.

      • Oberlin Lingga

        Fatal error: Call to undefined method mysqli_stmt::get_result() in
        /home/u790504072/public_html/gcm_chat_server/include/db_handler.php on line
        165

        code on line 165
        $tasks = $stmt->get_result();

        can u fix it?

        thanx

        • Enable mysqli in apache config.

          • Oberlin Lingga

            i can’t edit apache on my server.
            i use hostinger to run project.

            i only copy and paste source code to my server in hostinger.
            please help me

          • Then you need to find another hosting that supports mysqli or convert all the mysqli functions to PDO statements in php.

            https://mediatemple.net/community/products/dv/204642990/why-can't-i-connect-to-my-mysql-database-from-php

          • Oberlin Lingga

            thanks for your solution, i will try to convert to PDO

          • Cool

          • Oberlin Lingga

            I also had to download and install APK examples in my phone, after I login list chat room can show, but i try to run source code from android studio, i got some error, list chat room not show. I am sure you also use the server for this application.

            i am sorry for my english, because i can speak english very well 🙂

          • farhan sajid

            i have enabled mysqli but this error is not solving please help

      • Oberlin Lingga

        here is full script for chat rooms
        // fetching all chat rooms
        public function getAllChatrooms() {
        $stmt = $this->conn->prepare(“SELECT * FROM chat_rooms”);
        $stmt->execute();
        $tasks = $stmt->get_result();
        $stmt->close();
        return $tasks;

  • saurabh sarpotdar

    now GCM is upgraded to Firebase CM…what changes will be needed now..?

    • Nothing much. On server side the json format which is sent to FCM server along with endpoint and API Key. On android side, the message receiver and json parsing.

      Check the FCM article here
      http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

      • saurabh sarpotdar

        yes…doing it now..with FCM…will post there if there is any question…

        • Okay.

          • saurabh sarpotdar

            this is completely off topic but I still find it difficult to understand how to make request to APIs and how to parse the response…for example I need to work with Betaface face detection API..but I just don’t get it…how to make request to it to ul new image and all…where can i read about it..? I am trying to follow their docs regarding their API but I guess my basics abt this is not that good…so I want to start from scratch about APIs..plus can u just check it out and tell me how to use Chrome postman to make request to that Betaface api..?

          • You need to learn how to make http requests first. Learn the basic json parsing here
            http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

            Then use Retrofit to proper integration of json parser
            http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

            Learn how to build rest api
            http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/

          • saurabh sarpotdar

            okk..will do that..plus one more thing..if I want to ul an image on Betaface api…can I do that using postman.? means where should i store the image on computer or what path should I give in Post method in postman.?

          • Install WAMP server to create a localhost environment.

          • saurabh sarpotdar

            how to pass image data in an array.. like in this json request…can u just tell me what image[] exactly is..and what to add in it when making request to add new image.. following is the example json request for UploadImage() method..
            {
            “api_key”:”String content”,
            “api_secret”:”String content”,
            “detection_flags”:”String content”,
            “image”:[81,
            109,
            70,
            122,
            90,
            83,
            65,
            50,
            78,
            67,
            66,
            84,
            100,
            72,
            74,
            108,
            89,
            87,
            48,
            61],
            “image_base64″:”String content”,
            “original_filename”:”String content”,
            “url”:”String content”
            }

            below is for UploadNewImage_File

            {
            “api_key”:”String content”,
            “api_secret”:”String content”,
            “detection_flags”:”String content”,
            “imagefile_data”:[81,
            109,
            70,
            122,
            90,
            83,
            65,
            50,
            78,
            67,
            66,
            84,
            100,
            72,
            74,
            108,
            89,
            87,
            48,
            61],
            “original_filename”:”String content”
            }

            what exactly to pass in image[] and imagefile_data[] in both cases.?

        • Sonagara Shailesh

          hello, can your share your code after changes ?. only selected file which you changed.

  • waseem93

    When I make any request .. WAMP Homepage appears.
    What should I do?

  • farhan sajid

    Hi Ravi Tamada i have enabled mysqli but i am unable to remove the error.
    when i am calling /chat_rooms method i am facing the issue

    Fatal error: Call to undefined method mysqli_stmt::get_result() in
    /home/wasifapp/public_html/ChatApp/include/db_handler.php on line
    164

    please help, thanks

  • Ramya kalijavedu

    hello sir,
    the index.php in v1 sub directory is showing an error while executing as http://localhost/gcm_chat/v1 the error is in the line “require_once ‘../include/db_handler.php’;” saying that there is no file in the specified path,but i have followed the directory structure as u have specified.can u please help me?

  • Vikas Chouhan

    Hi Ravi,

    Am trying to run this project in ubuntu OS, am getting this error
    –> “The requested URL /gcm_chat/v1/users/message was not found on this server.”

    and other URL also gets same error.
    Please can help me in this.

    Thanks in advanced,
    Vikas

  • Benja Mbuthia

    Hi hardcore, your tutorial is great and i think you’re a genius.
    Question : How do i insert the “code snippets” that you have described in point no.7

  • Larcenciels

    hi ravi, recently gcm moved to fcm, is hard to using your tutorial (this tutorial) with fcm ? (not gcm) what i need to change ?

  • Mouad Dloo

    hi Ravi Tamada i check method post with URL http://192.168.1.4/gcm_chat/v1/index.php/user/login but return in all the time 404 and get work good plz help

  • Muhammad Nadzir

    hello sir i have been follow this part 1 tutorial and i found some problems
    1. if i open the index.php there’s no requst for submit a user name is it true or not ?

    2. the user data not have gcm_user_id so how to get gcm user id using firebase ?(i have change my google API key with my firebase project) https://uploads.disquscdn.com/images/c6f9940563222082b1e3a467ebd49b46c890ce10194f416c2958693af80883c2.jpg
    3 the message data has been uploaded on messages table in mysql database but there’s no change in my firebase database how to complited that ?
    https://uploads.disquscdn.com/images/dd1a052b3c1c8e62e85539d679e6718e37f308e5dde16f221821eb50ffbe1593.jpg https://uploads.disquscdn.com/images/ce202e7fc69a3b74765de421bd4d7f27be5c0d901acc56cbbdae9717d5bef231.jpg

    i am a beginner and actually i have read some comments below but i’m not really understand about that.
    could i asking for information that what parts should be change in your tutorial if we using firebase ?
    however
    the point is google cloud message have been change to firebase CM so maybe you could be upgrade your tutorial in to “simple chat app using firebase tutorial”

  • Abhin

    While checking REST API it showing me the 403: Forbidden error, “You don’t have permission to access /gcm_chat/v1/user/login on this server.”
    please check the problem

    https://uploads.disquscdn.com/images/0192e95500bf4da4010711c2aadb9994e39c28e6389a3455e330b91d99f88252.png

  • عبدالرحمن الذهبي

    hi @ravi8x:disqus …There are xss bugs

  • Vijay Singh Chouhan

    hello sir… what is the

    gcm_defaultSenderId_123ss??

  • Magic Man

    i have this error please help

    Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/u913270972/public_html/gcm_chat/demo.php on line 24

  • kiran

    am not able to download slim.zip
    Please help

  • RaviTejaGoud Panem

    I have not downloaded Slim floder please sned that Slim floder to my mail id :14dp1d5803@gmail.com

  • kiran

    not able to Slim.zip please send it to my mail id kiranreddy644@gmail.com

  • Chihab Ahmed

    Can i use my own authentication service. for instance i have node.js authenication service, can i integrate it to this and use it . thanks

  • sagar pawar

    what changes i have to do in above code so that i can use this rest api on 000webhost web server

  • PRAVEEN NAIK

    Sir DATABASE FOR MEDIA LIKE VIDEO AND IMAGES , should i create a Table in new like Photos and vedios or should i embed them in the current one…!!

    • PRAVEEN NAIK

      and should how do i achive that in PHP to display images and Videos…??

  • ZOOBAZIZ

    hi Ravi Tamada, in the postman step when I try to push the data i get a 404 error message.
    Please reply soon

    • Whats the url you are accessing?

      • ZOOBAZIZ

        i had an issue with the apache server in lamp.. tried the same on wamp, it worked. By the way is the server in this part local or online??

        –ZOOBAZIZ

      • ZOOBAZIZ

        http://192.168.43.40/gcm_chat/v1/user/login

        this message was displayed

        Not Found
        The requested URL /gcm_chat/v1/user/login was not found on this server.

        Apache/2.4.18 (Ubuntu) Server at 192.168.43.40 Port 80

  • Sanjay Chaurasiya

    Any idea about this type of animation feature for sendning text message…?

    https://mir-s3-cdn-cf.behance.net/project_modules/disp/092d8f25685965.5634935a53dde.gif

  • Sakshi Verma

    Can I use Xampp server, if yes how do i use it? It would kind of you to help me out .
    -Sakshi

    • Saurabh Bhandari

      yes you can use xampp server. You just need to save your files in htdocs folder. For hosting your files from local pc or laptop you can use ng-roc tool that is used provide access to your local web server from online http requests

  • Tirumalesh kallepalli

    Hi Ravi i am getting error like this in post man “Oops! An error occurred while registereing” i am using wamp server i have done exactly the same what you did and have enabled what all required but i am unable to enter name and email to database using postman kindly help me on this thanks

    • Mike

      i had the same problem too

    • Ibrahim Samad

      You can place this code:
      mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

      on the top of your index.php after the: ini_set(‘display_errors’, ‘On’); This will turn mysql specific errors on so you can then post back here, the error you get.

  • Rushikesh Bhojane

    what changes do i have to make to use firebase instead of gcm

  • Muneer Khan

    Are all the steps and code still valid even after the introduction of FCM? I’m just starting with this tute, do I need to make any changes or just follow all the steps accordingly?
    Best Regards.

  • Tirumalesh kallepalli

    Hi ravi Please create a new chat application this one is not working at all thanks

  • 형준우

    hi Ravi Tamada
    I use AutoSet instead of WARM Server
    http://127.0.0.1:8090/gcm_chat/v1/user/login
    this message was displayed

    404 Page Not Found

    I think rest api setting problum..

    Please reply soon
    – korean student

    • Binamra Kandel

      I guess the problem is with .htacess and httpd.conf. I am facing the same problem. Will let you know if i found a solution.

      • 형준우

        Thank you!

  • dipanshu21

    Hy ravi…. I wuld request you to please upload the same project using firebase cloud system… I want the same project bt as the GCM is upgraded to FCM so its a bit difficult to switch .. please help!! Thnx

  • Saqib Kafeel

    Hi !

    Its Fantastic ! but i want to use it without internet and also push notifications not required !
    Please Give me Any Suggestion !

  • Ritu Rajan

    Hi ravi I am getting such errors..
    404 Page Not Found
    The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below. when trying to /gcm_chat/v1/ url

    • Ibrahim Samad

      It is Slim specific error, either you didn’t type the url correctly or you are using GET when you should have used POST and the vice versa.

  • Alita Toh

    Hi ravi I am getting this error:

    {“error”:true,”message”:”Oops! An error occurred while registereing”}

    I have entered a user name and a valid email address.

    • Dexter Fury (Kombat Zone)

      if you found the fix please let me know i have the same problem

    • Ibrahim Samad

      Turn mysql errors on by placing this code:

      mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

      on the top of your index.php file and post back the error you get.

      • Kevin.c Ciang

        this code (error) show up in postman while registering

        Slim Application Error
        body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}

        Slim Application Error
        The application could not run because of the following error:
        Details

        Type: mysqli_sql_exception

        Code: 1364

        Message: Field ‘gcm_registration_id’ doesn’t have a default value

        File: E:wamp64wwwgcm_chatincludedb_handler.php

        Line: 31

        Trace
        #0 E:wamp64wwwgcm_chatincludedb_handler.php(31): mysqli_stmt->execute()
        #1 E:wamp64wwwgcm_chatv1index.php(28): DbHandler->createUser(‘ciang’, ‘ciang@gmail.com’)
        #2 [internal function]: {closure}()
        #3 E:wamp64wwwgcm_chatlibsSlimRoute.php(436): call_user_func_array(Object(Closure), Array)
        #4 E:wamp64wwwgcm_chatlibsSlimSlim.php(1307): SlimRoute->dispatch()
        #5 E:wamp64wwwgcm_chatlibsSlimMiddlewareFlash.php(85): SlimSlim->call()
        #6 E:wamp64wwwgcm_chatlibsSlimMiddlewareMethodOverride.php(92): SlimMiddlewareFlash->call()
        #7 E:wamp64wwwgcm_chatlibsSlimMiddlewarePrettyExceptions.php(67): SlimMiddlewareMethodOverride->call()
        #8 E:wamp64wwwgcm_chatlibsSlimSlim.php(1254): SlimMiddlewarePrettyExceptions->call()
        #9 E:wamp64wwwgcm_chatv1index.php(385): SlimSlim->run()
        #10 {main}

        • Ibrahim Samad

          The error means that you have set ‘gcm_registration_id’ column to NOT NULL, mean while you are not posting any value for it from your android code. So you can cross check to make sure that
          1. The post variable name in your android matches the one in your PHP code
          2. The targeted column for gcm_registration_id in your PHP code is spelt correctly.
          3. You are actually sending a value for gcm_registration_id to mysql.

          • Kevin.c Ciang

            Thank you so much for your reply. I have completed the part 1 and now I’m stuck in the part 2.

  • Morton

    Hi Ravi:
    I had completed your part1 and part2 tutorial and used FCM instead of GCM .

    When i try to send notification from web , i got the json format exception from my android logcat , i don’t know how to fix my json format from php .

    Can you teach me which part should i exchange ?

    Here is my logcat from android:

    03-22 06:00:51.434 9706-20224/tw.idv.mogoflash.gcmadvance1 D/MyGcmPushReceiver: Data payload :{data={“image”:”http://www.androidhive.info/wp-content/uploads/2016/01/Air-1.png”,”message”:{“chat_room_id”:””,”created_at”:”2017-03-22 6:00:48″,”message_id”:””,”message”:”741″},”user”:{“user_id”:null,”gcm_registration_id”:null,”name”:null,”created_at”:null,”email”:null}}, flag=0, title=Google Cloud Messaging, is_background=false}
    03-22 06:00:51.434 9706-20224/tw.idv.mogoflash.gcmadvance1 D/MyGcmPushReceiver: Exception :Can’t create handler inside thread that has not called Looper.prepare()

    • Dexter Fury (Kombat Zone)

      I also did the same using FCM instead GCM but am stuck in part one on testing postman, its giving me this error
      {
      “error”: true,
      “message”: “Oops! An error occurred while registereing”
      }

  • Rushikesh Bhojane

    how can i modify the above program inirder to use it with firebase cloud messanging??THANKS

  • PHP Fatal error: Call to undefined method mysqli_stmt::get_result() in /home/gcm_chat/demo.php on line 24
    how can i fix it?

  • Armando Esparza García

    Hi @ravi8x:disqus, firstly congrats this is a very nice tuto, but I have a question, when I create a new chatroom I can see it in my list, but doen´t receive any notification(that new chatroom), if I send a message to another chatroom works ok, but when I create a new one I can´t, do you have any advice? Or do you know what can I do?

    • When a new is room is created, you should subscribe to that. Do you see anything that says subscribed to topic in logcat.

      • Armando Esparza García

        Hi @ravi8x:disqus yeah, I got that message (Subscribed to topic: topic_n), do you have any track?

        • Armando Esparza García

          I Have seen something interesting, if your topic is higher than 9 you will be unable to add a notification to taht topic

          • Please debug it well. I am not sure about the problem.

  • Rakesh Katta

    Hi,
    Thanks for such a great tutorial. But i’m not able to send messages to specific user (like one to one chat) using users/:id/message api.
    Error shown in ARC: {
    “error”: true,
    “message”: “Failed send message”
    }

    It seems like i have missed something but not getting it. Please help me to solve it.

    Thanks

  • Miraj Jungi

    Hello sir,
    Please add this same tutorial using FCM. Please sir its urgent.

    • Its the same with FCM, just a little tweak.

  • Dexter Fury (Kombat Zone)

    Am getting this error in Postman, please help?
    {
    “error”: true,
    “message”: “Oops! An error occurred while registereing”
    }

    • Ibrahim Samad

      You might want to place this code:

      mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); on the top of index.php file,
      since your problem is more likely to mysql related. You can then post back here, the error you get.

      • Simran Sharma

        no use of this answer..please help me to solve this error

  • ketki

    Thanks for the information.

    I have a question regarding Push Notification Permission. Since, there is a provision to disable pushNotification from device settings- Is there any fallback mechanism?

    What approach should be followed in such a case?

    • None. Except you result back to HTTP Long Polling which I is popularly advised that you avoid using because of battery draining. However what major app doesn’t drain battery.

  • IS Lem

    hello for all who found this error 500 internal server error in ” postman” its caused from .htaccess file because mode rewrite its not activated so i have found the solution by watching this tutorial enjoyyyyyyyyyyyyyy
    https://www.youtube.com/watch?v=GmrqZImaPK8

  • pammy

    i cant seem to find GCM in my console. can you give me a link to it please. it keeps directing me to firebase. will firebse work with this tutorial

  • Digvijay Rathod

    I can not post any messages. while posting message it shows ” Sorry! Unable to post message”. And by exploring more I find this error is coming from addmessage function . I’ve configured as proper as you said.

    “Cannot add or update a child row: a foreign key constraint fails (`chat_demo`.`messages
    `, CONSTRAINT `messages_ibfk_3` FOREIGN KEY (`chat_room_id`) REFERENCES `chat_rooms` (`chat_room_id`
    ))”

    Thank you

    • The problem is with your Database, check to make sure your tables are well created also make check to make sure respective constrains are made properly.

  • Lamassu Iraq

    please i can’t download the code any one can help me?

    • Ibrahim Samad

      If you already signed in, you should be able to download the code without any difficulty.

  • Muhammad Jawad

    hi, Can you help me how can i send notification to android app from wamp server ?

    • WAMP Server is just a local server that sits on your local pc to avoid you the cost of using a realistic server during development. I’ll suggest you subscribe to one of the web hosting company like whogohost.com, hostgator.com or godaddy.com to have access to a live server, then the rest is just easy pizzy.

  • Abdul Rehman

    Warning: mysqli::mysqli(): (HY000/2002): Connection refused in /var/www/html/demos/gcm_chat/include/db_connect.php on line 24
    Failed to connect to MySQL: Connection refused
    Warning: mysqli::prepare(): Couldn’t fetch mysqli in /var/www/html/demos/gcm_chat/demo.php on line 41

    Fatal error: Call to a member function bind_param() on a non-object in /var/www/html/demos/gcm_chat/demo.php on line 42

    • Are you sure all the files and libraries are placed properly, however your question is not very clear.

  • Kishore Reddy

    hi ravi, can you provide the api key

    • The API Key, is not a generic key, its an Authorization Key, you get from Google Developer Console. Handles the use of all Google Services Tools

  • Kevin.c Ciang
  • Kevin.c Ciang

    Hello @ravi8x:disqus i got an error in testing on postman
    When I request the chat_rooms

    http://192.168.1.7:80/gcm_chat/v1/chat_rooms <– I write this by following the last video in part 6

    this code show up
    {
    "error": false,
    "chat_rooms": [] <– this is empty
    }

    Please tell me how to fi this.
    Thank you

  • Vinu Chacko

    Hai Ravi Tamada , Is this code work with FCM?

    • Yes, needs few modifications.

      • Vinu Chacko

        Thank you.. Now I am reading your articles about FCM. Hope I can Make this.. Thank u again

        • alaa

          Please can you tell me what changes you made to make this project work with fcm

  • Nand Kishor Patidar

    Hi Ravi sir,
    I want to send image with chat using php and mysql in android chat app. how will this happen?

    • In your message send CRUD API, you should add php codes that can handle file uploads, then
      mySQL should handle storage of the link location of the image file uploaded to your server.
      Go through the tutorial carefully, I think Raji pointed out somethings relating to that.

      • Simran Sharma

        hello, i get {“error”:true,”message”:”Oops! An error occurred while registereing”} this error how i solve this..please help me reply as soon as possible

  • Ahana

    hello..tell me one thing u use gcm here i hear that fcm is new rather then gcm so can i use fcm or which is best …and if i use fcm so how i will…please help me and reply soon as possible..thanks

  • Simran Sharma

    hello.this is group chat but how i make first one to one chat and then add feature of group chat..please help me and reply soon as possible

  • Simran Sharma

    hello, i get {“error”:true,”message”:”Oops!
    An error occurred while registereing”} this error how i solve
    this..please help me reply as soon as possible….and help me to sort out

    • It seems you have php errors. Check your php error logs once.

      • Simran Sharma

        thanks for the reply I solved this error but can u please help me with how to pin and archive and mute list view item like WhatsApp plz reply me and help

        • Hassan Iqbal

          Can u plz share how did u solve the PHP problem.

          • Simran Sharma

            yes sure.i was created table again in wamp for store data cause in this table our data can’t get table so do not do any thing just make another table in wamp with same name or same ..it should work.

          • Hassan Iqbal

            Thanks but i got error “table already exist” , when i tried to create the same table again. Although 000webhost went well in place of wamp.

          • Simran Sharma

            can u delete that table from wamp and then create new one .may be it helps you cause i only solve this error from to create new one sorry if this not help if i get other solution so i also tell u

  • Nikhil Patil

    hello ….
    when i submit chat field from admin dashboard …that time it will give and alert massage “sorry !, your msg can’t send “….i click on ok on alert screen ….and checked my screen msg send which i was typed ..

    …………… how can i stop this alert msg

  • Simran Sharma

    yes sure no need to thanks but i also new in php and also do the same what u do copy and paste. 🙂