Wednesday, 24 February 2021

Online Doctor Appointment System Project in PHP Mysql


PHP Online Doctor Appointment Management System has been build by using PHP with Mysql database at server side and at client-side using Ajax jQuery and other jquery plugin. This PHP project you can use for your major PHP project. The main aim for developed Doctor Appointment System is for solve the purpose for disallow the problems, which are not in the current system. This Doctor Appointment System is assume to remove the hardships, which will be available in the current appointment system. But by using electronics equipment like computer and by using this devices we can stored valuable information which we can stored under this appointment system. This Online Doctor Appointment system is show as the fast, error free and secured system with fast management of data. With the help of this Doctor Appointment System which show the good for use of resources and stored records in central location of database.

Online Doctor Appointment System using PHP and Mysql is developed with point of manage the list of data of doctors, patients, appointment bookings, doctor available schedule information etc. This PHP Project on Doctor Appointment System, which is web based or online application which will resolves the problem of booking of Appointment according to the choice and requirement of the patient. Under this system, there is one feature like it is very effective solution which has offered with different available doctor availability on suitable dates and times, so patient can book doctor appointment according to their requirements or choice and patient can also cancel doctor appointment which also available under this system.

This system we can also called Online Patient Scheduling or also known as Online Appointment booking system and it has optimized phase of medical services to increase patient healthcare experience in hospitals or in clinics. This system has been build by motivating to see the increasing popularity of online appointment booking system and the main aims of developing this project on online appointment booking system, we have add doctor scheduling model also which has been takes into accounts when patient would like to seen this feature. Now a days it is rational to established the issue that a very less hospitals has provide online appointment booking system. So solve this all problem we have build this Doctor Online Appointment booking system.

This Online Doctor Appointment Booking System in PHP is a easy project developed using PHP script, Mysql database, Ajax and jQuery. Under this project there are three sides. One at Admin side, second is doctor side and third is patient side. Under this Doctor Appointment System Admin can manage whole system data like doctor data, patient data, doctor schedule data and appointment data. At the Doctor side, doctor can schedule their available time details under this system, Doctor can view appointment data. And at patient side, they can view doctor availability data and based on that data they can book appointment under this system.


Online Doctor Appointment System Project in PHP Mysql


Modules of Online Doctor Appointment Management System


Following are the main Module of Online Doctor Appointment Management System.

  1. Appointment Management Module
  2. Doctor Schedule Management Module
  3. Patient Management Module
  4. Doctor Management Module
  5. Login Module
  6. Registration Module





Features of Online Doctor Appointment Management System


This system has three users. Admin, Doctor and Patients. So all feature has been divided between this three users.

Admin or Master Users


  1. Admin can Add Edit Delete and view Doctor data.
  2. Admin can view all patient data.
  3. Admin can Schedule any Doctor Availability data and manage that data like edit or delete it.
  4. Admin can view all doctor appointment data and he or she can also process appointment.
  5. Admin can edit profile detials.
  6. Admin can login into this system.
  7. Admin can see Analytics data.


Doctor Users


  1. Doctor can Add Edit Delete their availablity data under this system.
  2. Doctor can view only his or her appointment data, they cannot see other doctor appointment data.
  3. Doctor can see appointment patients details
  4. Doctor can write comment in patient appointment.
  5. Doctor can edit profile detials.
  6. Doctor can login into this system.

Patients Users


  1. Patient can view Doctor Availability data on web page.
  2. Patient can register into this system.
  3. Patient can login into this system.
  4. Patient can book appointment and they can also cancel appointment.
  5. Patient can download appointment in PDF format also.
  6. Patient can change their profile details also.

Web Technology Used in Online Doctor Appointment Booking System


There are following Web Technology has used for build this Online Doctor Appointment Booking System.

Server-side


  • PHP
  • Mysql Database

Client-side


  • jQuery
  • Ajax
  • Bootstrap 4
  • Parsley.js
  • jQuery DataTable Plugin
  • Bootstrap DatePicker Plugin

Database of Online Doctor Appointment Booking System


Before start using this Online Doctor Appointment Booking System, first you have to create database of this system in you local computer. So for create database of Online Doctor Appointment Booking System you have to create new database in your local phpmyadmin and then after run following sql script. So it will make required table for this Online Doctor Appointment Booking System and you can check source in your local computer.



-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 25, 2021 at 05:51 AM
-- Server version: 10.1.30-MariaDB
-- PHP Version: 5.6.33

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `doctor_appointment`
--

-- --------------------------------------------------------

--
-- Table structure for table `admin_table`
--

CREATE TABLE `admin_table` (
  `admin_id` int(11) NOT NULL,
  `admin_email_address` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `admin_password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `admin_name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `hospital_name` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `hospital_address` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `hospital_contact_no` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `hospital_logo` varchar(200) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `admin_table`
--

INSERT INTO `admin_table` (`admin_id`, `admin_email_address`, `admin_password`, `admin_name`, `hospital_name`, `hospital_address`, `hospital_contact_no`, `hospital_logo`) VALUES
(1, 'johnsmith@gmail.com', 'password', 'John smith', 'Mount Hospital', '115, Last Lane, NYC', '741287410', '../images/15001.png');

-- --------------------------------------------------------

--
-- Table structure for table `appointment_table`
--

CREATE TABLE `appointment_table` (
  `appointment_id` int(11) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `patient_id` int(11) NOT NULL,
  `doctor_schedule_id` int(11) NOT NULL,
  `appointment_number` int(11) NOT NULL,
  `reason_for_appointment` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `appointment_time` time NOT NULL,
  `status` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `patient_come_into_hospital` enum('No','Yes') COLLATE utf8_unicode_ci NOT NULL,
  `doctor_comment` mediumtext COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `appointment_table`
--

INSERT INTO `appointment_table` (`appointment_id`, `doctor_id`, `patient_id`, `doctor_schedule_id`, `appointment_number`, `reason_for_appointment`, `appointment_time`, `status`, `patient_come_into_hospital`, `doctor_comment`) VALUES
(3, 1, 3, 2, 1000, 'Pain in Stomach', '09:00:00', 'Cancel', 'No', ''),
(4, 1, 3, 2, 1001, 'Paint in stomach', '09:00:00', 'Booked', 'No', ''),
(5, 1, 4, 2, 1002, 'For Delivery', '09:30:00', 'Completed', 'Yes', 'She gave birth to boy baby.'),
(6, 5, 3, 7, 1003, 'Fever and cold.', '18:00:00', 'In Process', 'Yes', ''),
(7, 6, 5, 13, 1004, 'Pain in Stomach.', '15:30:00', 'Completed', 'Yes', 'Acidity Problem. ');

-- --------------------------------------------------------

--
-- Table structure for table `doctor_schedule_table`
--

CREATE TABLE `doctor_schedule_table` (
  `doctor_schedule_id` int(11) NOT NULL,
  `doctor_id` int(11) NOT NULL,
  `doctor_schedule_date` date NOT NULL,
  `doctor_schedule_day` enum('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') COLLATE utf8_unicode_ci NOT NULL,
  `doctor_schedule_start_time` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_schedule_end_time` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `average_consulting_time` int(5) NOT NULL,
  `doctor_schedule_status` enum('Active','Inactive') COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `doctor_schedule_table`
--

INSERT INTO `doctor_schedule_table` (`doctor_schedule_id`, `doctor_id`, `doctor_schedule_date`, `doctor_schedule_day`, `doctor_schedule_start_time`, `doctor_schedule_end_time`, `average_consulting_time`, `doctor_schedule_status`) VALUES
(2, 1, '2021-02-19', 'Friday', '09:00', '14:00', 15, 'Active'),
(3, 2, '2021-02-19', 'Friday', '09:00', '12:00', 15, 'Active'),
(4, 5, '2021-02-19', 'Friday', '10:00', '14:00', 10, 'Active'),
(5, 3, '2021-02-19', 'Friday', '13:00', '17:00', 20, 'Active'),
(6, 4, '2021-02-19', 'Friday', '15:00', '18:00', 5, 'Active'),
(7, 5, '2021-02-22', 'Monday', '18:00', '20:00', 10, 'Active'),
(8, 2, '2021-02-24', 'Wednesday', '09:30', '12:30', 10, 'Active'),
(9, 5, '2021-02-24', 'Wednesday', '11:00', '15:00', 10, 'Active'),
(10, 1, '2021-02-24', 'Wednesday', '12:00', '15:00', 10, 'Active'),
(11, 3, '2021-02-24', 'Wednesday', '14:00', '17:00', 15, 'Active'),
(12, 4, '2021-02-24', 'Wednesday', '16:00', '20:00', 10, 'Active'),
(13, 6, '2021-02-24', 'Wednesday', '15:30', '18:30', 10, 'Active'),
(14, 6, '2021-02-25', 'Thursday', '10:00', '13:30', 10, 'Active');

-- --------------------------------------------------------

--
-- Table structure for table `doctor_table`
--

CREATE TABLE `doctor_table` (
  `doctor_id` int(11) NOT NULL,
  `doctor_email_address` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_profile_image` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_phone_no` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_address` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `doctor_date_of_birth` date NOT NULL,
  `doctor_degree` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_expert_in` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `doctor_status` enum('Active','Inactive') COLLATE utf8_unicode_ci NOT NULL,
  `doctor_added_on` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `doctor_table`
--

INSERT INTO `doctor_table` (`doctor_id`, `doctor_email_address`, `doctor_password`, `doctor_name`, `doctor_profile_image`, `doctor_phone_no`, `doctor_address`, `doctor_date_of_birth`, `doctor_degree`, `doctor_expert_in`, `doctor_status`, `doctor_added_on`) VALUES
(1, 'peterparker@gmail.com', 'password', 'Dr. Peter Parker', '../images/10872.jpg', '7539518520', '102, Sky View, NYC', '1985-10-29', 'MBBS MS', 'Sergen', 'Active', '2021-02-15 17:04:59'),
(2, 'adambrodly@gmail.com', 'password', 'Dr. Adam Broudly', '../images/21336.jpg', '753852963', '105, Fort, NYC', '1982-08-10', 'MBBS MD(Cardiac)', 'Cardiologist', 'Active', '2021-02-18 15:00:32'),
(3, 'sophia.parker@gmail.com', 'password', 'Dr. Sophia Parker', '../images/13838.jpg', '7417417410', '50, Best street CA', '1989-04-03', 'MBBS', 'Gynacologist', 'Active', '2021-02-18 15:05:02'),
(4, 'williampeterson@gmail.com', 'password', 'Dr. William Peterson', '../images/9498.jpg', '8523698520', '32, Green City, NYC', '1984-06-11', 'MBBS MD', 'Nurologist', 'Active', '2021-02-18 15:08:24'),
(5, 'emmalarsdattor@gmail.com', 'password', 'Dr. Emma Larsdattor', '../images/1613641523.png', '9635852025', '25, Silver Arch', '1988-03-03', 'MBBS MD', 'General Physian', 'Active', '2021-02-18 15:15:23'),
(6, 'manuel.armstrong@gmail.com', 'password', 'Dr. Manuel Armstrong', '../images/1614081376.png', '8523697410', '2378 Fire Access Road Asheboro, NC 27203', '1989-03-01', 'MBBS MD (Medicine)', 'General Physician', 'Active', '2021-02-23 17:26:16');

-- --------------------------------------------------------

--
-- Table structure for table `patient_table`
--

CREATE TABLE `patient_table` (
  `patient_id` int(11) NOT NULL,
  `patient_email_address` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  `patient_password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `patient_first_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `patient_last_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `patient_date_of_birth` date NOT NULL,
  `patient_gender` enum('Male','Female','Other') COLLATE utf8_unicode_ci NOT NULL,
  `patient_address` mediumtext COLLATE utf8_unicode_ci NOT NULL,
  `patient_phone_no` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `patient_maritial_status` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `patient_added_on` datetime NOT NULL,
  `patient_verification_code` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `email_verify` enum('No','Yes') COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `patient_table`
--

INSERT INTO `patient_table` (`patient_id`, `patient_email_address`, `patient_password`, `patient_first_name`, `patient_last_name`, `patient_date_of_birth`, `patient_gender`, `patient_address`, `patient_phone_no`, `patient_maritial_status`, `patient_added_on`, `patient_verification_code`, `email_verify`) VALUES
(3, 'jacobmartin@gmail.com', 'password', 'Jacob', 'Martin', '2021-02-26', 'Male', 'Green view, 1025, NYC', '85745635210', 'Single', '2021-02-18 16:34:55', 'b1f3f8409f7687072adb1f1b7c22d4b0', 'Yes'),
(4, 'oliviabaker@gmail.com', 'password', 'Olivia', 'Baker', '2001-04-05', 'Female', 'Diamond street, 115, NYC', '7539518520', 'Married', '2021-02-19 18:28:23', '8902e16ef62a556a8e271c9930068fea', 'Yes'),
(5, 'web-tutorial@programmer.net', 'password', 'Amber', 'Anderson', '1995-07-25', 'Female', '2083 Cameron Road Buffalo, NY 14202', '75394511442', 'Single', '2021-02-23 17:50:06', '1909d59e254ab7e433d92f014d82ba3d', 'Yes');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `admin_table`
--
ALTER TABLE `admin_table`
  ADD PRIMARY KEY (`admin_id`);

--
-- Indexes for table `appointment_table`
--
ALTER TABLE `appointment_table`
  ADD PRIMARY KEY (`appointment_id`);

--
-- Indexes for table `doctor_schedule_table`
--
ALTER TABLE `doctor_schedule_table`
  ADD PRIMARY KEY (`doctor_schedule_id`);

--
-- Indexes for table `doctor_table`
--
ALTER TABLE `doctor_table`
  ADD PRIMARY KEY (`doctor_id`);

--
-- Indexes for table `patient_table`
--
ALTER TABLE `patient_table`
  ADD PRIMARY KEY (`patient_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `admin_table`
--
ALTER TABLE `admin_table`
  MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

--
-- AUTO_INCREMENT for table `appointment_table`
--
ALTER TABLE `appointment_table`
  MODIFY `appointment_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;

--
-- AUTO_INCREMENT for table `doctor_schedule_table`
--
ALTER TABLE `doctor_schedule_table`
  MODIFY `doctor_schedule_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15;

--
-- AUTO_INCREMENT for table `doctor_table`
--
ALTER TABLE `doctor_table`
  MODIFY `doctor_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

--
-- AUTO_INCREMENT for table `patient_table`
--
ALTER TABLE `patient_table`
  MODIFY `patient_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;






Thursday, 7 January 2021

Build Real time Chat Application in PHP Mysql using WebSocket


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.

  1. Once single user has send chat message then other connected other user can received chat message using Ratchet client server.
  2. 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.

  1. Send One to One Chat Message in Real-time using Ratchet WebSocket Library
  2. Display or Hide Unread Message Notification in Real-time using Ratchet WebSocket Library
  3. 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.





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.


--
-- 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.


<?php

//ChatUser.php

class ChatUser
{
	private $user_id;
	private $user_name;
	private $user_email;
	private $user_password;
	private $user_profile;
	private $user_status;
	private $user_created_on;
	private $user_verification_code;
	private $user_login_status;
	public $connect;

	public function __construct()
	{
		require_once('Database_connection.php');

		$database_object = new Database_connection;

		$this->connect = $database_object->connect();
	}

	function setUserId($user_id)
	{
		$this->user_id = $user_id;
	}

	function getUserId()
	{
		return $this->user_id;
	}

	function setUserName($user_name)
	{
		$this->user_name = $user_name;
	}

	function getUserName()
	{
		return $this->user_name;
	}

	function setUserEmail($user_email)
	{
		$this->user_email = $user_email;
	}

	function getUserEmail()
	{
		return $this->user_email;
	}

	function setUserPassword($user_password)
	{
		$this->user_password = $user_password;
	}

	function getUserPassword()
	{
		return $this->user_password;
	}

	function setUserProfile($user_profile)
	{
		$this->user_profile = $user_profile;
	}

	function getUserProfile()
	{
		return $this->user_profile;
	}

	function setUserStatus($user_status)
	{
		$this->user_status = $user_status;
	}

	function getUserStatus()
	{
		return $this->user_status;
	}

	function setUserCreatedOn($user_created_on)
	{
		$this->user_created_on = $user_created_on;
	}

	function getUserCreatedOn()
	{
		return $this->user_created_on;
	}

	function setUserVerificationCode($user_verification_code)
	{
		$this->user_verification_code = $user_verification_code;
	}

	function getUserVerificationCode()
	{
		return $this->user_verification_code;
	}

	function setUserLoginStatus($user_login_status)
	{
		$this->user_login_status = $user_login_status;
	}

	function getUserLoginStatus()
	{
		return $this->user_login_status;
	}

	function make_avatar($character)
	{
	    $path = "images/". time() . ".png";
		$image = imagecreate(200, 200);
		$red = rand(0, 255);
		$green = rand(0, 255);
		$blue = rand(0, 255);
	    imagecolorallocate($image, $red, $green, $blue);  
	    $textcolor = imagecolorallocate($image, 255,255,255);

	    $font = dirname(__FILE__) . '/font/arial.ttf';

	    imagettftext($image, 100, 0, 55, 150, $textcolor, $font, $character);
	    imagepng($image, $path);
	    imagedestroy($image);
	    return $path;
	}

	function get_user_data_by_email()
	{
		$query = "
		SELECT * FROM chat_user_table 
		WHERE user_email = :user_email
		";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_email', $this->user_email);

		if($statement->execute())
		{
			$user_data = $statement->fetch(PDO::FETCH_ASSOC);
		}
		return $user_data;
	}

	function save_data()
	{
		$query = "
		INSERT INTO chat_user_table (user_name, user_email, user_password, user_profile, user_status, user_created_on, user_verification_code) 
		VALUES (:user_name, :user_email, :user_password, :user_profile, :user_status, :user_created_on, :user_verification_code)
		";
		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_name', $this->user_name);

		$statement->bindParam(':user_email', $this->user_email);

		$statement->bindParam(':user_password', $this->user_password);

		$statement->bindParam(':user_profile', $this->user_profile);

		$statement->bindParam(':user_status', $this->user_status);

		$statement->bindParam(':user_created_on', $this->user_created_on);

		$statement->bindParam(':user_verification_code', $this->user_verification_code);

		if($statement->execute())
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function is_valid_email_verification_code()
	{
		$query = "
		SELECT * FROM chat_user_table 
		WHERE user_verification_code = :user_verification_code
		";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_verification_code', $this->user_verification_code);

		$statement->execute();

		if($statement->rowCount() > 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function enable_user_account()
	{
		$query = "
		UPDATE chat_user_table 
		SET user_status = :user_status 
		WHERE user_verification_code = :user_verification_code
		";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_status', $this->user_status);

		$statement->bindParam(':user_verification_code', $this->user_verification_code);

		if($statement->execute())
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function update_user_login_data()
	{
		$query = "
		UPDATE chat_user_table 
		SET user_login_status = :user_login_status 
		WHERE user_id = :user_id
		";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_login_status', $this->user_login_status);

		$statement->bindParam(':user_id', $this->user_id);

		if($statement->execute())
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function get_user_data_by_id()
	{
		$query = "
		SELECT * FROM chat_user_table 
		WHERE user_id = :user_id";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_id', $this->user_id);

		try
		{
			if($statement->execute())
			{
				$user_data = $statement->fetch(PDO::FETCH_ASSOC);
			}
			else
			{
				$user_data = array();
			}
		}
		catch (Exception $error)
		{
			echo $error->getMessage();
		}
		return $user_data;
	}

	function upload_image($user_profile)
	{
		$extension = explode('.', $user_profile['name']);
		$new_name = rand() . '.' . $extension[1];
		$destination = 'images/' . $new_name;
		move_uploaded_file($user_profile['tmp_name'], $destination);
		return $destination;
	}

	function update_data()
	{
		$query = "
		UPDATE chat_user_table 
		SET user_name = :user_name, 
		user_email = :user_email, 
		user_password = :user_password, 
		user_profile = :user_profile  
		WHERE user_id = :user_id
		";

		$statement = $this->connect->prepare($query);

		$statement->bindParam(':user_name', $this->user_name);

		$statement->bindParam(':user_email', $this->user_email);

		$statement->bindParam(':user_password', $this->user_password);

		$statement->bindParam(':user_profile', $this->user_profile);

		$statement->bindParam(':user_id', $this->user_id);

		if($statement->execute())
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	function get_user_all_data()
	{
		$query = "
		SELECT * FROM chat_user_table 
		";

		$statement = $this->connect->prepare($query);

		$statement->execute();

		$data = $statement->fetchAll(PDO::FETCH_ASSOC);

		return $data;
	}

}



?>




database/ChatRooms.php


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.


<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$error = '';

$success_message = '';

if(isset($_POST["register"]))
{
    session_start();

    if(isset($_SESSION['user_data']))
    {
        header('location:chatroom.php');
    }

    require_once('database/ChatUser.php');

    $user_object = new ChatUser;

    $user_object->setUserName($_POST['user_name']);

    $user_object->setUserEmail($_POST['user_email']);

    $user_object->setUserPassword($_POST['user_password']);

    $user_object->setUserProfile($user_object->make_avatar(strtoupper($_POST['user_name'][0])));

    $user_object->setUserStatus('Disabled');

    $user_object->setUserCreatedOn(date('Y-m-d H:i:s'));

    $user_object->setUserVerificationCode(md5(uniqid()));

    $user_data = $user_object->get_user_data_by_email();

    if(is_array($user_data) && count($user_data) > 0)
    {
        $error = 'This Email Already Register';
    }
    else
    {
        if($user_object->save_data())
        {

            $mail = new PHPMailer(true);

            $mail->isSMTP();

            $mail->Host = 'smtpout.secureserver.net';

            $mail->SMTPAuth = true;

            $mail->Username   = 'xxxxx';                     // SMTP username
            $mail->Password   = 'xxxxxx';

            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

            $mail->Port = 80;

            $mail->setFrom('tutorial@webslesson.info', 'Webslesson');

            $mail->addAddress($user_object->getUserEmail());

            $mail->isHTML(true);

            $mail->Subject = 'Registration Verification for Chat Application Demo';

            $mail->Body = '
            <p>Thank you for registering for Chat Application Demo.</p>
                <p>This is a verification email, please click the link to verify your email address.</p>
                <p><a href="http://localhost/tutorial/chat_application/verify.php?code='.$user_object->getUserVerificationCode().'">Click to Verify</a></p>
                <p>Thank you...</p>
            ';

            $mail->send();


            $success_message = 'Verification Email sent to ' . $user_object->getUserEmail() . ', so before login first verify your email';
        }
        else
        {
            $error = 'Something went wrong try again';
        }
    }

}


?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Register | PHP Chat Application using Websocket</title>

    <!-- Bootstrap core CSS -->
    <link href="vendor-front/bootstrap/bootstrap.min.css" rel="stylesheet">

    <link href="vendor-front/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="vendor-front/parsley/parsley.css"/>

    <!-- Bootstrap core JavaScript -->
    <script src="vendor-front/jquery/jquery.min.js"></script>
    <script src="vendor-front/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="vendor-front/jquery-easing/jquery.easing.min.js"></script>

    <script type="text/javascript" src="vendor-front/parsley/dist/parsley.min.js"></script>
</head>

<body>

    <div class="containter">
        <br />
        <br />
        <h1 class="text-center">Chat Application in PHP & MySql using WebSocket - Email Verification</h1>
        
        <div class="row justify-content-md-center">
            <div class="col col-md-4 mt-5">
                <?php
                if($error != '')
                {
                    echo '
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                      '.$error.'
                      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                      </button>
                    </div>
                    ';
                }

                if($success_message != '')
                {
                    echo '
                    <div class="alert alert-success">
                    '.$success_message.'
                    </div>
                    ';
                }
                ?>
                <div class="card">
                    <div class="card-header">Register</div>
                    <div class="card-body">

                        <form method="post" id="register_form">

                            <div class="form-group">
                                <label>Enter Your Name</label>
                                <input type="text" name="user_name" id="user_name" class="form-control" data-parsley-pattern="/^[a-zA-Z\s]+$/" required />
                            </div>

                            <div class="form-group">
                                <label>Enter Your Email</label>
                                <input type="text" name="user_email" id="user_email" class="form-control" data-parsley-type="email" required />
                            </div>

                            <div class="form-group">
                                <label>Enter Your Password</label>
                                <input type="password" name="user_password" id="user_password" class="form-control" data-parsley-minlength="6" data-parsley-maxlength="12" data-parsley-pattern="^[a-zA-Z]+$" required />
                            </div>

                            <div class="form-group text-center">
                                <input type="submit" name="register" class="btn btn-success" value="Register" />
                            </div>

                        </form>
                        
                    </div>
                </div>
                
            </div>
        </div>
    </div>

</body>

</html>

<script>

$(document).ready(function(){

    $('#register_form').parsley();

});

</script>


index.php


Under this file we will make login page for this chat application.



<?php

session_start();

$error = '';

if(isset($_SESSION['user_data']))
{
    header('location:chatroom.php');
}

if(isset($_POST['login']))
{
    require_once('database/ChatUser.php');

    $user_object = new ChatUser;

    $user_object->setUserEmail($_POST['user_email']);

    $user_data = $user_object->get_user_data_by_email();

    if(is_array($user_data) && count($user_data) > 0)
    {
        if($user_data['user_status'] == 'Enable')
        {
            if($user_data['user_password'] == $_POST['user_password'])
            {
                $user_object->setUserId($user_data['user_id']);
                $user_object->setUserLoginStatus('Login');

                if($user_object->update_user_login_data())
                {
                    $_SESSION['user_data'][$user_data['user_id']] = [
                        'id'    =>  $user_data['user_id'],
                        'name'  =>  $user_data['user_name'],
                        'profile'   =>  $user_data['user_profile']
                    ];

                    header('location:chatroom.php');

                }
            }
            else
            {
                $error = 'Wrong Password';
            }
        }
        else
        {
            $error = 'Please Verify Your Email Address';
        }
    }
    else
    {
        $error = 'Wrong Email Address';
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Login | PHP Chat Application using Websocket</title>

    <!-- Bootstrap core CSS -->
    <link href="vendor-front/bootstrap/bootstrap.min.css" rel="stylesheet">

    <link href="vendor-front/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="vendor-front/parsley/parsley.css"/>

    <!-- Bootstrap core JavaScript -->
    <script src="vendor-front/jquery/jquery.min.js"></script>
    <script src="vendor-front/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="vendor-front/jquery-easing/jquery.easing.min.js"></script>

    <script type="text/javascript" src="vendor-front/parsley/dist/parsley.min.js"></script>
</head>

<body>

    <div class="containter">
        <br />
        <br />
        <h1 class="text-center">Chat Application in PHP & MySql using WebSocket - Login</h1>
        <div class="row justify-content-md-center mt-5">
            
            <div class="col-md-4">
               <?php
               if(isset($_SESSION['success_message']))
               {
                    echo '
                    <div class="alert alert-success">
                    '.$_SESSION["success_message"] .'
                    </div>
                    ';
                    unset($_SESSION['success_message']);
               }

               if($error != '')
               {
                    echo '
                    <div class="alert alert-danger">
                    '.$error.'
                    </div>
                    ';
               }
               ?>
                <div class="card">
                    <div class="card-header">Login</div>
                    <div class="card-body">
                        <form method="post" id="login_form">
                            <div class="form-group">
                                <label>Enter Your Email Address</label>
                                <input type="text" name="user_email" id="user_email"  class="form-control" data-parsley-type="email" required />
                            </div>
                            <div class="form-group">
                                <label>Enter Your Password</label>
                                <input type="password" name="user_password" id="user_password" class="form-control" required />
                            </div>
                            <div class="form-group text-center">
                                <input type="submit" name="login" id="login" class="btn btn-primary" value="Login" />
                            </div>
                        </form>
                    </div>  
                </div>
            </div>
        </div>
    </div>

</body>

</html>

<script>

$(document).ready(function(){
    
    $('#login_form').parsley();
    
});

</script>


verify.php


This file source code will verify user email address and it will enable user account for login into chat system.


<?php

//verify.php

$error = '';

session_start();

if(isset($_GET['code']))
{
    require_once('database/ChatUser.php');

    $user_object = new ChatUser;

    $user_object->setUserVerificationCode($_GET['code']);

    if($user_object->is_valid_email_verification_code())
    {
        $user_object->setUserStatus('Enable');

        if($user_object->enable_user_account())
        {
            $_SESSION['success_message'] = 'Your Email Successfully verify, now you can login into this chat Application';

            header('location:index.php');
        }
        else
        {
            $error = 'Something went wrong try again....';
        }
    }
    else
    {
        $error = 'Something went wrong try again....';
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Email Verify | PHP Chat Application using Websocket</title>

    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <!-- Bootstrap core JavaScript -->
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

</head>

<body>

    <div class="containter">
        <br />
        <br />
        <h1 class="text-center">PHP Chat Application using Websocket</h1>
        
        <div class="row justify-content-md-center">
            <div class="col col-md-4 mt-5">
            	<div class="alert alert-danger">
            		<h2><?php echo $error; ?></h2>
            	</div>
            </div>
        </div>
    </div>
</body>

</html>


chatroom.php


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.


<?php 
session_start();

if(!isset($_SESSION['user_data']))
{
	header('location:index.php');
}

require('database/ChatUser.php');

require('database/ChatRooms.php');

$chat_object = new ChatRooms;

$chat_data = $chat_object->get_all_chat_data();

$user_object = new ChatUser;

$user_data = $user_object->get_user_all_data();

?>

<!DOCTYPE html>
<html>
<head>
	<title>Chat application in php using web scocket programming</title>
	<!-- Bootstrap core CSS -->
    <link href="vendor-front/bootstrap/bootstrap.min.css" rel="stylesheet">

    <link href="vendor-front/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">

    <link rel="stylesheet" type="text/css" href="vendor-front/parsley/parsley.css"/>

    <!-- Bootstrap core JavaScript -->
    <script src="vendor-front/jquery/jquery.min.js"></script>
    <script src="vendor-front/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="vendor-front/jquery-easing/jquery.easing.min.js"></script>

    <script type="text/javascript" src="vendor-front/parsley/dist/parsley.min.js"></script>
	<style type="text/css">
		html,
		body {
		  height: 100%;
		  width: 100%;
		  margin: 0;
		}
		#wrapper
		{
			display: flex;
		  	flex-flow: column;
		  	height: 100%;
		}
		#remaining
		{
			flex-grow : 1;
		}
		#messages {
			height: 200px;
			background: whitesmoke;
			overflow: auto;
		}
		#chat-room-frm {
			margin-top: 10px;
		}
		#user_list
		{
			height:450px;
			overflow-y: auto;
		}

		#messages_area
		{
			height: 650px;
			overflow-y: auto;
			background-color:#e6e6e6;
		}

	</style>
</head>
<body>
	<div class="container">
		<br />
        <h3 class="text-center">PHP Chat Application using Websocket - Display User with Online or Offline Status</h3>
        <br />
		<div class="row">
			
			<div class="col-lg-8">
				<div class="card">
					<div class="card-header"><h3>Chat Room</h3></div>
					<div class="card-body" id="messages_area">
					<?php
					foreach($chat_data as $chat)
					{
						if(isset($_SESSION['user_data'][$chat['userid']]))
						{
							$from = 'Me';
							$row_class = 'row justify-content-start';
							$background_class = 'text-dark alert-light';
						}
						else
						{
							$from = $chat['user_name'];
							$row_class = 'row justify-content-end';
							$background_class = 'alert-success';
						}

						echo '
						<div class="'.$row_class.'">
							<div class="col-sm-10">
								<div class="shadow-sm alert '.$background_class.'">
									<b>'.$from.' - </b>'.$chat["msg"].'
									<br />
									<div class="text-right">
										<small><i>'.$chat["created_on"].'</i></small>
									</div>
								</div>
							</div>
						</div>
						';
					}
					?>
					</div>
				</div>

				<form method="post" id="chat_form" data-parsley-errors-container="#validation_error">
					<div class="input-group mb-3">
						<textarea class="form-control" id="chat_message" name="chat_message" placeholder="Type Message Here" data-parsley-maxlength="1000" data-parsley-pattern="/^[a-zA-Z0-9\s]+$/" required></textarea>
						<div class="input-group-append">
							<button type="submit" name="send" id="send" class="btn btn-primary"><i class="fa fa-paper-plane"></i></button>
						</div>
					</div>
					<div id="validation_error"></div>
				</form>
			</div>
			<div class="col-lg-4">
				<?php

				$login_user_id = '';

				foreach($_SESSION['user_data'] as $key => $value)
				{
					$login_user_id = $value['id'];
				?>
				<input type="hidden" name="login_user_id" id="login_user_id" value="<?php echo $login_user_id; ?>" />
				<div class="mt-3 mb-3 text-center">
					<img src="<?php echo $value['profile']; ?>" width="150" class="img-fluid rounded-circle img-thumbnail" />
					<h3 class="mt-2"><?php echo $value['name']; ?></h3>
					<a href="profile.php" class="btn btn-secondary mt-2 mb-2">Edit</a>
					<input type="button" class="btn btn-primary mt-2 mb-2" name="logout" id="logout" value="Logout" />
				</div>
				<?php
				}
				?>

				<div class="card mt-3">
					<div class="card-header">User List</div>
					<div class="card-body" id="user_list">
						<div class="list-group list-group-flush">
						<?php
						if(count($user_data) > 0)
						{
							foreach($user_data as $key => $user)
							{
								$icon = '<i class="fa fa-circle text-danger"></i>';

								if($user['user_login_status'] == 'Login')
								{
									$icon = '<i class="fa fa-circle text-success"></i>';
								}

								if($user['user_id'] != $login_user_id)
								{
									echo '
									<a class="list-group-item list-group-item-action">
										<img src="'.$user["user_profile"].'" class="img-fluid rounded-circle img-thumbnail" width="50" />
										<span class="ml-1"><strong>'.$user["user_name"].'</strong></span>
										<span class="mt-2 float-right">'.$icon.'</span>
									</a>
									';
								}

							}
						}
						?>
						</div>
					</div>
				</div>

			</div>
		</div>
	</div>
</body>
<script type="text/javascript">
	
	$(document).ready(function(){

		var conn = new WebSocket('ws://localhost:8080');
		conn.onopen = function(e) {
		    console.log("Connection established!");
		};

		conn.onmessage = function(e) {
		    console.log(e.data);

		    var data = JSON.parse(e.data);

		    var row_class = '';

		    var background_class = '';

		    if(data.from == 'Me')
		    {
		    	row_class = 'row justify-content-start';
		    	background_class = 'text-dark alert-light';
		    }
		    else
		    {
		    	row_class = 'row justify-content-end';
		    	background_class = 'alert-success';
		    }

		    var html_data = "<div class='"+row_class+"'><div class='col-sm-10'><div class='shadow-sm alert "+background_class+"'><b>"+data.from+" - </b>"+data.msg+"<br /><div class='text-right'><small><i>"+data.dt+"</i></small></div></div></div></div>";

		    $('#messages_area').append(html_data);

		    $("#chat_message").val("");
		};

		$('#chat_form').parsley();

		$('#messages_area').scrollTop($('#messages_area')[0].scrollHeight);

		$('#chat_form').on('submit', function(event){

			event.preventDefault();

			if($('#chat_form').parsley().isValid())
			{

				var user_id = $('#login_user_id').val();

				var message = $('#chat_message').val();

				var data = {
					userId : user_id,
					msg : message
				};

				conn.send(JSON.stringify(data));

				$('#messages_area').scrollTop($('#messages_area')[0].scrollHeight);

			}

		});
		
		$('#logout').click(function(){

			user_id = $('#login_user_id').val();

			$.ajax({
				url:"action.php",
				method:"POST",
				data:{user_id:user_id, action:'leave'},
				success:function(data)
				{
					var response = JSON.parse(data);

					if(response.status == 1)
					{
						conn.close();
						location = 'index.php';
					}
				}
			})

		});

	});
	
</script>
</html>



Build Real time Chat Application in PHP Mysql using WebSocket




action.php


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

//action.php

session_start();

if(isset($_POST['action']) && $_POST['action'] == 'leave')
{
	require('database/ChatUser.php');

	$user_object = new ChatUser;

	$user_object->setUserId($_POST['user_id']);

	$user_object->setUserLoginStatus('Logout');

	if($user_object->update_user_login_data())
	{
		unset($_SESSION['user_data']);

		session_destroy();

		echo json_encode(['status'=>1]);
	}
}


?>


src/Chat.php



<?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();


?>


composer.json



{
	"autoload": {
        "psr-4": {
            "MyApp\\": "src"
        }
    },
    
    "require": {
        "phpmailer/phpmailer": "^6.2",
        "cboden/ratchet": "v0.4"
    }
}






Wednesday, 6 January 2021

List of Popular Sites Built With Laravel


Laravel is one of the most used PHP (Personal Home Page) frameworks for the development of web applications. After launching the 5.4 version with Vue.js, Laravel is now available as a full-stack framework. Today, Laravel takes pride in building the best sorts of platforms for developers to draw more clients.

Laravel is an open-source software used for the development of web applications. There are some features that make it one of the most popular web frameworks available in the market:

  1. Laravel is available with the latest technological facilities. In that sense, it is quite modern compared to other frameworks.
  2. Laravel’s simple structure makes it accessible and popular. Hazardless maintenance is a crucial factor.
  3. For being a PHP-based MVC framework, users prefer Laravel above others.
  4. Its entire community is huge and well established.
  5. Gives in-depth documentation.

Here is a list of websites built with Laravel framework ---


1. Alison.com:


Alison was founded in the year 2007 in Galway, Ireland, and has become one of the biggest platforms for online education and skill training. Alison is a learning site with vast availability of online courses. You can enroll yourself in courses like marketing, health, science, lifestyle, humanities, etc. They provide both diploma and certificate courses with affordable facilities.

2. Deltanet Travel:


Deltanet Travel was built by tourism experts in Greece in the year 2001. While Deltanet manages tourism mainly in Greece, it also provides packages for customers traveling to different places. This company, with its steady growth, covers the facilities for lakhs of travelers since its inception.

3. Attendize.com:


Attendize is a free and open-source ticket-selling website based on the Laravel web framework. The platform is also used for event management.

4. Laracasts.com:


It helps you form web development skills on Laravel, Vue, and many others. The screencasts available for the working developer are languages, techniques, testing, tolling, and framework. It provides the courses starting from beginners to master level. Experts are ready to help the learners to solve the queries.

5. World Walking:


It is an application that encourages people to walk, where walking is a joyful activity and helps one to live a healthier life. The users can install the application on their smartphones to keep track of their walking history. The function of this web-based application is also controlled by Laravel. The app helps you to get day-to-day updates on your physical activity.



6. Watchseries.cr:


Watchseries.cr is an online platform to which you can subscribe to watch the online streaming of web series. This Laravel web application-based portal provides you with all the latest uploaded videos.

7. Rocket Rubbers:


Robert Rubbers has taken up an interesting initiative to promote safe sex to another level. They aim to extend the digital stores of Durex condoms to provide the simplest way of delivery.

8. Barchart.com:


It is a widely accessed online portal for getting to know the latest marketing information and trends from the US and UK. It also provides data from the Australian and Canadian stock market and other countries across Europe. Barchart.com, in a very simple manner, helps to display stock market quotes, customizable charts, and many others.

9. Monicahq.com:


If you, like many others, face trouble in remembering the names of the family members of your friends and relatives, then monicahq.com can help you to overcome that. Monica can store all this little but significant information to make you feel comfortable at the ceremonial gatherings.

10. LaravellO:


It is a popular portal that is accessed broadly by the community of Laravel developers. The portal is built exclusively on the Laravel web application. The signup module of LaravellO has an in-built integration with GitHub. When you plan to develop your own social apps, the worth of this platform increases. The platform helps the developers of Laravel effectively.

11. My Rank:


It is an online learning application for people in India. My Rank helps to promote input-based education to increase the students’ skill to crack competitive exams. This is a very useful platform for the students who aspire to crack exams like JEE MAINS, AIIMS, JEE ADVANCED, NEET, GATE, and JIPMER.

This is a limited discussion on the list of popular web applications that are built with Laravel. The immense popularity of the framework has helped to such massive growth of it while the list remains almost unending.

Author Name:- Harikrishna Kundariya

Biography:- Harikrishna Kundariya, a marketer, developer, IoT, ChatBot & Blockchain savvy, designer, co-founder, Director of eSparkBiz Technologies. His 8+ experience enables him to provide digital solutions to new start-ups based on IoT and ChatBot.

Complete Guide on JavaScript Frameworks for Frontend Development

Complete Guide on JavaScript Frameworks for Frontend Development


You don’t need to be tech-savvy to understand the concept of web and app development. We live in an increasingly technological world, and so it’s only normal to adapt to all the new changes.

Even if you don’t have the slightest idea about how web development works, we can lay it out for you. We all surf through the internet and watch things unfold, and you might know that everything runs smoothly because of programming.

Our computers need commands and a language to do all the tasks. So, that is how you get what you need. However, to paint a better picture for you, here’s a little introduction:

What is JavaScript?


So, mostly we have all seen how different web pages work, and different programming languages are responsible for everything. For instance, you see HTML and CSS that provide the format and style for websites.

However, JavaScript is a text-based language that is mainly responsible for creating interactive elements of a web page that help users take action. You log onto a website and see pop-ups, a sign up for a newsletter, a web form, compelling graphics, or anything moving around; that is because of JavaScript.

It has a lot of benefits because to stand out from the crowd; you need dynamic content that tempts your readers to engage with it. Today, everything is about making the user’s experience more positive and refreshing, so JavaScript is ideal for taking your web development up a notch. You can add any responsive elements you want to target any specific audience and boost your online traffic through JavaScript. Web developers are the reason behind us aimlessly surfing through different websites each day. You come across various styles, themes, sign up or log out buttons, required fields to check out a web page, all of this is done with the help of web developers.

For instance, it can be used in apps for small businesses, and you can create a catchy login button and have it do the job. Web developers create exciting features in web and mobile apps so you can have a memorable experience, and JS is behind it all.

What is the JavaScript Framework?


So, imagine you need to create a software or any application; you will need a step-by-step plan to accomplish this. That’s where frameworks come in handy because they are the blueprints of any app you want to build. It will help you gather everything you are going to need and help web developers achieve what they want.

Now, your application framework won’t do the job for you, but instead, it will help you using programs and libraries to create something that fulfils all your needs. JavaScript Framework is just a collection of different code libraries related to JavaScript.

It helps you save time and effort by providing you structure and assembling everything for you. You can reuse the same JavaScript code to create basic features for your applications. The frameworks help you add a little something to existing web pages instead of developing something new from scratch.

Frontend JavaScript Frameworks


There are two kinds of web and mobile app developers; backend and frontend. Now, the backend web developers are responsible for running the app, and frontend developers are responsible for how the app would work on its users’ devices.

There has been a lot of improvement and advancement in the tech and web development domain, so people no longer rely on HTML and CSS.

Nowadays, web applications can perform any task like paying a 2D/3D video, filling out required boxes, and engaging with the users. The whole world of all these new possibilities was introduced by Frontend JavaScript Frameworks that help your visitors stay hooked to the screen.

It is an application full of tactics that programmers can use to their advantage to create attention-grabbing and smooth web and mobile apps. It is all about making everything more convenient for you.



Why Do We Need the JS Frameworks?


Fundamentally, JavaScript Frameworks help achieve the following:

  • Give you all you require to make a web application
  • Furnish clients with formats to fabricate normal pieces of your web applications
  • Address an approach to make parts including directing, collecting information, structures, and static pages

You can’t just get by using catchy headlines and ads, you need to get your audience to engage with your content, and Frontend Web Development helps you build the most accessible user interface. JavaScript Frameworks are a high-level programming language, so they come with improved responsiveness.

1. Top JavaScript Frameworks


Following are by far the most commonly utilized JavaScript Frameworks:

1. React.js


This framework has been used for both Facebook and Instagram. It helps immensely with any kind of data management and lets you integrate with the rest of the code libraries. If you’re a web developer looking for something that helps you break down any code into little fragments, then the React.js framework is ideal for you.

2. Vue.js


Vue.js is the least complex option out of most of the JS frameworks. You can use it to create any kind of application because it has such a small size, so you can have all the features you want. Most web developers demand diversity when it comes to frameworks, and Vue.js will help you out in any department.

3. Angular


The angular framework gives you a wide platform and to explore any versatility you want. You can get several numbers activities done at the same time without facing any hassles.

Takeaway- A Definitive Guide on How Frontend JavaScript Frameworks Work


If you feel like you’re lost in the world of programming and coding, hopefully, this guide will help you out. It’s important to understand the basics and learn closely before you dive into the world of JavaScript frameworks.

You will need to choose the right type of framework for the kind of frontend development you wish to do, so make a wise choice. You can always opt for a framework that fulfils your criteria and then switches to another one for your project.

Author Bio:


Arslan Hassan is an electrical engineer with a passion for writing, designing, and anything tech-related. His educational background in the technical field has given him the edge to write on many topics. He occasionally writes blog articles for Apcelero.

Tuesday, 5 January 2021

Best Technologies For Web Development In 2021

In 2021, websites are playing an important role in attracting and retaining customers. Hence, more companies are investing money in web development technologies to improve their products and services. Top-notch employers are in a hunt for web developers these days. According to Computer Science Hero, about 5,000 companies are looking for qualified candidates, and there are over 181,000 open job listings.

If you’re thinking about becoming a website developer or seeking to stand out in the web development field, you should read this article. Learning front end and back end development skills are necessary to build a site. Consequently, here’s a list of the best technologies for web development in 2021.

Lavarel


Since data is among the most valuable resources, you’ll need to know how to build exceptional back end code if you want to stay relevant. PHP is a handy tech tool developers use to deal with data and architecture databases. Lavarel is a PHP framework used by many professionals in back end development.

Lavarel follows the Model-View-Controller architecture, and one of its most significant advantages is Blade Templating. Lavarel makes the job of coding complex back end solutions much more comfortable. Hence, developers can save time and build high-quality progressive web apps.

Digital solutions are often vulnerable to cyberattacks. Most web developers will need to build secure apps if they want to prevent attacks like SQL injections, DNS tunneling, or phishing. Lavarel takes security to the next level by providing developers with excellent authentication and authorization management tools.

Lavarel has a wide range of benefits, and it makes database migration hassle-free. Also, it has a huge community where developers can ask for help when necessary. In other words, building fantastic back end code will no longer be a challenge if you add Lavarel to your toolkit.

Angular


Angular is a JavaScript framework that’s becoming more and more popular day after day. It’s supported by Google and is available for front end development. Therefore, if you seek to build visually appealing websites, you can’t stop learning Angular. After all, it’s the preferred framework to create client-side applications in 2021.

By using Angular, web developers can build single-page applications. For that reason, creating high-performance web apps will no longer take your sleep. Keep in mind that single-page web apps load JavaScript, HTML, and CSS resources as soon as the site is loaded. To put it in another way, users will have an excellent experience and will feel engaged.

Web developers love angular because of its two-way data binding feature. This angular feature synchronizes the view and the model right after anything changes in one of them. Thus, updating the view and the model will be convenient, even in complex and large web apps.

Artificial Intelligence


In 2021, many companies have invested huge amounts of money in artificial intelligence. In the digital era, AI is helping companies provide more personalized services. Companies have widely used AI in automation, and when it’s about gathering and analyzing information, it can be handy. However, if you want to move in the right direction to success, you’ll need to learn how to implement AI-chatbots in your web apps.

AI-powered chatbots enable companies to improve their customer retention strategies by offering better customer service. Chatbots are available day and night, and no matter what time it is, any customer can find a solution to their issues.

On the other hand, many web developers use AI to automate some tasks in the development process. As a result, they will focus on other activities that may have a higher value.



Augmented Reality


If you seek to remain in the competition in 2021, you must acquire augmented reality skills. It has transformed the way retail companies offer their products. So, if you want to work in a company like IKEA, Home Depot, Sephora, or Gucci, you have no time to waste. At Sephora, for example, augmented reality has played an essential role in reducing return costs. Sephora’s Virtual Artist enables customers to try on any product and decide whether to buy it or not.

Voice Search


Although voice search has been used by users for many years already, it’s becoming more popular each day. Voice Search makes searching information on the web easy. When developers do not optimize websites for voice search technologies, they don’t appear in search results. It is convenient for companies who are looking to rank better in search engines.

By the end of 2021, most companies will probably modify their sites to take advantage of this tech trend. Consequently, you’ll need to learn how to boost websites’ load speed, ensure sites’ security, and enhance the UX. Otherwise, no matter how hard you try, voice search technologies won’t find your site on the web.

Conclusion


Since customers’ demands are higher, you must add these tools to your toolkit. Otherwise, staying in the game might become a struggle. Companies are looking for employees who seek to innovate the market. For that reason, you shouldn’t be afraid of going out of your comfort zone. Don’t forget that embracing change will help you move forward and meet employers’ expectations. Also, you should consider enrolling in a coding bootcamp. They are now among the best alternatives to learn from home.