In this tutorial, we will be creating a simple web-based chat application with PHP and jQuery. This sort of utility would be perfect for a live support system for your website.
This tutorial was updated recently to make improvements in the chat app.
The chat application we will be building today will be quite simple. It will include a login and logout system, AJAX-style features, and support for multiple users.
We will start this tutorial by creating our first file, called index.php.
lang="en">
charset="utf-8" />
Tuts+ Chat Application
name="description" content="Tuts+ Chat Application" />
rel="stylesheet" href="style.css" />
id="wrapper">
id="menu">
class="welcome">Welcome,
class="logout"> id="exit" href="#">Exit Chat
id="chatbox">
name="message" action="">
name="usermsg" type="text" id="usermsg" />
name="submitmsg" type="submit" id="submitmsg" value="Send" />
type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js">
type="text/javascript">
// jQuery Document
$(document).ready(function () <>);
We will now add some CSS to make our chat application look better than with the default browser styling. The code below will be added to our style.css file.
margin: 0;
padding: 0;
body
margin: 20px auto;
font-family: "Lato";
font-weight: 300;
form
padding: 15px 25px;
display: flex;
gap: 10px;
justify-content: center;
form label
font-size: 1.5rem;
font-weight: bold;
input
font-family: "Lato";
color: #0000ff;
text-decoration: none;
a:hover
text-decoration: underline;
#wrapper,
#loginform
margin: 0 auto;
padding-bottom: 25px;
background: #eee;
width: 600px;
max-width: 100%;
border: 2px solid #212121;
border-radius: 4px;
#loginform
padding-top: 18px;
text-align: center;
#loginform p
padding: 15px 25px;
font-size: 1.4rem;
font-weight: bold;
#chatbox
text-align: left;
margin: 0 auto;
margin-bottom: 25px;
padding: 10px;
background: #fff;
height: 300px;
width: 530px;
border: 1px solid #a7a7a7;
overflow: auto;
border-radius: 4px;
border-bottom: 4px solid #a7a7a7;
#usermsg
flex: 1;
border-radius: 4px;
border: 1px solid #ff9800;
#name
border-radius: 4px;
border: 1px solid #ff9800;
padding: 2px 8px;
#submitmsg,
#enter
background: #ff9800;
border: 2px solid #e65100;
color: white;
padding: 4px 10px;
font-weight: bold;
border-radius: 4px;
.error
color: #ff0000;
#menu
padding: 15px 25px;
display: flex;
#menu p.welcome
flex: 1;
a#exit
color: white;
background: #c62828;
padding: 4px 8px;
border-radius: 4px;
font-weight: bold;
.msgln
margin: 0 0 5px 0;
.msgln span.left-info
color: orangered;
.msgln span.chat-time
color: #666;
font-size: 60%;
vertical-align: super;
.msgln b.user-name, .msgln b.user-name-left
font-weight: bold;
background: #546e7a;
color: white;
padding: 2px 4px;
font-size: 90%;
border-radius: 4px;
margin: 0 5px 0 0;
.msgln b.user-name-left
background: orangered;
There's nothing special about the above CSS other than the fact that some ids or classes, which we have set a style for, will be added a bit later.
Now we will implement a simple form that will ask the user their name before continuing further.
session_start();
if(isset($_POST['enter']))
if($_POST['name'] != "")
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
else
echo 'Please type in a name';
function loginForm()
echo'
Please enter your name to continue!
The loginForm() function we created is composed of a simple login form which asks the user for their name. We then use an if and else statement to verify that the person entered a name. If the person entered a name, we set that name as $_SESSION['name'] . Since we are using a cookie-based session to store the name, we must call session_start() before anything is outputted to the browser.
One thing that you may want to pay close attention to is that we have used the htmlspecialchars() function, which converts special characters to HTML entities, therefore protecting the name variable from falling victim to cross-site scripting (XSS). Later, we will also add this function to the text variable that will be posted to the chat log.
In order to show the login form in case a user has not logged in, and hence has not created a session, we use another if and else statement around the #wrapper div and script tags in our original code. In the opposite case, this will hide the login form and show the chat box if the user is logged in and has created a session.
if(!isset($_SESSION['name']))
loginForm();
else
id="wrapper">
id="menu">
class="welcome">Welcome, echo $_SESSION['name']; ?>
class="logout"> id="exit" href="#">Exit Chat
id="chatbox">
if(file_exists("log.html") && filesize("log.html") > 0)
$contents = file_get_contents("log.html");
echo $contents;
name="message" action="">
name="usermsg" type="text" id="usermsg" />
name="submitmsg" type="submit" id="submitmsg" value="Send" />
type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js">
type="text/javascript">
// jQuery Document
$(document).ready(function()
We are not yet finished creating the login system for this chat application. We still need to allow the user to log out and end the chat session. If you remember, our original HTML markup included a simple menu. Let's go back and add some PHP code that will give the menu more functionality.
First of all, let's add the user's name to the welcome message. We do this by outputting the session of the user's name.
class="welcome">Welcome, echo $_SESSION['name']; ?>
In order to allow the user to log out and end the session, we will jump ahead of ourselves and briefly use jQuery.
script type="text/javascript">
// jQuery Document
$(document).ready(function()
//If user wants to end session
$("#exit").click(function()
var exit = confirm("Are you sure you want to end the session?");
if(exit==true)window.location = 'index.php?logout=true';>
/script>
The jQuery code above simply shows a confirmation alert if a user clicks the #exit link. If the user confirms the exit, therefore deciding to end the session, then we send them to index.php?logout=true . This simply creates a variable called logout with the value of true . We need to catch this variable with PHP:
if(isset($_GET['logout']))
//Simple exit message
$logout_message = "User ". $_SESSION['name'] ." has left the chat session. ";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: index.php"); //Redirect the user
We now see if a get variable of 'logout' exists using the isset() function. If the variable has been passed via a URL, such as the link mentioned above, we proceed to end the session of the user's name.
Before destroying the user's name session with the session_destroy() function, we want to write a simple exit message to the chat log. It will say that the user has left the chat session. We do this by using the file_put_contents() function to manipulate our log.html file, which, as we will see later on, will be created as our chat log. The file_put_contents() function is a convenient way to write data to a text file instead of using fopen() , fwrite() , and fclose() each time. Just make sure that you pass appropriate flags like FILE_APPEND to append the data at the end of the file. Otherwise, a new $logout_message will overwrite the previous content of the file. Please note that we have added a class of msgln to the div. We have already defined the CSS styling for this div.
After doing this, we destroy the session and redirect the user to the same page where the login form will appear.
After a user submits our form, we want to grab their input and write it to our chat log. In order to do this, we must use jQuery and PHP to work synchronously on the client and server sides.
Almost everything we are going to do with jQuery to handle our data will revolve around the jQuery post request.
//If user submits the form