Skip to content

PHP Chat Application With Source Code [COMPLETE PROJECT]

Updated: at 06:00 PM
Time to read: 5 min
Author: Mouad Nassri
🔗 SOURCE CODE HERE

This is a full chat application written in plain PHP, and it is my first web application that I made for the purpose of learning web development, along with programming languages and technologies including PHP, MySQL, HTML, CSS, and JavaScript. In this article, I want to share with you some explanations about the main concepts and topics covered in this app and how they are implemented.

Demo video

Steps to set up the project

  1. Install git on your device

  2. Install composer on your device

  3. Get a local server (Install XAMPP)

  4. Clone the project: After installing XAMPP and go to the location where you installed it. You will find a htdocs folder, or www if you use WAMP Server. Clone the project there by opening the terminal and running the following command (as shown in the demo at 05:02) :
git clone git@github.com:Hostname47/PHP-CHAT.git chat
  1. Create a database: Go to your phpMyAdmin, and open SQL tab, and run the following command to create the database:
CREATE DATABASE chat;

It is important to name your database ‘chat’ because this name is used in configuration files.

  1. Import the database tables and relationships: Go to the project folder, and under the database folder, there is a file called chat.sql. Copy all its content, open phpMyAdmin again, go to the databases list in the left sidebar, select the CHAT database, open the SQL tab, paste the content there, and click on Go to run the query.

  2. Install php dependencies: Go back to the project folder, open the terminal and run the following command:

composer install
  1. Now, you are able to access the project from your browser, by typing localhost/CHAT in the address bar.

Explanations:

Here, I have tried to separate each concept and discuss it in separated sections to make it easier for you to navigate and learn the concepts used within this project.

1. Redirect

Before discussing authentication, we need to address the concept of redirects. When a user visits the application for the first time, any path they access will redirect them to the login page.

An HTTP redirect is an action from the web server that tells the browser to automatically take the user to a different URL path. We used it here to redirect guest (unauthenticated) users to the login page, but it can be used in many scenarios, such as redirecting from an old URL to a new URL or domain, or guiding heavy traffic for load balancing. The server replies with a status code like 301 (permanent) or 302 (temporary) along with the new URL.

2. Authentication (Login / Sign in):

In every application, Authentication involves several steps, including the sign-up phase, which is the registration, as well as the login phase, which is responsible for logging the user into the application. You also have a page where you allow the user to change their credentials, validate their email address, and remove their account.

The sign-up phase is a simple creation process: you create a form for the user to fill in their personal information, and when they press the create button, you store the data in the database.

The login phase is basically a check step, where you check the username/email along with the password to see if they match the records stored in the database. The password requires an extra step, which is hashing the received password and checking if the hash value matches the hashes stored in the database records.

3. Hashing:

Here there is a really important concept to talk about, and that is Hashing. When the user enters their password, and you get the password in the payload, you SHOULD NOT store it directly in a plaintext format. Instead, what you need to do is hash it.

Hashing is the process of converting the user’s password into a fixed-length, unique string using a hash function, ensuring that the original password cannot be easily retrieved. This way, you protect the user passwords stored within your database in case your database is exposed or attacked.

In the project, you can see the process of hashing inside classes/Hash.php, where I define a function called make which is responsible for taking a string and hashing it using an algorithm called sha256, and returning a hashed content. (Salt within the function signature will be covered in the next section.)

I included a comment where I explain exactly what is happening and how to use it. The Hash class within classes/Hash.php is used in models/User.php to hash the user’s password in the registration phase, as well as in the login step.

If we hash the password in the registration phase, then how can we check if the password matches the next time the user logs in? We check it by hashing the input again and comparing the hash stored in the database with the hashed password entered by the user.

4. Salt

The concept of Salt, basically, is a random value added to the password before hashing to ensure consistency and make sure every password, when hashed, will give a unique value. For instance, when two users choose to use the same password, using salt will generate two different hashes for each one. This is useful to protect your users from attacks like rainbow table attacks.

Generating and using salt is available in the Hash class, where we have a salt function that generates a random value to be passed to the make function. The make function then passes it to the global hash function by concatenating the string (password) with the salt before hashing it.

5. Short Polling / Long polling

Short and long polling are two different techniques used to retrieve data, involving the concepts of Client and Resource. The client can be a JavaScript application, while the resource is a PHP backend.

In the short polling model, the client continuously makes calls to the resource server in an attempt to retrieve data, update something, or perform an action. The resource may respond with an empty payload or with a data object body if the resource exists. In this model, the client repeats this process approximately every 3 seconds: it sends a request, waits for the response, processes it, and then sends another request, and so on.

I used this model to update the last time the user interacts with the app. You can find this within the public/javascript/config.js file, where I constantly make requests every 2 minutes to update the last time the user interacted with the app and display them as a connected member. The request triggers the server/update_active_presence.php file to call the update_presence function within the User class, which updates the user_info column responsible for showing members online.

The concept of Long polling, on the other hand, works a little differently than short polling. In long polling, the client makes a request to the resource, and the resource receives the request. It has two options: if it has the data, it responds right away, and everything works as usual. However, if it does not have any data, it keeps the connection open until it receives data from the server and then sends the response to the client.

I used this model in the chatting procedure. When the user opens a chat tab to chat with a friend, we send a request to the long polling file within server/long-polling.php. Then, the script opens an infinite loop to check for any messages coming from a friend within a table called channel. If the server finds something that belongs to the current user, it responds with the component that will hold the message and closes the connection. Then, the user makes another call to open the connection again and wait for new messages.

6. Flash messages

Temporary messages or Flash messages or notifications displayed to users to provide feedback when a procedure is completed, or when there is an error or informational message. These messages are usually displayed after the user takes an action or submits a form and disappear after a short period or when the page is reloaded.

This is used within the application in several places, like when a new user registers for the application, we show them a flash message inside the index page. Session messages or notifications are stored within PHP sessions, and once the user consumes the message, we remove the viewed message from the session.

7. AJAX

The technique of AJAX, which stands for Asynchronous JavaScript and XML, is a web development technique that allows web applications to make requests and update the page content asynchronously by exchanging data with the server in the background, without the need to refresh the browser or the page.

We use this technique throughout the application. For example, when the user wants to create a post, we use AJAX calls using the jQuery AJAX helper function to make an asynchronous AJAX call to create the post without refreshing the page. See public/javascript/post.js file on line 484.

8. Components (UI)

UI components are reusable pieces of code that represent elements in the UI, such as buttons, input fields, and modals, encapsulating both structure and behavior to create a consistent and efficient user experience.

Since I didn’t use any frontend library to help me create reusable components, the way I implemented it is by having components defined on the server. When the client needs to add an item to a collection, what I did is return the component HTML content by filling the slots with the data of the item, append it to the DOM, and handle events by attaching event handlers one by one.

You can see this in the project when the user creates a new post. I return the post HTML content once the post is stored in the database. Then, I make another request to get the last post wrapped within the component UI and prepend it to the posts list to show it first. See public/javascript/post.js file, line 538.

And so on..

There are other techniques and concepts used within the project, but be cautious; the code is quite messy. It’s not really meant for use; it’s more of a ‘watch and see what’s happening’ situation… lol.

I hope you find this article useful !