Let's start with the database, let's assume that our database name is chat.
We need to four tables
user
images
sendedMessage
session
See the structure of the tables in the following figure
Let's assume that XAMPP has been installed, if not download it and see how to install it
here
Open the browser and type https://localhost/dashboard/
And then click on phpmyadmin, we will see our tables created in the database chat
To create the tables you need to the following sql script
User table
CREATE TABLE `user` (
`iduser` int(11) NOT NULL,
`nickname` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`password` text NOT NULL,
`idimage` int(11) DEFAULT NULL,
`state` int(11) NOT NULL DEFAULT 0,
`insertdate` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`updatedate` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `user`
ADD PRIMARY KEY (`iduser`);
ALTER TABLE `user`
MODIFY `iduser` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
Images table
CREATE TABLE `images` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`content` blob NOT NULL,
`type` varchar(20) NOT NULL,
`size` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `images`
ADD PRIMARY KEY (`id`);
ALTER TABLE `images`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=158;
sendedmessage table
CREATE TABLE `sendedmessage` (
`idsender` int(11) NOT NULL,
`idreceiver` int(11) NOT NULL,
`message` varchar(500) NOT NULL,
`message_read` int(11) NOT NULL DEFAULT 1,
`sound` int(11) NOT NULL DEFAULT 1,
`insertdate` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
session table
CREATE TABLE `session` (
`iduser` int(11) NOT NULL,
`ip` varchar(30) NOT NULL,
`insertdate` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Step - 2 -
Now let's move on to the PHP Backend part
In all the application files I used the class 'DBClass' declared in the file db.dzo.class.php
<?php
class DBClass {
private $conn;// The database connection variable
public function __construct($con)
{
$this->conn =$con;
}
public function DBClass()
{
}
// the methods which I will show later
....
....
....
}
?>
In this class I have grouped all the methods that I need like insertion into the database
First to connect the user with nickname and password we need to the method ConnectUser
<?php
function connectUser($nickname,$password){
$this->conn->query("SET NAMES UTF8");
$this->conn->query('SET CHARACTER SET utf8');
$query = "select iduser,password from user where nickname='".$nickname."'";
$result = $this->conn->query ( $query );
$iduser=0;
if ($result){
if (mysqli_num_rows ( $result ) > 0)
{
$row = @mysqli_fetch_row ( $result );
$iduser=$rowΎ];
if (!password_verify($password, $rowΏ]))
{
return "Wrong password";
}
else
{
$msgerr= $this->updSessionTable($iduser);
if(!empty($msgerr))
{
return $msgerr;
}
}
}
else
{
return "User not found !";
}
}
else
{
return mysqli_error();
}
return "id".$iduser;
}
//get the user email from the user ID
function GetUserFromId($iduser) // return the user email
{
$email="";
$query = 'select email from user where iduser='.$iduser;
$result = $this->conn->query ( $query );
if ($result){
if (mysqli_num_rows ( $result ) > 0){
$row = @mysqli_fetch_row ( $result );
$email=$rowΎ];
}
}
return $email;
}
//delete the user session from the database
function DeleteSessionTable($email)// When the user logout , we delete his session from the database
{
$query = "delete from session where iduser in ";
$query.= "(select iduser from user where email='".$email."')";
$result = $this->conn->query ( $query );
if (! $result)
{
return mysqli_error ();
}
return "";
}
//create a user session
function UpdSessionTable($iduser)
{
$query = "";
$email=$this->GetUserFromId($iduser);
$msgerr=$this->DeleteSessionTable($email);
if(!empty($msgerr)) return $msgerr;
$query = "INSERT INTO session (`iduser`,`ip`,`insertdate`) VALUES
($iduser,'".$this->getIp()."',now())";
$result = $this->conn->query ( $query );
if (! $result)
{
return mysqli_error ();
}
$_SESSION[$email]=$email;
// Update the user state (online state) when connected.
$this->UpdUserState($iduser,1);
return "";
}
?>
To add the avatar, we need to this method AddAvatar to add the image in the database
To get or change the user state we need to these methods
<?php
function getState($iduser)
{
$query = "select state from user where iduser=".$iduser;
$result = $this->conn->query ( $query );
$row = mysqli_fetch_row($result);
return $rowΎ];
}
function updUserState($iduser,$state)
{
$query = "update user set state=".$state." where iduser=".$iduser;
$result = $this->conn->query ( $query );
}
?>
To add a new user or to update an existant user we need to these methods:
The first method shows the dialog box at the client level that allows the user to input his data,
instead the second, add the user data in the database.
To send message from user to other, we need to the method sendmessage
We need also to the method RefreshMessage that allows to display the message at the client level
<?php
function SendMessage($iduser_from,$iduser_to,$message)
{
$query = "INSERT INTO `messages` (message,iduser_from,iduser_to,inserdate,state) VALUES ";
$query.=('$message',$iduser_from,$iduser_to, now(),0)";
$result = $this->conn->query ( $query );
if (! $retval)
{
return mysqli_error ();
}
return $message;
}
function RefreshMessage($from,$to)
{
$html= '<table border="0" width="100%" height="90%">';
$sql="SELECT idsender,idreceiver ,message FROM sendedmessage where (idsender=$from and idreceiver=$to)";
$sql="or (idsender=$to and idreceiver=$from) order by insertdate asc";
$result = $this->conn->query ( $sql );
if ($result)
{
while($row = @mysqli_fetch_row ( $result ))
{
if($rowΎ]==$to)
{
$html .= '<tr><td style="text-align:right;" ><div class="containerChatFrom">'.$rowΐ].'</td></tr>';
}
else
{
$html .= '<tr><td style="text-align:left;"><div class="containerChatTo">'.$rowΐ].'</td></tr>';
}
}
}
$html .= '</table>';
return $html;
}
?>
To view all the registered users, we need to the following method:
You can notice that we also manage the beep at every new arrived message
the value of the variable 'sound' is 1 when the message is sended, if the reciever open the message
sound is set to 0.
We will see how play the sound at the client level with Javascript
To stop the sound we need to the following method
<?php
function StopSound($iduser)
{
$sql="update sendedmessage set sound=0 where idreceiver=$iduser";
$this->conn->query( $sql );
}
?>
We need also to the following php files where we call all the methods defined in our class DBClass
1- chatUser.php
<?php
require "db.dzo.class.php";
$con=mysqli_init();// Initialize the MySQL database connection
if (!$con)
{
die("mysqli_init failed");
}
if(!mysqli_real_connect($con,"127.0.0.1","root","","chat")) // Connect to the database chat
{
die("Connect Error: " . mysqli_connect_error());
}
$dbconnect = new DBClass($con);// get the instance of DBClass
$to = $_REQUEST['to']; // read the parameter 'to' from the request where to is the user ID
$from= $_REQUEST['from']; // read the parameter 'from' from the request where from is the user ID
$html=$dbconnect->RefreshChat($from,$to,"");// call the RefreshChat method
echo $html; // Write the html code returned by the method
?>
I used AJAX which is a developer's dream, because you can:
.Read data from a web server - after the page has loaded
.Update a web page without reloading the page
.Send data to a web server - in the background
The javascript file chat.js
The most important function is sendData, has as parameters
data : of FormData type
action : the php file which contains the action
header : 1 to set the header Content-Type
divinnerHtml: the html code returned after the execution of the action (php file)
Example:
This javascript code allows us to send a message from sender to reciever, the data to send are:
the user ID of the sender, the user ID of the reciever and the message
the action is sendMessage.php that we have seen before, and the result (divinnerHtml) will be returned in the div
having the id 'users'.
function sendMessageTo()
{
var from=document.getElementById("sender").value;
var to=document.getElementById("reciever").value;
document.getElementById("message").value.trim();
if(document.getElementById("message").value!="")
{
var data = new FormData();
data.append("from", from);
data.append("to", to);
data.append("message", document.getElementById("message").value);
sendData(data,"sendMessage.php",0,"users");
}
}
function sendData(data,action,header,divinnerHtml)
{
var location = window.location;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr)
{
xhr.open("POST", action, true);
if(header==1)
{
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;text/html; charset=utf-8");
}
xhr.send(data);
xhr.onreadystatechange = display_data;
}
else
{
alert('Sorry, your browser does not support this.;');
}
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
endProgress();
if(divinnerHtml=="head"){
document.getElementById(divinnerHtml).innerHTML =
document.getElementById(divinnerHtml).innerHTML+ xhr.responseText;
return;
}
else
{
if(divinnerHtml=="disconnect")
{
window.location = "http://localhost/CHAT/";
}
else
{
if(divinnerHtml!="sound")
{
document.getElementById(divinnerHtml).innerHTML = xhr.responseText;
}
}
}
if(action=="updUser.php")
{
var t=xhr.responseText.trim();
var j='OK';
if(t==j)
{
goToHome();
}
else
{
document.getElementById(divinnerHtml).style.display="block";
}
}
else
{
if (divinnerHtml=="dlguser") // to create new user or update user data
{
document.getElementById(divinnerHtml).style.display="block";
}
if(action=="sendMessage.php" || action=="chatUser.php" || action=="refreshChat.php")
{
var objDiv = document.getElementById("divChat");
objDiv.scrollTop = objDiv.scrollHeight;
if(action=="sendMessage.php")
{
document.getElementById("message").focus();//set focus on input text message
}
}
if(action=="refreshUsers.php")
{
var iduser=document.getElementById("sender").value;
var elm=document.getElementById("sound_mess");
if(elm)
{
if(elm.value=="1")
{
var snd = new Audio("audio/notify.mp3"); //sound
snd.play();
var data = new FormData();
data.append("iduser", iduser);
sendData(data,"stopSound.php",0,"sound");
}
}
}
}
}
}
}
return;
}
function OverUser(user,indice) //On Mouse Over the user avatar
{
document.getElementById("selectedUser"+indice).innerHTML
="<font color=\"blue\"><span><b>"+user+"</b></span></font>";
}
function LeaveUser(user,indice) // On Mouse Leave user avatar
{
document.getElementById("selectedUser"+indice).innerHTML
="<font color=\"black\"><span><b>"+user+"</b></span></font>";
}
//Reload the page
function goToHome()
{
location.reload();
}
function sendMessageToKeydown() //Send message with 'return' key
{
if(event.keyCode==13)
{
sendMessageTo();
}
}
function sendMessageTo()
{
var from=document.getElementById("sender").value;
var to=document.getElementById("reciever").value;
document.getElementById("message").value.trim();
if(document.getElementById("message").value!="")
{
var data = new FormData();
data.append("from", from);
data.append("to", to);
data.append("message", document.getElementById("message").value);
sendData(data,"sendMessage.php",0,"users");
}
}
function StartChat(from,to) / Start the chat with other user
{
startProgress();
document.getElementById("reciever").value=to;
var data = new FormData();
data.append("from", from);
data.append("to", to);
sendData(data,"chatUser.php",0,"users");
}
function exitChat() // End chat
{
startProgress();
sendData(null,"logout.php",0,"disconnect");
}
function New_User() // Create new user
{
startProgress();
var data = new FormData();
data.append("iduser", 0);
sendData(data,"getUser.php",0,"dlguser");
}
function transfererImage(iduser) // Upload the picture on server to store it in the database
{
startProgress();
var fichier= document.getElementById("userfileUser").filesΎ];
var formdata = new FormData();
formdata.append("iduser", iduser);
formdata.append("userfile", fichier);
sendData(formdata,"addAvatar.php",0,"divimaprofile");
}
function closedlguser()
{
document.getElementById("dlguser").style.display="none";
}
//--------------------------------------------------
function closediv(ediv){
document.getElementById(ediv).style.display="none";
}
function elimphotoprofile(id){
var formdata = new FormData();
formdata.append("id", id);
sendData(formdata,"delPhoto.php",0,"divimaprofile");
}
function HandleBrowseClickUser() //To load user avatar
{
var fileinput = document.getElementById("userfileUser");
fileinput.click();
}
function HandlechangeUserHandlechangeUser()
{
var fileinput = document.getElementById("userfileUser");
var textinput = document.getElementById("filenameUser");
textinput.value = fileinput.value;
}
function saveuser(id) // Save user data
{
if(document.getElementById("email").value=="")
{
document.getElementById("err").innerHTML='<font color="red">Email required</font>';
return;
}
if(document.getElementById("nickname").value=="")
{
document.getElementById("err").innerHTML='<font color="red">Nickname required</font>';
return;
}
if(document.getElementById("password").value=="")
{
document.getElementById("err").innerHTML='<font color="red">Password required</font>';
return;
}
startProgress();
var fdata=new FormData();
fdata.append("email",document.getElementById("email").value);
fdata.append("nickname",document.getElementById("nickname").value);
fdata.append("password",document.getElementById("password").value);
if(!document.getElementById("vidimage"))
{
fdata.append("idimage",document.getElementById("idimage").value);// Avatar id
}
else
{
fdata.append("idimage",document.getElementById("vidimage").value);
}
fdata.append("iduser",id);
sendData( fdata,"updUser.php",0,"err");
}
//--------------------------------------
function update_user(iduser){ // Show the user dialog
startProgress();
var data = new FormData();
data.append("iduser", iduser);
sendData(data,"getUser.php",0,"dlguser");
}
function login()// Connect
{
var formdata = new FormData();
formdata.append("nickname", document.getElementById("nicknameLogin").value);
formdata.append("password", document.getElementById("passwordLogin").value);
startProgress();
var xhr;
if (window.XMLHttpRequest)
{ // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "connectTosite.php", true);
xhr.send(formdata);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
endProgress();
var t=xhr.responseText.trim();
var j="CONNECTED";
if(t==j)
{
location.reload();
return;
}
else
{
document.getElementById("errlogin").innerHTML=xhr.responseText;
return;
}
}
}
return;
}
}
function startProgress()// Show then Progress gif animated
{
document.body.style.cursor="progress";
document.getElementById("idprogress").style.display="block";
}
function endProgress(){ // Hide the progress gif animated
document.body.style.cursor="auto";
document.getElementById("idprogress").style.display="none";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
Like most websites, we use data file small
dimensions that are saved on your computer, tablet, mobile phone or other device
Mobile (collectively referred to as 'device') to record certain data whenever
login or interact with our sites, services, apps, messaging systems
and strumenti.I names and specific types of cookies used can change over time.
To help you better understand the rules and \ 'use of such technology, the following are
some terms and their definitions:
Cookies: small text files (usually formed by letters and numbers) that are saved
in memory of the browser or the device when you visit a website or display a message.
Cookies enable a website to recognize a particular device or browser. There
different types of cookies:
Session cookies expire at the end of the browser session and allow us to
connect your actions during that specific session.
Persistent cookies are instead stored in your device even after the end
the browser session and let you remember your preferences or actions at multiple sites.
First-party cookies are set by the site you're visiting.
The third-party cookies are set by a third party site than the site you are visiting.
Cookies can be disabled or removed using the tools available in most
browsers. The cookie preferences must be set separately
for each browser used, because each offers features and specific options.