This is a fully functional web based PHP & Vanilla JavaScript Chat Application project on Real Time Chat application which has been build with PHP script, MySQL Database, Vanilla JavaScript and Bootstrap 5 library. Under this PHP an Vanilla JavaScript Project, it has cover all essential functionality or features which you can use under your second year or final year student for their collage projects. This PHP Chat Application has many number of features like multiple user can chat with each other in real-time. This system is a Single page Chat application in which all operation like search user, accept chat request, real time chat with each other and profile setting. This all operation user can do on same page without going to other page without refresh of web page. By follow this tutorial, you can learn how to create Chat Web Application using PHP with MySQL and Vanilla JavaScript.
About Realtime Chat App using PHP & Vanilla JavaScript
This Chat Application in PHP and JavaScript, we have mainly focuses on how user can chat in real-time using Vanilla JavaScript. Because we have already published Chat application tutorial using jQuery but there are many viewers has requested us to published how to make chat application in PHP using JavaScript because for JavaScript can be run independently but for run jQuery we have to load jQuery library first. So many programmers are prefer Vanilla JavaScript for their web development project. So for here also we have use Vanilla JavaScript for build Real time chat application project. Under this Chat Application, we have use Vanilla JavaScript Fetch API for make real-time chat application.
Below you can find Demo link, so click on that Chat application Demo Link.
Once Chat Application Demo has been open first you have to register under this Chat Application.
Once you have register under this PHP Chat Application Demo, then you will received email verification email, so you have to verify your email address.
After Email verification, you will be redirect to index.html page and on that page you can fine chat application login area. So their you have to enter your login details.
After Login in to Chat Application demo, now you will be login under this chat application and with setting button, you can find source code download link.
Once you have click on Chat Application Source Code download link, then source code will download in you local computer.
Once source code has been downloaded you will be redirect again this Chat Application post, and on this post you can find password link, so once you have click on that link you will be redirect to YouTube video, and under that video description, you can find password for source code file, because source code file is password protected. So this is complete process of how to get Chat Application Source Code.
How to Run Chat Application?
After Source code file and password of Source Code file, then you have to unzip the project file under this directory of XAMPP.
Under XAMPP directory you will find folder naming "htdocs"
Under the "htdocs" directory, you have to unzip PHP Chat Application Source code.
Next you have to open your browser like Google chrome or Mozilla Firefox.
Under Browser you have to go URL like "http://localhost/phpmyadmin".
Under PHPMyAdmin you have to first create database and after create database, you have to create table for chat application. Under source code you can file chat.sql file for create required table for this chat system.
After create table in database, you have to open [project_folder_name]/backend/Db.php file.
Under this file, you have to define database name and base url of your chat application and save that file.
Once you have setting all above these, now you have to go to url "http://localhost/[ PROJECT_FOLDER_NAME ]/"
For check chat application, first you have to register under that system and then after you have to login under that system and check chat application.
So This is real time Chat Application in PHP with Vanilla JavaSCript project, which will helpful to both immediate level programmer and senior level programmer who want to work with PHP script and Vanilla JavaScript and want to build robust application with this technology. And at lastly, here we have share complete source code of PHP and Vanilla JavaScript Chat Application, so download it and learn something new from that source code and build another level Chat Application.
In this post, we are going to build a simple PHP and Mysql Chat Application using PHP Web Socket Ratchet. If you are looking for How to create Live or Real time chat Application in PHP then you have come on the right place, because in this post we have share you how to create Live Chat Application PHP with WebSockets. In this post, we will create Chat Application in which multiple user can chat with other users.
This is very interesting post on How to create chat App in PHP without using Ajax. In one of our previous post, we have already published tutorial on Chat application in PHP using ajax. But As we have know in Chat system, Ajax based Chat application in PHP is not best solution, this is because Ajax will increases the load on the server. So for this here we have use Ratchet PHP WebSockets for build real-time live chat application in PHP and in this chat app we will store chat data in Mysql database when one user has post chat under this system.
From this tutorial you can learn not only how to make group chat or multi user chat application using Ratchet WebSocket library but also you can also find this solution of one to one or single user or private chat application also. This is because under this post we will combine source code of group chat system and one to one chat application tutorial source code also. So from this single tutorial you can find solution for how to make group chat system and how to build real time one to one chat application also.
Feature of Group Chat Application
Under this Group Chat application using Ratchet Web socket you can get following feature under this tutorial.
Once single user has send chat message then other connected other user can received chat message using Ratchet client server.
User online or Offline status will be change after page refresh
Feature of One to One Chat Application
Under this One to one or Single User or Private chat application with Ratchet WebSocket library you can find following feature under this tutorial.
Send One to One Chat Message in Real-time using Ratchet WebSocket Library
Display or Hide Unread Message Notification in Real-time using Ratchet WebSocket Library
Display User Online or Offline Status in Real-time using Ratchet WebSocket Library
What is WebSockets?
WebSockets is a bi-directional and full-duplex which has provide persistent connection from a web browser to our server. So when WebSocket connection has been established in our browser, then it will open connection until client or server has decides to close this connection. So by with this open connection, the user or our server can send or receive chat data at any given time to the each other and it will makes our web programming completely on event driven and not just user started off. The other benefits of this websockets is that, at the same time on single running server, it will connect all connection and it will allowing us to communicate with any number of live connection at the any given time. So this are all benefits of this WebSockets in this Web programming.
Based on this benefits, we have use PHP WebSockets like Ratchet for build Chat Application in PHP and Mysql. Under this post, we will learn you step by step how to build Chat Application in PHP using WebSocket from scratch. Under this PHP Web Development tutorial, you can learn how can we quickly build at Chat App with RatChet using PHP script and Mysql Database.
Database of Chat Application
Before learning chat application, first you need to make tables for store chat application data in Mysql database. So first you need to create tables by run following Sql script you can create chat application tables in you mysql database.
Before learning chat application, first you need to make tables for store chat application data in Mysql database. So first you need to create tables by run following Sql script you can create chat application tables in you mysql database.
--
-- Database: `chat`
--
-- --------------------------------------------------------
--
-- Table structure for table `chatrooms`
--
CREATE TABLE `chatrooms` (
`id` int(11) NOT NULL,
`userid` int(11) NOT NULL,
`msg` varchar(200) NOT NULL,
`created_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `chat_user_table`
--
CREATE TABLE `chat_user_table` (
`user_id` int(11) NOT NULL,
`user_name` varchar(250) NOT NULL,
`user_email` varchar(250) NOT NULL,
`user_password` varchar(100) NOT NULL,
`user_profile` varchar(100) NOT NULL,
`user_status` enum('Disabled','Enable') NOT NULL,
`user_created_on` datetime NOT NULL,
`user_verification_code` varchar(100) NOT NULL,
`user_login_status` enum('Logout','Login') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `chatrooms`
--
ALTER TABLE `chatrooms`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `chat_user_table`
--
ALTER TABLE `chat_user_table`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `chatrooms`
--
ALTER TABLE `chatrooms`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `chat_user_table`
--
ALTER TABLE `chat_user_table`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
Source Code of PHP Chat Application
Below you can find PHP Chat Application Source code file.
database/Database_connection.php
This file we will use for make database connection under this chat application.
<?php
//Database_connection.php
class Database_connection
{
function connect()
{
$connect = new PDO("mysql:host=localhost; dbname=chat", "root", "");
return $connect;
}
}
?>
database/ChatUser.php
This ChatUser.php class file we have use for process user data at server side. Under this class file we have make set and get method for user data and after this we have make method for check user already register or not and lastly we have make insert user data in mysql table.
This class we will use for database operation of chat message data. Under this class we will make set and get function for process chat data form database related operation. By using this class we will insert or store chat message in Mysql database and fetch chat data from Mysql database for display on web page.
<?php
class ChatRooms
{
private $chat_id;
private $user_id;
private $message;
private $created_on;
protected $connect;
public function setChatId($chat_id)
{
$this->chat_id = $chat_id;
}
function getChatId()
{
return $this->chat_id;
}
function setUserId($user_id)
{
$this->user_id = $user_id;
}
function getUserId()
{
return $this->user_id;
}
function setMessage($message)
{
$this->message = $message;
}
function getMessage()
{
return $this->message;
}
function setCreatedOn($created_on)
{
$this->created_on = $created_on;
}
function getCreatedOn()
{
return $this->created_on;
}
public function __construct()
{
require_once("Database_connection.php");
$database_object = new Database_connection;
$this->connect = $database_object->connect();
}
function save_chat()
{
$query = "
INSERT INTO chatrooms
(userid, msg, created_on)
VALUES (:userid, :msg, :created_on)
";
$statement = $this->connect->prepare($query);
$statement->bindParam(':userid', $this->user_id);
$statement->bindParam(':msg', $this->message);
$statement->bindParam(':created_on', $this->created_on);
$statement->execute();
}
function get_all_chat_data()
{
$query = "
SELECT * FROM chatrooms
INNER JOIN chat_user_table
ON chat_user_table.user_id = chatrooms.userid
ORDER BY chatrooms.id ASC
";
$statement = $this->connect->prepare($query);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
register.php
This file we have use for get Chat application user registration. User can register from this web page.
This chatroom.php will be only access by login user, so once user has been login into this chat application, then system will redirect page to this chatroom.php file and under this file we will make chat room, so each user can chat with each other. Under this page, user can see their profile picture with edit profile and logout button link also.
This file has received ajax request for user logout from chat user application. Under this file, first we have remove session variable value and then after we have remove all session variable and give status value to ajax request in json format.
<?php
//Chat.php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
require dirname(__DIR__) . "/database/ChatUser.php";
require dirname(__DIR__) . "/database/ChatRooms.php";
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo 'Server Started';
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
echo 'Server Started';
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
$data = json_decode($msg, true);
$chat_object = new \ChatRooms;
$chat_object->setUserId($data['userId']);
$chat_object->setMessage($data['msg']);
$chat_object->setCreatedOn(date("Y-m-d h:i:s"));
$chat_object->save_chat();
$user_object = new \ChatUser;
$user_object->setUserId($data['userId']);
$user_data = $user_object->get_user_data_by_id();
$user_name = $user_data['user_name'];
$data['dt'] = date("d-m-Y h:i:s");
foreach ($this->clients as $client) {
/*if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}*/
if($from == $client)
{
$data['from'] = 'Me';
}
else
{
$data['from'] = $user_name;
}
$client->send(json_encode($data));
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
?>
bin/server.php
<?php
//server.php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
?>