facebook like messaging system with php

Facebook like messaging system with php




Hey guyz! In this tutorial i am going to teach you how to make a facebook like messaging system with php. Creating a facebook like messaging is not difficult So lets get started. First thing first Discalmer We will be using ajax for this real time facebook like messaging system but thats not idea because server send to many http connection, Instead we should use node.js or socket for this type of application. But by this tutorial you will get the understanding how the facebook like messaging system with php works.



Facebook like messaging system with php

MySql

First we have to make 1 database with name `fb_p_msg` and 3 table `user`, `conversation` and `message`.
facebook like messaging system with php

`user` table

`user` table will store all the user details like id,username,password,img and Id is unique
facebook like messaging system with php

`conversation` table

in `conversaton` we will be having 3 fields id,user_one and user_two. id is the converstion id which will be unique and user_one and user_two are the id of the users which are having conversation with each other
facebook like messaging system with php

`messages` table

in the `messages` table we will be storing messages. messages table will have 5 fields id,conversation_id,user_from,user_to,message. In `conversation_id` we will store the id of the conversation table, On `user_from` we will store the id of the user how send the message and on `user_to` we will store the id of the user who receive the message.`id` field is unique and on `message` field we store the message

-- Table structure for table `conversation`
--

CREATE TABLE IF NOT EXISTS `conversation` (
  `id` int(11) NOT NULL,
  `user_one` int(11) NOT NULL,
  `user_two` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `messages`
--

CREATE TABLE IF NOT EXISTS `messages` (
  `id` int(11) NOT NULL,
  `conversation_id` int(11) NOT NULL,
  `user_from` int(11) NOT NULL,
  `user_to` int(11) NOT NULL,
  `message` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- Table structure for table `user`
--

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL,
  `username` text NOT NULL,
  `password` text NOT NULL,
  `img` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `user`
--

INSERT INTO `user` (`id`, `username`, `password`, `img`) VALUES
(1, 'husain', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-1.jpg'),
(2, 'hunk', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-2.jpg'),
(3, 'hackerkernel', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-3.jpg'),
(4, 'murtaza', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-4.jpg'),
(5, 'qut', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-5.jpg'),
(6, 'sakina', 'cc03e747a6afbbcbf8be7668acfebee5', 'img/dp-6.jpg');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `conversation`
--
ALTER TABLE `conversation`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `user`
--
ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `conversation`
--
ALTER TABLE `conversation`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7;
/*!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 */;

File Structure

facebook like messaging system with php

connect.php – Connect to mysql database

We will connect to mysql database using mysqli

<?php
	$con = mysqli_connect("localhost","root","","fb_p_msg");
?>

index.php – login page

in index.php we are taking username and password from the user and if the username and password matches a entry in the `user` table we log the user in, store its id in the session and send him to message.php

<?php require_once("connect.php"); ?>
<!DOCTYPE html>
<html>
<head>
	<title>Facebook Style Private Messaging System in php</title>
	<link rel="stylesheet" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">

</head>
<body style="background:#eee;">
	<!-- login -->
	<div class="login-container">
		<?php
			/*login script*/
			if(isset($_POST&#91;'login'&#93;)){
				$username = trim(mysqli_real_escape_string($con, $_POST&#91;'username'&#93;));
				$password = trim(mysqli_real_escape_string($con, $_POST&#91;'password'&#93;));
				$md5password = md5($password);
				//check user and password match to the database
				$query = mysqli_query($con,"SELECT * FROM `user` WHERE username='$username' AND password='$md5password'");
				//check how much rows return
				if(mysqli_num_rows($query) == 1){
					//login the user

					//get the id of the user
					$fetch = mysqli_fetch_assoc($query);
					//start the session and store user id in the session
					session_start();
					$_SESSION&#91;'id'&#93; = $fetch&#91;'id'&#93;;
					$_SESSION&#91;'username'&#93; = $fetch&#91;'username'&#93;;
					header("Location: message.php");
				}else{
					//show error message
					echo "<div class='alert alert-danger'>Invalid username Or password.</div>";
				}
			}
		?>
		<h1>Login</h1>
		<form action="index.php" method="post">
			<div class="form-group">
				<input required type="text" class="form-control" name="username" placeholder="Enter Your username.">
			</div>
			<div class="form-group">
				<input required type="password" class="form-control" name="password" placeholder="Enter Your password.">
			</div>
			<input type="submit" value="login"  name="login" class="btn btn-primary btn-block">
		</form>
		<br>
		<span><b>User & pass:</b> husain / test123</span><br>
		<span><b>User & pass:</b> hunk / test123</span><br>
		<span><b>User & pass:</b> hackerkernel / test123</span><br>
		<span><b>User & pass:</b> murtaza / test123</span><br>
		<span><b>User & pass:</b> qut / test123</span><br>
		<span><b>User & pass:</b> sakina / test123</span>
	</div>
	<!-- /login -->
</body>
</html>

message.php – messaging area

  1. First we will check user login status if he is login we will save $_SESSION['id'] into $user_id else send him to index.php
  2. On line 31 we will fetch all the users from the `user` table except us (The logged in user)
  3. On line 47 we will wait for the loggedin user to click on other users profile and when they click on the user we will store the id of that user in $user_two. Then we will try to fetch the conversation between then from `conversation` table, If the conversation has already started we will fetch its id and store it in $conversation_id else we will start a new conversation and then store its id in $conversation_id
  4. On line 79 we will store $conversation_id,$user_id, $user_two into a input hidden field in base64 encrypted format
<?php
	//connect to the database
	require_once("connect.php");
	session_start();
	//shop not login  users from entering 
	if(isset($_SESSION&#91;'id'&#93;)){
		$user_id = $_SESSION&#91;'id'&#93;;
	}else{
		header("Location: index.php");
	}
?>
<!DOCTYPE html>
<html>
<head>
	<title>Facebook Style Private Messaging System in php</title>
	<link rel="stylesheet" href="css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
	<center>
		<a href="http://blog.hackerkernel.com/2015/09/17/jqueryui-autocomplete-dropdown-with-php-and-json" target="_blank">Tutorial</a> / 
		<a href="http://demo.hackerkernel.com/download.php?url=1ozuzawpkwuzjd3uzmomwbrt5pnzpjsa" target="_blank">Download Script</a> / 
		<a href="http://hackerkernel.com/contact.php" target="_blank">Want Me to Work on your Dream Project</a> / 
		<br>
		<strong>Welcome <?php echo $_SESSION&#91;'username'&#93;; ?>  <a href="logout.php">logout</a></strong>
	</center>
	
	<div class="message-body">
		<div class="message-left">
			<ul>
				<?php
					//show all the users expect me
					$q = mysqli_query($con, "SELECT * FROM `user` WHERE id!='$user_id'");
					//display all the results
					while($row = mysqli_fetch_assoc($q)){
						echo "<a href='message.php?id={$row&#91;'id'&#93;}'><li><img src='{$row&#91;'img'&#93;}'> {$row['username']}</li></a>";
					}
				?>
			</ul>
		</div>

		<div class="message-right">
			<!-- display message -->
			<div class="display-message">
			<?php
				//check $_GET&#91;'id'&#93; is set
				if(isset($_GET&#91;'id'&#93;)){
					$user_two = trim(mysqli_real_escape_string($con, $_GET&#91;'id'&#93;));
					//check $user_two is valid
					$q = mysqli_query($con, "SELECT `id` FROM `user` WHERE id='$user_two' AND id!='$user_id'");
					//valid $user_two
					if(mysqli_num_rows($q) == 1){
						//check $user_id and $user_two has conversation or not if no start one
						$conver = mysqli_query($con, "SELECT * FROM `conversation` WHERE (user_one='$user_id' AND user_two='$user_two') OR (user_one='$user_two' AND user_two='$user_id')");

						//they have a conversation
						if(mysqli_num_rows($conver) == 1){
							//fetch the converstaion id
							$fetch = mysqli_fetch_assoc($conver);
							$conversation_id = $fetch&#91;'id'&#93;;
						}else{ //they do not have a conversation
							//start a new converstaion and fetch its id
							$q = mysqli_query($con, "INSERT INTO `conversation` VALUES ('','$user_id',$user_two)");
							$conversation_id = mysqli_insert_id($con);
						}
					}else{
						die("Invalid $_GET ID.");
					}
				}else {
					die("Click On the Person to start Chating.");
				}
			?>
			</div>
			<!-- /display message -->

			<!-- send message -->
			<div class="send-message">
				<!-- store conversation_id, user_from, user_to so that we can send send this values to post_message_ajax.php -->
				<input type="hidden" id="conversation_id" value="<?php echo base64_encode($conversation_id); ?>">
				<input type="hidden" id="user_form" value="<?php echo base64_encode($user_id); ?>">
				<input type="hidden" id="user_to" value="<?php echo base64_encode($user_two); ?>">
				<div class="form-group">
					<textarea class="form-control" id="message" placeholder="Enter Your Message"></textarea>
				</div>
				<button class="btn btn-primary" id="reply">Reply</button> 
				<span id="error"></span>
			</div>
			<!-- / send message -->
		</div>
	</div>
	<script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="js/script.js"></script>	
</body>
</html>

style.css

Their are some basic style of messaging system and the custom scroll bar is designed Noman Ali Samejo

/*login*/
.login-container{
	display: block;
	width: 330px;
	height: 350px;
	padding: 0 20px 20px 20px;
	background: white;
	border: 1px solid #ccc;
	border-radius: 5px;
	/*verticaly center*/
	position: absolute;
	top: 50%;
	left: 50%;
	margin-top: -165px;
	margin-left: -165px;
}
::-webkit-scrollbar{
	height:10px;
	width:10px;
	background:#FFF;
}
::-webkit-scrollbar-thumb{
	background:#BBB;
	border:solid 2px #FFF;
}
::-webkit-scrollbar-thumb:hover{
	background:#888;
}
::-moz-scrollbar{
	height:10px;
	width:10px;
	background:#FFF;
}
::-moz-scrollbar-thumb{
	background:#BBB;
	border:solid 2px #FFF;
}
::-moz-scrollbar-thumb:hover{
	background:#888;
}
/*message*/
.message-body{
	display: block;
	height: 600px;
	width: 70%;
	margin:0px auto;
	border:1px solid #ccc;
}
.message-left{
	display: block;
	height: 100%;
	width: 30%;
	float: left;
	overflow-y: scroll;
	border-right: 1px solid #ccc;
}
.message-right{
	display: block;
	height: 100%;
	width: 70%;
	float: left;
}
.message-left ul{
	list-style: none;
	margin: 0;
	padding: 0;
	width: 100%;
}
.message-left ul a{
	text-decoration: none;
}
.message-left ul a li{
	padding: 5px;
	border-bottom: 1px solid #ccc;
	font-weight: bold;
	color: black;
}
.message-left ul a li img{
	height: 50px;
	width: 50px;
}
.message-left ul a li:hover{
	background: #EBEDF5;
}
.message-left ul a li.active{
	background: #6B83B3;
}
.message-right .display-message{
	display: block;
	height: 80%;
	width: 100%;
	border-bottom: 1px solid #ccc;
	overflow-y:scroll;
}
.message-right .send-message{
	height: 20%;
	background: #eee;
	padding: 10px;
}
.display-message .message{
	min-height: 60px;
	padding: 5px;
}
.message .img-con{
	width: 10%;
	float: left;
	height: inherit;
}
.message .img-con > img{
	height: 50px;
	width: 50px;
}
.message .text-con{
	width: 90%;
	float: left;
	height: inherit;
}
hr{
	margin-top: 0;
	margin-bottom: 0;
	border-top:1px solid #ccc;
}

Script.js

in script.js we will post messages by ajax

  1. On line 3 we will wait for the #reply button to be click and when the button is clicked we will get message,conversation_id,user_from,user_to and send then to post_message_ajax.php
  2. On line 22 we are getting the conversation_id and then we are loading get_message_ajax.php into .display-message on a interval of every 2 second
$(document).ready(function(){
	/*post message via ajax*/
	$("#reply").on("click", function(){
		var message = $.trim($("#message").val()),
			conversation_id = $.trim($("#conversation_id").val()),
			user_form = $.trim($("#user_form").val()),
			user_to = $.trim($("#user_to").val()),
			error = $("#error");

		if((message != "") && (conversation_id != "") && (user_form != "") && (user_to != "")){
			error.text("Sending...");
			$.post("post_message_ajax.php",{message:message,conversation_id:conversation_id,user_form:user_form,user_to:user_to}, function(data){
				error.text(data);
				//clear the message box
				$("#message").val("");
			});
		}
	});


	//get message
	c_id = $("#conversation_id").val();
	//get new message every 2 second
	setInterval(function(){
		$(".display-message").load("get_message_ajax.php?c_id="+c_id);
	}, 2000);

	$(".display-message").scrollTop($(".display-message")[0].scrollHeight);
});

post_message_ajax.php

in this page we will decrypt the $conversation_id, $user_from, $user_to and then store the message into `message` table

<?php
	require_once("connect.php");
	//post message
	if(isset($_POST&#91;'message'&#93;)){
		$message = mysqli_real_escape_string($con, $_POST&#91;'message'&#93;);
		$conversation_id = mysqli_real_escape_string($con, $_POST&#91;'conversation_id'&#93;);
		$user_form = mysqli_real_escape_string($con, $_POST&#91;'user_form'&#93;);
		$user_to = mysqli_real_escape_string($con, $_POST&#91;'user_to'&#93;);

		//decrypt the conversation_id,user_from,user_to
		$conversation_id = base64_decode($conversation_id);
		$user_form = base64_decode($user_form);
		$user_to = base64_decode($user_to);

		//insert into `messages`
		$q = mysqli_query($con, "INSERT INTO `messages` VALUES ('','$conversation_id','$user_form','$user_to','$message')");
		if($q){
			echo "Posted";
		}else{
			echo "Error";
		}
	}
?>

get_message_ajax.php

we will decrypt the conversation_id and then fetch all the relevant messages

<?php
    require_once("connect.php");
    if(isset($_GET&#91;'c_id'&#93;)){
        //get the conversation id and
        $conversation_id = base64_decode($_GET&#91;'c_id'&#93;);
        //fetch all the messages of $user_id(loggedin user) and $user_two from their conversation
        $q = mysqli_query($con, "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'");
        //check their are any messages
        if(mysqli_num_rows($q) > 0){
            while ($m = mysqli_fetch_assoc($q)) {
                //format the message and display it to the user
                $user_form = $m['user_from'];
                $user_to = $m['user_to'];
                $message = $m['message'];

                //get name and image of $user_form from `user` table
                $user = mysqli_query($con, "SELECT username,img FROM `user` WHERE id='$user_form'");
                $user_fetch = mysqli_fetch_assoc($user);
                $user_form_username = $user_fetch['username'];
                $user_form_img = $user_fetch['img'];

                //display the message
                echo "
                            <div class='message'>
                                <div class='img-con'>
                                    <img src='{$user_form_img}'>
                                </div>
                                <div class='text-con'>
                                    <a href='#''>{$user_form_username}</a>
                                    <p>{$message}</p>
                                </div>
                            </div>
                            <hr>";

            }
        }else{
            echo "No Messages";
        }
    }

?>

logout.php

logout the user and destroy his session

<?php
	session_start();
	session_destroy();
	header("Location: index.php");
?>

12 thoughts to “Facebook like messaging system with php”

  1. beautiful work from you. keep it up. however, i am unable to login on my offline server. it keeps saying invalid username/password

Leave a Reply

Your email address will not be published. Required fields are marked *