Simply put, a web application is a program that runs on a browser. This program is stored on the server and is accessible to clients via any browser when required. Specific elements or functions of the web application can be processed and carried out on the server rather than solely within the user’s browser. Facebook, Netflix, Spotify, X (formerly known as Twitter), and YouTube are some famous examples of dynamic web applications that provide online services to millions of users around the globe.
Client-server communication must be governed according to some set of rules, also known as protocols. Every web application that is accessible through the browser follows HTTP (HyperText Transfer Protocol). The client sends an HTTP request, and then the server sends an appropriate response.
Communication governed by HTTPHTTP supports different requests, e.g., GET , POST , PUT , DELETE , etc., against which the server sends a response. For example, what do you think happens when you type “www.google.com" in a browser and hit “Enter” or “Return”? It sends the GET request to the server, and if no problem is encountered, the server returns a status code of 200 along with the Google search page. Otherwise, it will send the relevant status code (404 or something) and an HTML response.
To make a web application work, the browser uses a combination of programming languages that are generally categorized as follows:
PHP is a server-side scripting Employing scripts on the web server to produce a customised response as per the client's request. language that allows the creation of dynamic and interactive web pages. Instead of replacing HTML, PHP was designed to extend it. This means it can be easily embedded into HTML code. The browser can handle HTML independently, but the server must use a PHP interpreter to run the PHP scripts, take the response, and emit the corresponding HTML.
It is a simple language, which is why beginners often prefer it. A PHP website is easy to manage after it is developed. With its combination of speed, flexibility, and control, PHP remains a leading choice for web development. It is one of the most popular solutions in the digital world.
Create a file, main.php , and add the basic “Hello world!” code to it.
$name = "Hello John";echo $name;?>That’s how easy it is to extend HTML. The basic PHP code is enclosed in the of a web page (lines 5–8). In line 6, we initialized a string-type variable, $name . Try changing the value to see the updated result.
If you want a refresher on the basics of PHP, review our PHP scratch course.
How to create a sign-up form in PHP
Web forms, such as registration forms, are a popular way to interact with users. They are often the first thing users interact with before using the web application. Usually, a username, email, and password are required to set up an account. Let’s make a basic web form.
Client-side implementation
Create a file, main.php , and add the following code to it:
First name:
Last name:
Username:
Email:
Password:The above code creates a simple web form via the tag.
- Line 4: For the first name, we create the fname -labeled text field.
- Line 6: For the last name, we create the lname -labeled text field.
- Line 8: For the username, we create the username -labeled text field.
- Line 10: For the email, we create the email -labeled text field.
- Line 12: For the password, we create the password -labeled field.
Client-side validation
What if the user leaves a field blank or enters a wrong value? The data must be validated before sending it to the web server, adjusting the interface in response to user feedback. This is called client-side scripting.
Registration is not complete without a username, email, and password. Therefore, these fields must be completed when filling out the form. Also, the password must be strong for security purposes. User experience (UX) similar to the below illustration must be used to ensure users fill out the form correctly and completely.
Username is missing 1 of 3We can use HTML 5 and JS for client-side validation without submitting anything to the server. Update the main.php file as follows:
.error /* Hide error messages initially */// Validate the password entered by a userfunction validatePassword()var passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).$/;var passwordInput = document.getElementById("password");if (!passwordPattern.test(passwordInput.value))document.getElementById("passwordError").style.display = "inline"; // Display password errorreturn false;>return true;>// Validate the email entered by a userfunction validateEmail()var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;var emailInput = document.getElementById("email");if (!emailPattern.test(emailInput.value))document.getElementById("emailError").style.display = "inline"; // Display email errorreturn false;>return true;>// Validate the formfunction validateForm()var isValid = true;var errorElements = document.getElementsByClassName("error");// Reset error message displayfor (var i = 0; i < errorElements.length; i++)errorElements[i].style.display = "none";>// Validate each inputisValid = validatePassword();isValid = validateEmail();return isValid;>First name:
Last name:
Username:
Email:
Password:=8 and should have 1 uppercase, 1 lowercase, 1 digit, and 1 special character
- Lines 34–48: We define the validateForm() function to validate if the email and password follow the correct pattern.
- Line 35: We create the isvalid variable to track if the form is valid.
- Line 36: We create the errorElements variable to retrieve all elements in the document that have the class name error .
- Lines 39-41: We ensure that error messages are hidden initially when the form is submitted or revalidated. This provides a clean slate for displaying only the relevant error messages.
- Line 44: Websites want users to create a strong password matching a specific pattern. We call the validatePassword() method.
- Lines 10–19: The passwordPattern variable defines the rule that a password’s length should not exceed eight and must contain one uppercase, lowercase, number, and special character. The value entered in the password -labeled field is verified. If it doesn’t match the criteria, passwordError is displayed.
- Lines 22–31: The emailPattern variable defines the rules of valid email. The value entered in the email -labeled text field is verified. If it doesn’t match the criteria, emailError is displayed.
Server-side implementation
Also known as back-end development, this refers to a program that runs on a server. Client(s) do not have access to this type of programming. Operations like sanitizing, hashing/encrypting the data, and connecting websites to databases are implemented on the server side.
Sanitizing the data
We can sanitize data both on the client and server side. Client-side sanitization helps improve user experience by providing immediate feedback to the user, while the latter is crucial for security and data integrity.
We can use various PHP functions “PHP: Sanitize Filters - Manual.” n.d. Www.php.net. https://www.php.net/manual/en/filter.filters.sanitize.php. and filters to sanitize different types of data, such as strings, numbers, emails, and URLs. For example, we can use FILTER_SANITIZE_EMAIL to remove illegal characters from an email address.
$email = "bill(.joe)@gma/il.com";$email = filter_var($email, FILTER_SANITIZE_EMAIL);echo $email;?>Notice how the parentheses are removed from the email address.
Tip: Try using server-side validation rather than relying solely on client-side validation. Unlike server-side validation, client-side validation can be circumvented.
Hiding private information
It’s unsafe to add passwords as plain text in the database. A hacker may access the stored passwords associated with each email. The solution is to make passwords unreadable to the outside party, a technique known as hashing.
if ($_SERVER['REQUEST_METHOD'] === 'POST')$password = htmlspecialchars($_POST['password']);// Hashing the password$password = password_hash($password, PASSWORD_DEFAULT);>?>The password_hash() function takes two arguments: the password and the hashing algorithm. In this example, we use the PASSWORD_DEFAULT algorithm (You can find more hashing algorithms in PHP’s documentation The PHP Group. 2015. “PHP: Password_hash - Manual.” Php.net. 2015. https://www.php.net/manual/en/function.password-hash.php. ).
Database integration
To register, the user must enter a unique username. Now, imagine millions of users using a website managed by multiple servers. Where do you think the data of a million users is stored? The answer is “a database.”
When a user tries to register, the server verifies the credentials from the database. If no duplicate exists, only then the user’s account will be created. The same applies to a login request. When a user tries to log in, the server verifies the credentials from the database. If such a record exists, only then the user can access services.
Data verificationFor example, the server stores the information passed during the successful registration in the Users table, which is a part of the website’s database.
The following steps need to be performed:
- Connect to your database.
- Receive data from the web form via the POST request.
- Insert a value in the database.
Create a file, register.php , and add the following code to it:
$servername = "localhost";$username = "your_username";$password = "your_password";$dbname = "simple_web_app_db";// Establishing connection$conn = new mysqli($servername, $username, $password, $dbname);// Checking if connectedif ($conn->connect_error)die("Connection failed: " . $conn->connect_error);>if ($_SERVER['REQUEST_METHOD'] === 'POST')$fname = htmlspecialchars($_POST['fname']);$lname = htmlspecialchars($_POST['lname']);$username = htmlspecialchars($_POST['username']);$email = htmlspecialchars($_POST['email']);$email = filter_var($email, FILTER_SANITIZE_EMAIL);$password = htmlspecialchars($_POST['password']);$password = password_hash($password, PASSWORD_DEFAULT); // Hashing the password// Insert data into the database$sql = "INSERT INTO Users VALUES ('$username', '$fname', '$lname', '$email, '$password')";if ($conn->query($sql) === TRUE)echo "Registeration successful";> elseecho "Error: " . $sql . "
" . $conn->error;>$conn->close();header('Location: index.html'); // Redirect back to the main page>?>Registration successful: User record added in the databaseIn the above example, the server is connecting to an SQL database.
- Lines 2–5: We create a few variables, $servername , $username , $password , and $dbname , to establish a connection with the database. Do not forget to change the values according to your database’s credentials.
- Lines 8–13: We establish the connection through the mysqli() function.
- Lines 15–21: We fetch data from the web form received via the POST request. In line 20, we sanitize the email before entering it into the database. Notice line 38 of index.html . The form data is sent for processing to a PHP file named register.php via the POST method.
- Lines 25–30: We insert data in the database via an SQL query.
The server should validate the data, check for any possible errors, and filter the unwanted data before entering it into the database.
Sessions and cookies
In web development, both sessions and cookies are used to maintain the app state and manage user interactions.
Sessions help manage user-specific data throughout their interaction with a web application. This allows for personalized user experiences by storing user preferences.
To use sessions in PHP, we need to start a session at the beginning of our script:
session_start();
We can store user-specific information in session variables:
$_SESSION['username'] = 'BillJoe_123';
We can access session variables:
$userName = $_SESSION['username'];
We should log out or end the session when the user logs out or after a period of inactivity:
session_destroy();
Cookies are small pieces of data stored on the client’s browser, which are sent back to the server with subsequent requests. They help maintain state information between requests, which is crucial for tracking user activities.
We can set a cookie to store information on the user’s browser:
setcookie('username', 'BillJoe_123, time() + 3600, '/');
Here, username is the cookie. “BillJoe_123” is the value of the cookie. The expiry time is time() + 3600 . The path for which the cookie is valid is '/' .
We can access cookie values:
$username = $_COOKIE['username'];
We should remove a cookie when it’s no longer needed:
setcookie('username', '', time() - 3600, '/');
Securing PHP applications
We can follow these best practices to enhance the security of our PHP applications:
- Always validate user input to prevent attacks and other security vulnerabilities.
- Implement error handling to provide minimal information to users while logging detailed errors for developers.
- Avoid storing sensitive information in cookies and use sessions for server-side storage.
- Set reasonable session expiration times to mitigate the risk of session hijacking.
- Always stay informed about the latest security recommendations.
- Regularly audit your codebase for security attacks and implement monitoring to detect suspicious activities.
- Keep your PHP version, libraries, and frameworks up to date.
Conclusion
Before you start actually writing some code, it’s important to think about your project first. Starting coding straight away won't serve you right. Take a seat, relax, and decide on the technologies you want to use. Which server do you want to use? Where will you store the data and host your PHP application? What is the best framework to use? These questions must be answered.
You can consider Apache or Nginx for your server, MySQL or PostgreSQL for your database, and Laravel or Symfony as a PHP framework. You can set up a local development environment using options like XAMPP and MAMP or configure PHP with a web server like Apache. The local development environment allows programmers to test and debug their projects before deploying them to a live server.
Whatever is discussed above is just the tip of the iceberg. To learn more, take our course Developing Web Applications with PHP, which is designed for people who have already learned the basics of PHP and want the bigger picture of making big web applications with PHP.
![]()