Chat Web Application using PHP with MySQL & JavaScript

276
Realtime Chat Application using PHP with MySQL & JavaScript Ajax

Hey friends, today in this blog you’ll learn how to create a Chat Web Application using PHP with MySQL & JavaScript. Earlier I have shared a blog on how to create a Simple Chatbot using PHP with MySQL & jQuery Ajax. Our maximum viewers have requested me to create a Chat App so I decided to create one.

In this chat application, when you open it first on your browser, there is shown a signup form where you have to signup with your details like name, email, password, and image. Email and image field is fully validated which means you’ve to enter a valid email and an image file only. Once you signed up successfully, you’ll be redirected to the user’s page where you can see your full name, image, status, and logout button to the top, and users, like you, appear on the bottom if someone has signed up.

On this page, you can see their image, name, status, and the last message if they sent to you. You have to click on the particular user or you can also search any existing user with their name then you’ll be redirected to the chat page and there you can see the image, name, status of that user who is going to chat.

Once you send a message to another user then immediately that message appears in your chat box and another user chatbox too which you’ve sent the message. On the message receiver chatbox, this user received the message with the sender image. Remember chatbox will be automatically scrolled to the bottom once the chatbox starts scrolling. You can log out from the chat application at any time and once you log out, immediately all other users will know that you’ve been log out or offline.

Once you log out, you can again login and with your email and password that you used when signing up for the form. If you entered the correct credentials then you’ll be redirected to the user’s page and all other users will immediately know that you’ve logged on and now active.

Video Tutorial of Chat Application in PHP and MySQL

 
In the video, you’ve seen the demo of the chat application in PHP and MySQL and the codes or concepts behind creating a chat app. As I already told you I used PHP with MySQL and pure JavaScript Ajax to create this chat app so you don’t need to reload the page to see changes in the chat app. I know if you’re a beginner and you don’t have enough knowledge about PHP then definitely you’ve to difficult to understand the codes.

But I tried to explain each JavaScript and PHP line with comments, subtitles, etc. But don’t worry I have provided the source code files of this chat app so you can easily download from the given download button and try analyzing, practicing the codes to understand better. And I know, there are many other features that are missed on this chat app but for now, I think it is more than enough for practice.

You might like this:

Chat Web Application using PHP [Source Codes]

How to download source code files and what to do after downloading them?

Steps: – To download files, just click on the given download button then a 60 seconds timer will start, just wait for the timer. Once the timer completed then a zip file will be downloaded automatically. Once it downloaded, just extract the zip file then you’ll see the folder name with ChatApp. Copy this folder and paste it inside htdocs folder of your XAMPP then start your apache and MySQL from the XAMMP control panel.

After completing these steps, go to your browser and open this URL localhost/phpmyadmin then create a new database name with a chatapp. After creating the database, there you can see an import option, just click on that and import the SQL file which is in the ChatApp folder. Everything is done now, just open this URL localhost/chatapp that’s it. Your chat application is ready to chat.

If you want to upload this chat application to an online server for free and don’t know how? Then please watch this video How to upload Chat Application to an Online Server for Free?

 

Previous articleHow To Make Search Box Using HTML & CSS
Next articleZ-Index Transition on Image using CSS

276 COMMENTS

  1. Hello CodingNepal, I’m writing to you again because I need help with the following. I’d like to know if you can help me put all your code in a button like a messenger and that when you click on it, it opens on the same page of my website and so we can start chatting.

    Best regards,
    Jorge Luis

  2. Hi Coding Nagpal.

    First of all, thank you for everything you share.

    My question would be this: how would I enclose the entire index.php in a button so that on my page only a chat icon is visible and when you click on it, the entire app opens.

    Thank you very much.

  3. I have used to user and sending messages but each time when i logged in using a user id all the chat messages shows under his name.

  4. I am not getting any errors or warnings but when I register a new user, and after filling in all input fields I click on the continue to chat button nothing happens just an error block [error-txt] appears on the signup form without any text or error in it, and also the data is not inserted in the database.

  5. Hey actually i was using your project for the development process as i am using macbook pro 14 inch M1 Pro chip and it’s working properly but as soon as i upload the image as you mentioned it doesn’t login can you explain whats is wrong or i am doing some wrong process

  6. Hi this code is a solid foundation! May I ask you if you could consider expanding this code and add the following features:

    General area or room for all users to chat.
    User profile with basic info
    User edit profile
    User notifications

    Thanks

  7. I ask this question again. why do we need a unzipuploader.php page in this package? if you don’t publish this question I will get my answer

  8. I check the files and find a PHP file called unzipped which is used for uploading zip files unzip It is vulnerable to the website because everyone can upload the zip file and extract it from the same address and do the shell scripting or more. just I want to know why we have it there, thank you.

  9. Hey, Coding Nepal this chat app project is so awesome. I am doing this project for Placement. I submitted this project to University. Please can you send me a Project Report or Fully Documentation?

    • I don’t have basic knowledge but I did as below

      1. Make another form to upload file.
      2. Save file to folder & path to mysql, Message input value = path of file, Button Click to insert chat
      3. embed file in get-chat

      For Video Call option:
      Make div to show as message with 2 links – Accept & Decline.
      Message input value = div.outerHTML
      If click Accept link=> open new page for video call in parent window
      If click Decline link => message value = He/She decline video call & button click

  10. I enjoyed watching your tuturial and its really cool, interface is nice hopes there a feature an option to determine when theres a new message arrive.

  11. Good afternoon,
    It would be great to add editing/deleting messages.
    Notifications for new messages.
    Profile editing
    Domain Authorization

    Thanks, great product

  12. Hello, I have no problem so far and I have completed the project but two issues, when I try adding the You for outgoing messages, it gives me an array offset error. Then, how can I arrange it for new users messages to show first like incoming messages should be on top in the user-list section

  13. at 01:42:18 when you refresh your browser codingNepal’s account turned into Andrew’s account. so that no two users can be logged in at the same time. this issue is still in the downloaded code as well. could you please tell me how to correct that issue?

  14. Hi,CodingNepal van I get your contact details.
    I did something similar to this.
    But it’s not a chat app.
    It’s a normal app.
    It allows you to chat and do various things
    How does app like this work.
    Do I create a chat table and create another table for posts or do I just try what I can ?

  15. Thank you very well !!
    you are the best in real time between all of developers open source code .
    keep it up to success in your coding life !!

  16. Hello! Thank you very much for your project. How to add sending images and emoticons, and time with date set each message could you help me ?

  17. Hey coding Nepal can you add some more functionality like message delete, sending attachments and show user typing and also notification sound if possible.. it would be very helpful and great.

    Thanks in advance.

  18. great work man. i tried the app with friends on my local wifi at home and they loved it. however when we have so many people logged in there is no vertical scroll bar to be able to view everyone on the list.

  19. Hello! Thank you very much for your project. I have already managed to implement sending emojis and images, but have not yet been able to add a notification sound with each new message. Could you give me any hints on how to achieve it?

  20. Hi,
    great job. Im impressed.
    Just wanted to let you know the folder: ChatApp – CodingNepal\php\images is empty.
    Im really sure. There is no image in it.
    Thank you

    • Yes, there are no images but when the user signed up to this chat app then the user profile will be saved in this folder.

  21. Thanks for this great job code nepal
    But i don’t know if this is possible please
    I want it to be like before a user can chat with another user they must have and id of another user, this id will be given why signing up, so on typing a user id, after submit button, it will bring the user profile, just like Facebook, so if don’t i don’t have a user id i can’t chat with anyone

    Sir/ma is this possible??

  22. session_start();
    include_once “config.php”;
    $sql = “SELECT * FROM users”;
    $output = “”;

    if(mysqli_num_rows($con->query($sql)) == 1 )
    {
    $output.=”No users are available to chat”;
    }
    elseif(mysqli_num_rows($con->query($sql)) >0 )
    {
    while($row = mysqli_fetch_assoc($con->query($sql)))
    {
    $output.=’

    ‘.$row[‘fname’].” “.$row[‘lname’].’
    This is test message


    ‘;
    }
    }

    echo $output;

    =============
    i’m getting error here :

    Fatal error: Maximum execution time of 120 seconds exceeded in C:\xampp\htdocs\Chat_App\php\users.php on line 14

    help me please

  23. Hello my fan codingnepal i am student studying computer science, honestly this your chat app assist me in my final year project thanks so much and i will be with you for life

  24. Hi,

    Liked your chat App, Can you please add a forgot password retrieve option too for the same,
    so it is easy to reset the password incase forgotten to retrieve

    Binoy.

  25. This can have so many integrations to it! I love it, cant wait for the update! (if there is gonna be an update, i hope it will!)

  26. Hi CodeingNepal
    You are one of the finest brains i have ever come across. Thank you very much for this. Waah!
    May God bless you. Exactly what i needed.

  27. hello when i try to send messages between two logged in user can’t chat directly. please help it requires me to logout through an account to see available chat. please help i want to chat directly.

  28. Hello sir, I’m a big fan off yours, I’ve a question. Can I remove image while creating an account or add image size and extension validation

  29. Hi! This is really cool. It was very useful to me. Could you add an option to show a notification when a message is received or maybe a sound that works the same way? That could be great! Thank you

  30. Hi, this is really cool and working very well, thank you. I have added the ability to mark messages as read when the recipient sees them.
    I just have a quick question about the scrolling in the chat window. Works fine on desktop browser where you can scroll back up through the chat log. On a mobile device (where it is touch events and not mouse clicks) you cannot scroll up without it immediately scrolling to the latest message. I think this is due to chatBox.onmouseenter = ()=>{ chatBox.classList.add(“active”); etc in the chat.js file. Tried changing to touch enter touch leave etc but not working. Anyone (or maybe the author) got any advice on this please?
    Thanks in advance,
    Martyn.

    • Actually, to stop the chatbox from scrolling to the bottom I used mouseenter event. So on the mobile devices, first you need to click on the chatbox to fire this mouseenter event and hold it. Then you can scroll the chats to the top or bottom.

  31. Hi Sir,
    the code in Description is not like same as you shown in video, i mean extra features like: status button where online/offline, send button in bottom corner side.
    Before some day i downloaded the code, it worked nicely, but again i need code for this chat app sir, please sir, i need it, As Soon as possible please update it soon sir.

  32. It is really a good tutorial it perfectly works in my case. I really appreciate your work. I request one more help from your side to include an unread message count along with user name. The necessary css code is needed. Thanks in advance.

  33. Hi Sir, It is really a great tutorial and self-descriptive. It is working perfectly in my program.
    One more help I am seeking. Can we add an unread message count superscript after the name of each user? Thanks in advance.

  34. how can i only pull out/show users who i have chatted with before or have an existing chat history with , i dont want to show every user from the database

  35. hello CodingNepal,
    when i want to register a new user i get an red box with no error in it. and i cannot go any further.
    Thnx

  36. This is great tutorial and an application. I’m little bit confused regarding application optimization, due to interval ajax call app memory increase.
    If possible please clear it.

  37. Good work
    Can you add user status and send jpg/pdf on this chat??
    I try to add sound on msg send/recived but wen i send msg the sound work not working on msg recived can you help pls i mod chat.js :
    xhr.onload = ()=>{
    if(xhr.readyState !== undefined && xhr.readyState === 4){
    if(xhr.status === 200){
    inputField.value = “”;
    scrollToBottom();
    var audio = new Audio(“php/sounds/beep.mp3”);
    audio.play();
    }
    }
    }

    • Hello, don’t to this because notification sound will play after each 500ms even if you’re not receiving message.

  38. Hey, Really great tutorial and inspirational.
    Please let me know using why web-socket chat application is not better than ajax ?

    • I think use of websocket or socket.io is better than ajax for realtime chat but it really depends on project requirements.

  39. Perfect!!!
    ILOVE this but i keep getting error when tryin to group the users into chatroom.
    and when i tried to update profile picture whenn user already signed in

    • Hello bro, I checked it and didn’t seem any problems. I think you did some mistakes on codes or you may be confused about it. Can you send me a video clip so I can confirm this problem..?

    • Hi Bro, I tested it properly and I think I was confused. Everything is working fine. Thanks again 🙂

    • Yes, it is possible and the steps are the same as shown in this video but this chat app is not secure and anyone with basic knowledge of PHP can attack this chat app. When I was making this chat app, my purpose is to teach how to make a simple chat app only not to how to secure it. If you can modify codes and make them secure then you can upload it otherwise do it at your own risk.

  40. Dear Coding Nepal, I Got This Error When Trying To Signup With An Account. I Did All The Steps For Uploading The Site And I Got This Error!

    Warning: move_uploaded_file(images/16230201755_0.png): failed to open stream: No such file or directory in /storage/ssd2/539/16989539/public_html/php/signup.php on line 28 Warning: move_uploaded_file(): Unable to move ‘/storage/ssd2/539/16989539/tmp/php8cen6w’ to ‘images/16230201755_0.png’ in /storage/ssd2/539/16989539/public_html/php/signup.php on line 28

    Please Help Me Fix It!

    • I think you did some changes to codes or you’ve changed folders name. If you don’t know about it please don’t do anything except what is mentioned in the blog.

  41. The description read that you will have to wait 30 sec and the download will start. In reality I
    had to wait 50 sec and the download never happened.

    • Yes, I increased the download time but the zip file will be downloaded once the timer is completed.

  42. Is there a way we can add settings to change your profile picture and get sound alerts when a new message comes in?

  43. Hi bro thanks for the project I tried the project and ran all the files as you described in video the chat system is running but only one message able to send and i tried to send another message it is neither displaying in the chat-area nor storing database please help me to sort the issue.

  44. Thank you for the quick answer, don’t get me wrong with the comment. I can understand your point of view, Github just allow you to be able to share the solution of any problem or maybe update the source.

  45. Hi both sources related to the chat are died. I have no idea why google drive don’t allow to download it. Why don’t you try to make a Github account to put the projects there and share it. I can’t deny that sometimes is hard to get happy to everybody but this kind of projects can be so useful for the leaning process of many visitors of your website. Keep working hard on it.

    • If I will put my source files on GitHub then why my viewers will come to my site? Instead of coming to my site, they will go to my GitHub account to get the source codes. I can share with you another link of files if you have problems downloading from the drive.

  46. I just completed the chat app by patiently typing in the code from the video tutorial. I could not download the source code because the site was down for maintenance when I went there. Anyway, I finished the video, and, after dealing with the errors due to my own mistakes in typing, I finally was able to make it work.
    One observation that I would like to share with you all, if you are not aware of it yet is that..
    after I completed the logout section, the following happens..
    Situationer:
    1) one user logs in (no errors). userlist is populated as it should be..
    2) another user, using a different browser tab, logs in.(no errors).. but the second user who logged in is removed from the userlist of the first user’s box who logged in earlier. The first user, though, appears on the user list of the second user who just logged in. (The list in the first user’s box changes to whatever list the second user has.)
    3) if either one of the two users logs out…. an error appears on the other user’s chatbox. No error appears on the chat box of the user that logged out.

    I hope I explained it clearly enough ..

    Anyways, my assumption is that the errors occur probably because the session variables are unset and destroyed when a user logs out. The errors are about ‘undefined’ variables.

    Nonetheless, a huge THANK YOU to CodingNepal for its generosity in posting tutorial videos, especially this real-time chatapp.I am eternally grateful!

    Update:
    I commented out the session_unset and session_destroy statements just to see what happens, and the errors disappeared. Of course, those must not be removed.
    The userl ist though is still the same for the two users.

    With this being the case, only one user can log in

    • Hi, first of all, big thanks to you for doing this project without depending on source files. When I was making this chat app I didn’t find or notice these problems or errors. So please download the source files from the given download button and check again because you may have did mistakes in coding.

  47. bro!…below warning is shown while i am trying to open in my webbrowser after entering url localhost/chatapp…please help

    Object not found!
    The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

    If you think this is a server error, please contact the webmaster.

    Error 404
    localhost
    Apache/2.4.41 (Win64) OpenSSL/1.1.1c PHP/7.3.9

  48. I am getting this error

    Warning: move_uploaded_file(images/1618997904lesson.jpg): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/ffyypp/ChatApp – CodingNepal/php/signup.php on line 28

    Warning: move_uploaded_file(): Unable to move '/Applications/XAMPP/xamppfiles/temp/phpmTMVIx' to 'images/1618997904lesson.jpg' in /Applications/XAMPP/xamppfiles/htdocs/ffyypp/ChatApp – CodingNepal/php/signup.php on line 28

    • Hello User We reviewed your query and found out that infinityfree.net servers don’t let create any chat application because according to them this can cause errors to the free servers
      so to try it you can paid hosting or localhost and configure it to a public ip and do port forwarding to use your device as a server

  49. i want to show user list according to the last received or outgoing message (like fb) and also i want seen or unseen msg tab (read or unread also okay )
    i am waiting forr the update, can you plz tell when exactly we get next update ? this is cool

  50. Hello Coding Nepal, thanks for the code, it is really useful.

    I have a problem to register, it does not show what the error is, but I believe the problem is in the image upload.

    Because I put the image in the images folder, and entered the data manually in the database and it worked.

    Do you know what the possible error is?

  51. hi, thanks for script.I install the script, everything ok. but not registering.when open the console this alert seen,[DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://goo.gl/9p2vKq) input type="password" name="password" placeholder="Enter new password" required=""

  52. You have a error when render user image account who send a message. receiver user show samself image but not sender. You need a change SQL query on file get-chat.php from … users.unique_id = messages.outgoing_msg_id … to … users.unique_id = messages.incoming_msg_id …

  53. I have successfully installed your chatapp.
    Except when I want to create a user or log in. It gives me no error, but no page loads. However, to verify the connection to the database, I created a user from the database, and when I want to create an account, it tells me "Email already exists". I therefore conclude that the connection to the database is successful.However, I don't know where the error came from.

  54. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /storage/ssd4/625/16245625/public_html/php/signup.php on line 11
    Something went wrong. Please try again!

  55. Hello there;
    I downloaded the source codes. I edited the config.php file with my own information. But do you know the reason I got this error? Note: I get an error like this when a second user is online. The online user does not appear. You can reach for a reply at [email protected]. Thx

    Fatal error: Uncaught TypeError: mysqli_fetch_assoc(): Argument #1 ($result) must be of type mysqli_result, bool given in C:xampphtdocschatphpdata.php:7 Stack trace: #0 C:xampphtdocschatphpdata.php(7): mysqli_fetch_assoc(false) #1 C:xampphtdocschatphpusers.php(11): include_once('C:\xampp\htdocs…') #2 {main} thrown in C:xampphtdocschatphpdata.php on line 7

  56. if you find this error again just replace line 14 in data.php file with ($outgoing_id == isset($row2['outgoing_msg_id'])) ? $you = "You: " : $you = "";
    BTW CodingNepal your work is amazing.

  57. This error you faced because you've written dbname or dbpass or dbuser name incorrectly in config.php. But if you were written all things correctly then delete the current database and create another one because this is a free hosting and sometimes you get an error even if you did everything perfectly.

  58. Brother, I have a problem! All details are perfect, but the connection was not a success.

    The Error: "Warning:mysqli_connect(): (HY000/1045): ProxySQL Error: Access denied for user 'id16130301_tawfik'@'2a02:4780:bad:f00d::3' (using password: YES)"

    Please help me. How can I solve this?

  59. Warning: Trying to access array offset on value of type null in C:xampphtdocsChatAppphpdata.php on line 14

    Warning: Trying to access array offset on value of type null in C:xampphtdocsChatAppphpdata.php on line 14

    Warning: Trying to access array offset on value of type null in C:xampphtdocsChatAppphpdata.php on line 14

    Warning: Trying to access array offset on value of type null in C:xampphtdocsChatAppphpdata.php on line 14

    Warning: Trying to access array offset on value of type null in C:xampphtdocsChatAppphpdata.php on line 14

    Its showing this i wanted the reference code but its not working idk why its showing this i ve downloaded it today 2 / 22 /2021 ( can you help me please )

  60. Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:xampphtdocsChatAppphpsignup.php on line 11
    Something went wrong. Please try again!

  61. Notice: Undefined index: incoming_id in C:xampphtdocsChatAppphpget-chat.php on line 6

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:xampphtdocsChatAppphpget-chat.php on line 12
    No messages are available. Once you send message they will appear here.

  62. Notice: Undefined index: incoming_id in C:xampphtdocsChatAppphpget-chat.php on line 6

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:xampphtdocsChatAppphpget-chat.php on line 12
    No messages are available. Once you send message they will appear here.

  63. Giving error' message When open file chat.php?user_id=….

    ⏬⏬⏬⏬⏬⏬⏬

    Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /storage/emulated/0/htdocs/chatapp/chatapp/php/get-chat.php on line 12

  64. Giving a Eror massage when giving image

    Warning: move_uploaded_file(images/1613574012IMG-5f8954caa02539.76436861.jpg): failed to open stream: No such file or directory in G:aiman studyhtdocsnew teamregisterChatAppphpsignup.php on line 27

    Warning: move_uploaded_file(): Unable to move 'G:aiman studytmpphpBCBB.tmp' to 'images/1613574012IMG-5f8954caa02539.76436861.jpg' in G:aiman studyhtdocsnew teamregisterChatAppphpsignup.php on line 27

LEAVE A REPLY

Please enter your comment!
Please enter your name here