Simple Public Chat Room Using PHP/MySQLi with Source Code

Language

This is a Simple Chat System wherein you can send messages to the public. This simple system requires users to register and login in order to join the public chat. The system is programmed using PHP, MySQL Database, HTML, CSS, JavaScript (jQuery), and MySQLi procedural method. The user can also update his/her account details.

Features:

  • Login
  • Registration
  • Send Message to Public
  • Update Account Details

The below image is the login form of this system.

Login Form

And for the registration form. This can be navigate to show by clicking the button with a pencil icon.

registration

The below scripts are the codes that I have used to build the login and registration form

index.php
  1. <?php
  2. if (isset($_SESSION['message'])){
  3. echo $_SESSION['message'];
  4. unset ($_SESSION['message']);
  5. }
  6. ?>
  7. <!DOCTYPE html>
  8. <html lang="en" >
  9.  
  10. <head>
  11. <meta charset="UTF-8">
  12. <title>chatME</title>
  13.  
  14. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
  15.  
  16. <link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
  17. <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'>
  18.  
  19. <link rel="stylesheet" href="css/style.css">
  20.  
  21.  
  22. </head>
  23.  
  24. <body>
  25.  
  26.  
  27. <!-- Form Mixin-->
  28. <!-- Input Mixin-->
  29. <!-- Button Mixin-->
  30. <!-- Pen Title-->
  31. <div class="pen-title">
  32. <h1><!-- ChatME--></h1>
  33. </div>
  34. <!-- Form Module-->
  35. <div class="module form-module">
  36. <div class="toggle"><i class="fa fa-times fa-pencil"></i>
  37. <div class="tooltip">Click Me</div>
  38. </div>
  39. <div class="form">
  40. <h2>Login to your account</h2>
  41. <form name="form_login" method="post" action="login.php">
  42. <input type="text" placeholder="Username" name="username" />
  43. <input type="password" placeholder="Password" name="password" />
  44. <button>Login</button>
  45. </form>
  46. </div>
  47. <div class="form">
  48. <h2>Create an account</h2>
  49. <form name="form_register" method="post" action="register.php">
  50. <input type="text" placeholder="Your Name" name="your_name" required="required" />
  51. <input type="text" placeholder="Username" name="username" required="required" />
  52. <input type="password" placeholder="Password" name="password" required="required" />
  53. <input type="email" placeholder="Email Address" name="email" />
  54. <input type="phone" placeholder="Phone Number" name="phone" />
  55. <button>Register</button>
  56. </form>
  57. </div>
  58. <div class="cta"><!-- <a href="#">Forgot your password?</a> --><center>Developed by: PJCaraig &copy 2018</center></div>
  59. </div>
  60. <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
  61. <script src='https://codepen.io/andytran/pen/vLmRVp.js'></script>
  62.  
  63.  
  64.  
  65. <script src="js/index.js"></script>
  66.  
  67.  
  68.  
  69.  
  70. </body>
  71.  
  72. </html>
register.php
  1. <?php
  2. include("conn.php");
  3.  
  4. $username=mysqli_real_escape_string($conn,$_POST['username']);
  5. $password=mysqli_real_escape_string($conn,$_POST['password']);
  6. $email=mysqli_real_escape_string($conn,$_POST['email']);
  7. $phone=mysqli_real_escape_string($conn,$_POST['phone']);
  8. $your_name=mysqli_real_escape_string($conn,$_POST['your_name']);
  9.  
  10. if($username == "" || $password == ""){
  11. echo "<script>window.alert('Username and Password are required fields!')</script>";
  12. }
  13. else{
  14. $insert_query=mysqli_query($conn,"INSERT INTO user(username,password,email,phone,your_name)VALUES('$username','$password','$email','$phone','$your_name')")or die(mysqli_error($conn));
  15. echo "<script>window.alert('Account successfully created! You can now login with your credentials.')</script>";
  16. echo "<script>window.location.href='index.php?registered'</script>";
  17. }
  18.  
  19. ?>
login.php
  1. <?php
  2. include('conn.php');
  3.  
  4. $username=$_POST['username'];
  5. $password=$_POST['password'];
  6.  
  7. $query=mysqli_query($conn,"select * from `user` where username='$username' and password='$password'");
  8.  
  9. if (mysqli_num_rows($query)<1){
  10. /* $_SESSION['message']="Login Error. Please Try Again"; */
  11. echo "<script>window.alert('Login Error. Please try again.')</script>";
  12. echo "<script>window.location.href='index.php?attempt=failed'</script>";
  13. //header('location:index.php');
  14. }
  15. else{
  16. $row=mysqli_fetch_array($query);
  17. $_SESSION['userid']=$row['userid'];
  18. header('location:home.php');
  19. }
  20.  
  21. ?>

For the "conn.php", the included file for both register and login process is the file where I open the connection with the database.

  1. <?php
  2. $date=date('F j, Y g:i:a');
  3.  
  4. //mysqli procedural
  5. $conn=mysqli_connect("localhost","root","","chatme");
  6. if(!$conn){
  7. die("Connection failed: " . mysqli_connect_error());
  8. }
  9. ?>

I used below script for the structure of my user table in the database.

  1. CREATE TABLE IF NOT EXISTS `user` (
  2. `userid` int(11) NOT NULL AUTO_INCREMENT,
  3. `username` varchar(30) DEFAULT NULL,
  4. `password` varchar(30) DEFAULT NULL,
  5. `your_name` varchar(60) DEFAULT NULL,
  6. `email` varchar(255) DEFAULT NULL,
  7. `phone` varchar(255) DEFAULT NULL,
  8. PRIMARY KEY (`userid`)

After the user login to the system, they will be redirected to the home page which is the chat room by default. For sending the messages of the user I used ajax send the message and user info to the back-end code to save it into the database without leaving the page.

Chat Room
home.php
  1. <?php
  2. include('conn.php');
  3. if (!isset($_SESSION['userid']) ||(trim ($_SESSION['userid']) == '')) {
  4. header('location:index.php');
  5. exit();
  6. }
  7.  
  8. $uquery=mysqli_query($conn,"SELECT * FROM `user` WHERE userid='".$_SESSION['userid']."'");
  9. $urow=mysqli_fetch_assoc($uquery);
  10. ?>
  11. <!DOCTYPE html>
  12. <html>
  13. <head>
  14. <title>chatME</title>
  15. <link rel="stylesheet" href="css/home.css">
  16. <script src="jquery-3.1.1.js"></script>
  17. <script src="js/home.js"></script>
  18. <script type="text/javascript">
  19.  
  20. $(document).keypress(function(e){ //using keyboard enter key
  21. displayResult();
  22. /* Send Message */
  23.  
  24. if(e.which === 13){
  25. if($('#msg').val() == ""){
  26. alert('Please write message first');
  27. }else{
  28. $msg = $('#msg').val();
  29. $id = $('#id').val();
  30. $.ajax({
  31. type: "POST",
  32. url: "send_message.php",
  33. data: {
  34. msg: $msg,
  35. id: $id,
  36. },
  37. success: function(){
  38. displayResult();
  39. $('#msg').val(''); //clears the textarea after submit
  40. }
  41. });
  42. }
  43.  
  44. /* $("form").submit();
  45. alert('You press enter key!'); */
  46. }
  47. }
  48. );
  49.  
  50.  
  51. $(document).ready(function(){ //using send button
  52. displayResult();
  53. /* Send Message */
  54.  
  55. $('#send_msg').on('click', function(){
  56. if($('#msg').val() == ""){
  57. alert('Please write message first');
  58. }else{
  59. $msg = $('#msg').val();
  60. $id = $('#id').val();
  61. $.ajax({
  62. type: "POST",
  63. url: "send_message.php",
  64. data: {
  65. msg: $msg,
  66. id: $id,
  67. },
  68. success: function(){
  69. displayResult();
  70. $('#msg').val(''); //clears the textarea after submit
  71. }
  72. });
  73. }
  74. });
  75. /* END */
  76. });
  77.  
  78. function displayResult(){
  79. $id = $('#id').val();
  80. $.ajax({
  81. url: 'send_message.php',
  82. type: 'POST',
  83. async: false,
  84. data:{
  85. id: $id,
  86. res: 1,
  87. },
  88. success: function(response){
  89. $('#result').html(response);
  90. }
  91. });
  92. }
  93. </script>
  94.  
  95. </head>
  96.  
  97. <body>
  98. <table id="chat_room" align="center">
  99. <tr>
  100. <th><h4>Hi, <a href="profile.php?userid=<?php echo $_SESSION['userid']; ?>"><?php echo $urow['your_name']; ?></a> - <a href="logout.php" onclick="return confirm_logout();">Logout</a></h4></th>
  101. </tr>
  102. <?php
  103. $query=mysqli_query($conn,"select * from `chat_room`");
  104. $row=mysqli_fetch_array($query);
  105. ?>
  106. <div>
  107. <tr>
  108. <td><?php echo $row['chat_room_name']; ?></td><br><br>
  109. </tr>
  110. </div>
  111. <tr>
  112. <td>
  113. <div id="result" style="overflow-y:scroll; height:300px; width: 605px;"></div>
  114. <form class="form">
  115. <!--<input type="text" id="msg">--><br/>
  116. <textarea id="msg" rows="4" cols="85"></textarea><br/>
  117. <input type="hidden" value="<?php echo $row['chat_room_id']; ?>" id="id">
  118. <button type="button" id="send_msg" class="button button2">Send</button>
  119. </form>
  120. </td>
  121. </tr>
  122.  
  123. </table>
  124.  
  125. </body>
  126. </html>

I used the code below for the structure of my "chat" table in the database.

  1. CREATE TABLE IF NOT EXISTS `chat` (
  2. `chatid` int(11) NOT NULL AUTO_INCREMENT,
  3. `chat_room_id` int(11) DEFAULT NULL,
  4. `chat_msg` text,
  5. `userid` int(11) DEFAULT NULL,
  6. `chat_date` varchar(255) DEFAULT NULL,
  7. PRIMARY KEY (`chatid`)

For building the User Account Details View or the User profile using the below script.

profile.php
  1. <?php
  2. include('conn.php');
  3. if (!isset($_SESSION['userid']) ||(trim ($_SESSION['userid']) == '')) {
  4. header('location:index.php');
  5. exit();
  6. }
  7.  
  8. $query=mysqli_query($conn,"SELECT * FROM user WHERE userid='$_SESSION[userid]' ")or die(mysqli_error($conn));
  9. $row=mysqli_fetch_array($query);
  10. $username=$row['username'];
  11. $password=$row['password'];
  12. $email=$row['email'];
  13. $phone=$row['phone'];
  14. $your_name=$row['your_name'];
  15.  
  16. ?>
  17. <!DOCTYPE html>
  18. <html>
  19. <head>
  20. <title>chatME - Profile</title>
  21. <link rel="stylesheet" href="css/home.css">
  22. <script src="js/home.js"></script>
  23. </head>
  24. <body>
  25. <table id="chat_room" align="center">
  26. <tr>
  27. <td><a href="home.php">Home</a></td>
  28. </tr>
  29. <tr>
  30. <th><h4>Profile Settings - <a href="logout.php" onclick="return confirm_logout();">Logout</a></h4></th>
  31. </tr>
  32.  
  33. <tr>
  34. <td>
  35. <h4>Hi there, <font color="blue"><?php echo $your_name; ?></font></h4>
  36. </td>
  37. </tr>
  38. <tr>
  39. <td><b>Details</b></td>
  40. </tr>
  41. <tr>
  42. <td>Username:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" value="<?php echo $username;?>" disabled /></td>
  43. </tr>
  44.  
  45. <tr>
  46. <td>Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" value="<?php echo $password; ?>" disabled /></td>
  47. </tr>
  48.  
  49. <tr>
  50. <td>Email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="email" value="<?php echo $email; ?>" disabled /></td>
  51. </tr>
  52.  
  53. <tr>
  54. <td>Phone:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" value="<?php echo $phone; ?>" disabled/></td>
  55. </tr>
  56.  
  57. <tr>
  58. <td></td>
  59. </tr>
  60.  
  61. <tr>
  62. <td><a href="edit_details.php?userid=<?php echo $_SESSION['userid']; ?>">Edit Details</a></td>
  63. </tr>
  64. </table>
  65. </body>
  66. </html>
Result
Profile

And below is for updating the user's account details.

edit_details.php
  1. <?php
  2. include('conn.php');
  3. if (!isset($_SESSION['userid']) ||(trim ($_SESSION['userid']) == '')) {
  4. header('location:index.php');
  5. exit();
  6. }
  7.  
  8. $query=mysqli_query($conn,"SELECT * FROM user WHERE userid='$_SESSION[userid]' ")or die(mysqli_error($conn));
  9. $row=mysqli_fetch_array($query);
  10. $username=$row['username'];
  11. $password=$row['password'];
  12. $email=$row['email'];
  13. $phone=$row['phone'];
  14. $your_name=$row['your_name'];
  15.  
  16. if(isset($_POST['submit'])){
  17.  
  18. $userid=$_GET['userid'];
  19. $your_name_edit=mysqli_real_escape_string($conn,$_POST['your_name']);
  20. $username_edit=mysqli_real_escape_string($conn,$_POST['username']);
  21. $password_edit=mysqli_real_escape_string($conn,$_POST['password']);
  22. $email_edit=mysqli_real_escape_string($conn,$_POST['email']);
  23. $phone_edit=mysqli_real_escape_string($conn,$_POST['phone']);
  24.  
  25. $update_query=mysqli_query($conn,"UPDATE user SET your_name='$your_name_edit',username='$username_edit',password='$password_edit',email='$email_edit',phone='$phone_edit' WHERE userid='$userid' ")or die(mysqli_error($conn));
  26. echo "<script>window.alert('Record successfully updated!')</script>";
  27. echo "<script>window.location.href='edit_details.php?userid=$_SESSION[userid]'</script>";
  28. }
  29.  
  30. ?>
  31. <!DOCTYPE html>
  32. <html>
  33. <head>
  34. <title>chatME - Edit Details</title>
  35. <link rel="stylesheet" href="css/home.css">
  36. <script src="js/home.js"></script>
  37. </head>
  38. <body>
  39. <table id="chat_room" align="center">
  40. <tr>
  41. <td><a href="home.php">Home</a></td>
  42. </tr>
  43. <tr>
  44. <th><h4>Edit Details - <a href="logout.php" onclick="return confirm_logout();">Logout</a></h4></th>
  45. </tr>
  46.  
  47. <tr>
  48. <td>
  49. <h4>Hi there, <font color="blue"><?php echo $your_name; ?></font></h4>
  50. </td>
  51. </tr>
  52. <tr>
  53. <td><b>Details</b></td>
  54. </tr>
  55. <form name="form_edit" method="post" action="">
  56. <tr>
  57. <td>Your Name:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="your_name" value="<?php echo $your_name;?>" /></td>
  58. </tr>
  59.  
  60. <tr>
  61. <td>Username:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="username" value="<?php echo $username;?>" /></td>
  62. </tr>
  63.  
  64. <tr>
  65. <td>Password:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="password" name="password" value="<?php echo $password; ?>" /></td>
  66. </tr>
  67.  
  68. <tr>
  69. <td>Email:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="email" name="email" value="<?php echo $email; ?>" /></td>
  70. </tr>
  71.  
  72. <tr>
  73. <td>Phone:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" name="phone" value="<?php echo $phone; ?>" /></td>
  74. </tr>
  75.  
  76. <tr>
  77. <!--<td><button name="submit" type="button" id="send_msg" class="button button2">Update</button></td>-->
  78. <td><input type="submit" name="submit" class="button button2"></td>
  79. </tr>
  80. </form>
  81.  
  82. <tr>
  83. <td></td>
  84. </tr>
  85.  
  86. <tr>
  87. <td><a href="profile.php?userid=<?php echo $_SESSION['userid']; ?>">back to Profile</a></td>
  88. </tr>
  89. </table>
  90. </body>
  91. </html>
Result
Edit account

The system is free to download and for modification for educational purposes. To download and run this simple chat system, please continue reading and follow the instructions below.

How to Run

Requirements
  • Download and Install a local web server like XAMPP/WAMP.
  • Text Editor for your modification such as notepad++ or sublime.
Setting Up
  • Download and Extract the source code zip file. (download button is located below)
  • Start the "Apache" and "MySQL" of your local web server. For XAMPP/WAMP, open the XAMPP/WAMP's Control Panel to do this.
  • Open the PHPMyAdmin in a web browser (http://localhost/phpmyadmin) and create a new database naming "chatme".
  • Locate the SQL file in the extracted folder of the source code located inside the db folder. The SQL file is known as "chatme.sql".
  • If you are using XAMPP, copy the extracted source code folder and paste it into the xampp's "htdocs" folder. And for the WAMP, paste the folder inside the "www" folder.
  • Open a web browser and browse the system. (http://localhost/chat)

Sample User Access

Username: pao
Password: pao

Register a new user if you want to try the system in a multiple user.

I hope the Simple Chat System will help you with what you are looking for.

Enjoy :)

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Comments

Submitted byAbhishek Thakker (not verified)on Sun, 05/23/2021 - 03:11

Hey! i'm getting this error Connection failed: Unknown database 'chatme'

Thanks for your assistance. You have given me a helping hand.
Submitted byTom1239876 (not verified)on Fri, 12/24/2021 - 00:35

hello, like the simplicity of this. Would you consider building upon this code for customization/ many thanks

Add new comment