Hello friends, in this post I will show you How to Create Chat App for Android using PHP, MySQL and GCM. I have already posted about GCM and Push Notifications in my earlier post as these are very important for creating our chat app. So in this post we will create a simple chat room where many users can interact with each other.
This post was very lengthy so I divided it into two parts.
Part 1: This part will cover about creating server side codes and APIs.
Part 2: In this part we will actually build our chat application.
Table of Contents
Create Chat App for Android Live Demo
You can also check this video demonstrating the final app that we will make in this tutorial.
You can also get a live demo of the app that we will be building from below. Just download the apk from the link given and install it to your device. But you need two device to check it.
If you tested the apk and want to know how to code it then lets move ahead.
Prerequisite to Create Chat App for Android
- You should follow the previous Android Push Notification Tutorial using GCM.
- You should also follow the REST API tutorial using SLIM Framework.
- Other than the above mentioned tutorial we will be using PHP and MySQL you need a local server like wamp or xampp for it.
It is highly recommended that you go through the above mentioned tutorial before moving ahead on this Create Chat App for Android Tutorial. So lets begin.
Create Chat App for Android Tutorial
In this post we will create server side APIs and in the next post we will built the android application. I am using WAMP server. You can also use other server’s basically what is needed is PHP and MySQL. So lets start with creating database.
Creating Database
- This is our database model.
- So as you can see we have two tables one is users and other is messages. To create the above tables just copy the following SQL to your phpmyadmin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | -- Created by Simplified Coding https://www.simplifiedcoding.net -- Last modification date: 2016-05-30 15:41:34.537 -- tables -- Table: messages CREATE TABLE messages ( id int NOT NULL AUTO_INCREMENT, message varchar(100) NOT NULL, users_id int NOT NULL, sentat timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT messages_pk PRIMARY KEY (id) ); -- Table: users CREATE TABLE users ( id int NOT NULL AUTO_INCREMENT, name varchar(50) NOT NULL, email varchar(50) NOT NULL, gcmtoken text NOT NULL, CONSTRAINT users_pk PRIMARY KEY (id) ); -- foreign keys -- Reference: messages_users (table: messages) ALTER TABLE messages ADD CONSTRAINT messages_users FOREIGN KEY messages_users (users_id) REFERENCES users (id); -- End of file. |
- Now we have our database. Time to code our API.
Creating RESTful API
- I am using PHP Storm as I personally feel it is the best IDE. So whatever IDE you are using open it and create a new PHP Project in the WAMP’s root directory (c:/wamp/www). I have created SimplifiedCodingChat.
- Now you have to create the following folder structure as shown in the below screenshot.
- First download SLIM Framework 2.x and paste it inside your libs folder.
- Now inside include folder create 3 php files Config.php, DbConnect.php and DbOperation.php.
- First come inside Config.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('DB_NAME', 'db_simplifiedcodingchat'); define('USER_CREATED_SUCCESSFULLY', 0); define('USER_CREATE_FAILED', 1); define('USER_ALREADY_EXISTED', 2); define('GOOGLE_API_KEY','YOUR GOOGLE API KEY'); |
- You may need to change the value of the first 4 constants according to your MySQL database. And you also need to put your Google API Key. If you don’t know what is the google api key please go through the Android Push Notification Tutorial using GCM first.
- Now inside DbConnect.php write the following code. It is used to connect with the MySQL Database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?php class DbConnect { private $conn; function __construct() { } /** * Establishing database connection * @return database connection handler */ function connect() { require_once '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; } } |
- In DbOperation.php we will define functions for all the database related operations. Write the following code in DbOperation.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | <?php class DbOperation { private $conn; //Constructor function __construct() { require_once dirname(__FILE__) . '/Config.php'; require_once dirname(__FILE__) . '/DbConnect.php'; // opening db connection $db = new DbConnect(); $this->conn = $db->connect(); } //Function to create a new user public function createUser($name, $email) { if (!$this->isUserExists($email)) { $stmt = $this->conn->prepare("INSERT INTO users(name, email) values(?, ?)"); $stmt->bind_param("ss", $name, $email); $result = $stmt->execute(); $stmt->close(); if ($result) { return USER_CREATED_SUCCESSFULLY; } else { return USER_CREATE_FAILED; } } else { return USER_ALREADY_EXISTED; } } //Function to get the user with email public function getUser($email) { $stmt = $this->conn->prepare("SELECT * FROM users WHERE email=?"); $stmt->bind_param("s", $email); $stmt->execute(); $user = $stmt->get_result()->fetch_assoc(); return $user; } //Function to check whether user exist or not private function isUserExists($email) { $stmt = $this->conn->prepare("SELECT 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; } //Function to store gcm registration token in database public function storeGCMToken($id, $token) { $stmt = $this->conn->prepare("UPDATE users SET gcmtoken =? WHERE id=?"); $stmt->bind_param("si", $token, $id); if ($stmt->execute()) return true; return false; } //Function to get the registration token from the database //The id is of the person who is sending the message //So we are excluding his registration token as sender doesnt require notification public function getRegistrationTokens($id){ $stmt = $this->conn->prepare("SELECT gcmtoken FROM users WHERE NOT id = ?;"); $stmt->bind_param("i",$id); $stmt->execute(); $result = $stmt->get_result(); $tokens = array(); while($row = $result->fetch_assoc()){ array_push($tokens,$row['gcmtoken']); } return $tokens; } //Function to add message to the database public function addMessage($id,$message){ $stmt = $this->conn->prepare("INSERT INTO messages (message,users_id) VALUES (?,?)"); $stmt->bind_param("si",$message,$id); if($stmt->execute()) return true; return false; } //Function to get messages from the database public function getMessages(){ $stmt = $this->conn->prepare("SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;"); $stmt->execute(); $result = $stmt->get_result(); return $result; } } |
- Inside libs folder create a new folder named gcm and inside it create a new file named gcm.php and write the following code. This file will handle our push notifications.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php class GCM { function __construct() { } //This function will send message to the given registration ids //We are also passing a message that is actually an array containing the message public function sendMessage($registration_ids, $message) { $fields = array( 'registration_ids' => $registration_ids, 'data' => $message, ); //In this function we are calling the main method responsible for sending push notification //it is sendPushNotification return $this->sendPushNotification($fields); } //This is the main method responsible for sending push notification //I have already explained it in previous tutorials private function sendPushNotification($fields){ include_once __DIR__ . '/../../include/Config.php'; $url = 'https://android.googleapis.com/gcm/send'; $headers = array( 'Authorization: key=' . GOOGLE_API_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); if ($result === FALSE) { die('Curl failed: ' . curl_error($ch)); } curl_close($ch); return $result; } } |
- Now come inside v1 folder and create a .htaccess file and write the following.
1 2 3 4 5 | RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L] |
- Finally in v1 folder create index.php this file will handle all the API calls.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | <?php require_once '../include/DbOperation.php'; require_once '../libs/gcm/gcm.php'; require '.././libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); // User id from db - Global Variable $user_id = NULL; /** * User Registration * url - /register * method - POST * params - name, email */ $app->post('/register', function () use ($app) { //Verifying parameters verifyRequiredParams(array('name', 'email')); //Response array $response = array(); //Getting request parameters $name = $app->request->post('name'); $email = $app->request->post('email'); //Vaidating email validateEmail($email); //Creating a db object $db = new DbOperation(); //INserting user to database $res = $db->createUser($name, $email); //If user created //Adding the user detail to response if ($res == USER_CREATED_SUCCESSFULLY) { $response["error"] = false; $user = $db->getUser($email); $response['id'] = $user['id']; $response['name'] = $user['name']; $response['email'] = $user['email']; echoResponse(201, $response); //If user creating failes adding error to response } else if ($res == USER_CREATE_FAILED) { $response["error"] = true; $response["message"] = "Oops! An error occurred while registereing"; echoResponse(200, $response); //If user already exist //adding the user data to response } else if ($res == USER_ALREADY_EXISTED) { $response["error"] = false; $user = $db->getUser($email); $response['id'] = $user['id']; $response['name'] = $user['name']; $response['email'] = $user['email']; echoResponse(200, $response); } }); /* * URL: /send * Method: POST * parameters: id, message * */ //This is used to send message on the chat room $app->post('/send', function () use ($app) { //Verifying required parameters verifyRequiredParams(array('id', 'message')); //Getting request parameters $id = $app->request()->post('id'); $message = $app->request()->post('message'); $name = $app->request()->post('name'); //Creating a gcm object $gcm = new GCM(); //Creating db object $db = new DbOperation(); //Creating response array $response = array(); //Creating an array containing message data $pushdata = array(); //Adding title which would be the username $pushdata['title'] = $name; //Adding the message to be sent $pushdata['message'] = $message; //Adding user id to identify the user who sent the message $pushdata['id']=$id; //If message is successfully added to database if ($db->addMessage($id, $message)) { //Sending push notification with gcm object $gcm->sendMessage($db->getRegistrationTokens($id), $pushdata); $response['error'] = false; } else { $response['error'] = true; } echoResponse(200, $response); }); /* * URL: /storegcmtoken/:id * Method: PUT * Parameters: token * */ //This will store the gcm token to the database $app->put('/storegcmtoken/:id', function ($id) use ($app) { verifyRequiredParams(array('token')); $token = $app->request()->put('token'); $db = new DbOperation(); $response = array(); if ($db->storeGCMToken($id, $token)) { $response['error'] = false; $response['message'] = "token stored"; } else { $response['error'] = true; $response['message'] = "Could not store token"; } echoResponse(200, $response); }); /* * URL: /messages * Method: GET * */ //This will fetch all the messages available on the database to display on the thread $app->get('/messages', function () use ($app){ $db = new DbOperation(); $messages = $db->getMessages(); $response = array(); $response['error']=false; $response['messages'] = array(); while($row = mysqli_fetch_array($messages)){ $temp = array(); $temp['id']=$row['id']; $temp['message']=$row['message']; $temp['userid']=$row['users_id']; $temp['sentat']=$row['sentat']; $temp['name']=$row['name']; array_push($response['messages'],$temp); } echoResponse(200,$response); }); //Function to validate email function validateEmail($email) { $app = \Slim\Slim::getInstance(); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $response["error"] = true; $response["message"] = 'Email address is not valid'; echoResponse(400, $response); $app->stop(); } } //Function to display the response in browser function echoResponse($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); } //Function to verify required parameters function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $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'; echoResponse(400, $response); $app->stop(); } } function authenticate(\Slim\Route $route) { //Implement authentication if needed } $app->run(); |
- Thats it for the API Coding. Now you need a REST Client to Test the API. You can use Postman for google chrome.
Testing the API
- You can use Postman for chrome or any other REST Client to test your API. The final API we built is shown in the following table
Base URL: http://localhost/SimplifiedCodingChat/v1/
URL | Method | Parameters |
---|---|---|
register | POST | name,email |
send | POST | id, message |
storegcmtoken/:id | PUT | token |
messages | GET |
- If you are having some problems or troubles you can get my php project for this Android Chat App for Android Tutorial from the link given below (You need to unlock the link).
So thats all for this part friends. You can follow the next part from the link given.
Create Chat Application in Android using GCM Part 2
In this part we will actually Create Chat App for Android using Android Studio. And yes feel free to ask by comments if having any troubles. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
gcm is deprecated. do you think publishing a firebase chat room tutorial? there is not any in the web.
Who said gcm is deprecated???
“Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.”
deprecated may be an assertive word, but gcm is not recommended by google for new projects.
deprecated may be an assertive word, but gcm is not recommended by google for new projects.
“Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.”
i test this whole script after following all the procedures, uploaded it into server, i’ve changed all required credentials (Config.php to be specific), and run it using POSTMAN, and this is the result:
Slim Application Error
did i miss something?
p/s:
…it takes me about 5-6 times sending this post, everytime i submit my post it returns me to a 403 page, i think your site has something on that makes it so irresponsive…
.. who said that Google Cloud Messaging is deprecated? You might using other cloud messaging service, might be: xtify, urban airship, or pushy, but some people (mostly developers) say, (with “some people” with clause) that behind them is GCM .
.. who said that Google Cloud Messaging is deprecated? You might using other cloud messaging service, might be: xtify, urban airship, or pushy, but some people (mostly developers) say, (with “some people” with clause) that behind them is GCM . am telling you, the best of knowlegde , it is not.
“Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.”
deprecated may be an assertive word, but gcm is not recommended by google for new projects.
deprecated may be an assertive word, but gcm is not recommended by google for new projects.
“Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.”
Yeah I have published a Firebase tutorial too..
bilal i need a little help from you brother. then please mail me back bro thanks
Hello Belal Brother,Please Upload a chatting tutorial about a single chat like friend to friend chat using Firebase GCM,thanks in advance
Hi Sir,
The Tutorial is best and works excellently on XAMPP.
But when I upload the files to the online web server, the app malfunctions.
I have changed the Config.php page like DBname, Host while hosting it to the online Web Server. I have also changed the path given in the app.
I will thankful for your help!
Thank You!
It also work on online server.. as the apk I given for the demo is working on online server.. there may some misconfiguration in your server.. check that
Thank You, Sir for your reply.
But I made all the changes in the configuration to the best of my knowledge. But the malfunction continues.
Please can you list me the changes I should make for online server.
Will thankful for your help!
Thank You!
i had the same experienced, the scripts are fully working fine on local server but some negative issue exists on putting all scripts on online server, and this i figure out: error exists not because of buggy script, it is because of capability of your main host or hosting i should say. You might using a shared server, am i right? take note that in shared server mysqlnd driver is not enabled, in summary, you need to use such or some mysqli prepared statements with object oriented programming using such VPS or Dedicated Server.Because those host services provide full root access and mysqlnd driver run by default.
hi Shaun I also using web server but there is one problem i.e. getting 404 Page Not Found Error, if your app is running then help me.
Happy Ramadan belal.I have a questions you know the essential things required in the startup field , so why don”t you do it.Or you are already doing something.But above all thank you for these lovely tutorials.
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/home/test/public_html/test/chatting/include/DbOperation.php on line
41
i had the same experienced, the scripts are fully working fine on local server but some negative issue exists on putting all scripts on online server, and this i figure out: error exists not because of buggy script, it is because of capability of your main host or hosting i should say. You might using a shared server, am i right? take note that in shared server mysqlnd driver is not enabled, in summary, you need to use such or some mysqli prepared statements with object oriented programming using such VPS or Dedicated Server.Because those host services provide full root access and mysqlnd driver run by default.
why i received the message “Parse error: syntax error, unexpected ‘x’ (T_STRING) in C:\wamp\www\gcm_chat1\v1\index.php on line 6”, I don’t know what happen because I followed your example exactly, please help me to solve the problem, because I quite new in android
i am getting 404 page 🙁
HELP IDEM
hii i m getting 404 error plz guide mee..
Getting 404 Page Not Found Error.
Help!
Tutorial is good.Working At localhost perfectly but didn,t work inside the shared server.Didn’t get any responses why??????
There is a mistake that needs a fix. DbOperation.php line 21
Before: $stmt = $this->conn->prepare(“INSERT INTO users(name, email) values(?, ?)”);
When I tried to register it gave me an error but
After:
$stmt = $this->conn->prepare(“INSERT INTO users(name, email,gcmtoken) values(?, ?,’A’)”);
It worked for me by inserting gcmtoken.
Thanks you are really good in explaining this.
Can this be uploaded to lets say Google app engine instead of a local server?
What changes is needed for that?
Hello, i want this demo project using FCM.
hey please help us how can
Resolve 404 error
enable apache rewrite module
Will this still work,i saw a comment about been depreciated
NO it is not deprecated but you should use firebase cloud messaging instead. Check this fcm tutorial to replace gcm with fcm https://www.simplifiedcoding.net/firebase-cloud-messaging-android/
please help us how can
Resolve 404 error??
My apache rewrite module is ok
i use xampp
Hi,
I get an error ” java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean .helper.AppController.isLoggedIn()” and the app crashes.
Can u please help??
Please, help!
Error: ————
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.
Visit the Home Page
———-
Database and table is created
Installed Denwer
Apk i downloaded that itself not working properly, after entering email..it again asks for email…
enter name and enter email. submit button..only loaded the progress bar not open Next Actvity
Hello, where can I find the v1 folder?
Thank you very much!
enter name and enter email. submit button..only loaded the progress bar not open Next Actvity
when i am enter name and enter email but it still load progress bar but do not display next act.so pls give me fast solution as soon as possible
do you find what is the problem,same here!!
hello sir ,
when i have insert name and the email id in the field it will inserted in the database but couldn’t create the gcm tocken in “users” table
hello when i run this php code it show me error Internal Server Error
The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator, admin@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error.
More information about this error may be available in the server error log. …this error how i solve this please please help me and reply soon as possible..please help me belal
your code does not let connectivity to server and neither you reply to my queries?
You have surely done something wrong.. we are making an updated post using FCM so please have patience and we will post the updated content soon
Hello guys, I implemented the code of this tutorial ( and changed some pieces of it regarding to the needs of my app).
But I have a problem. When I try to use $gcm->sendMessage(…), I got an error as a result, saying : Error 411 (Length Required)!!, and That’s an error. POST requests require a Content-length header. That’s all we know.
Hope you guys can help me
You should try using FCM now.. and We are creating a tutorial for the same using FCM.
Don’t host such website if you do not have time to reply.
You waste both you and your viewer time.
Say what is the problem? We will try to help you
PHP Fatal error: Call to undefined method mysqli_stmt::get_result()
Hi, when the FCM version will be available? need it urgently
i keep getting 404 not found on postman and browser .i don’t know what’s the problem, i already enabled Apache rewrite module.
please help.
hi bro, do u have Create Chat App for Android using FCM?