Home/Blog/Web Development/Developing Web Applications using PHP
Home/Blog/Web Development/Developing Web Applications using PHP

Developing Web Applications using PHP

Maham Amjad
Apr 18, 2024
11 min read
content
Web communication and HTTP
Understanding HTTP requests and responses
Programming languages in web applications
PHP: A popular web programming choice
HTML integration: Try your first PHP script
How to create a sign-up form in PHP
Client-side implementation
Client-side validation
Server-side implementation
Sanitizing the data
Hiding private information
Database integration
Sessions and cookies
Securing PHP applications
Conclusion
share

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.

Web communication and HTTP

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 HTTP
Communication governed by HTTP

Understanding HTTP requests and responses

HTTP supports different requests, e.g., GETPOSTPUT, 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.

Programming languages in web applications

To make a web application work, the browser uses a combination of programming languages that are generally categorized as follows:

  1. HTML: A markup language that lets us design and structure content to be displayed on the web browser.

  2. Front-end language: A scripting language that allows for dynamic and interactive elements on a web page to enable client-side interactivity.

  3. Back-end language: While not directly visible to the user, browsers communicate with the web server, which is powered by server-side programming languages.

PHP is a server-side scriptingEmploying 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.

HTML integration: Try your first PHP script

Create a file, main.php, and add the basic “Hello world!” code to it.

<!DOCTYPE html>
<html>
<body>
<b>
<?php
$name = "Hello John";
echo $name;
?>
</b>
</body>
</html>

That’s how easy it is to extend HTML. The basic PHP code is enclosed in the <body> 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:

<html>
<body>
<form>
First name: <input type="text" name="fname">
<br><br>
Last name: <input type="text" name="lname">
<br><br>
Username: <input type="text" name="username">
<br><br>
Email: <input type="text" name="email">
<br><br>
Password: <input type="password" name="password">
<br><br>
<input type="submit">
</form>
</body>
</html>

The above code creates a simple web form via the <form> 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
Username is missing
1 of 3

We can use HTML 5 and JS for client-side validation without submitting anything to the server. Update the main.php file as follows:

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000; display: none;} /* Hide error messages initially */
</style>
<script>
// Validate the password entered by a user
function validatePassword()
{
var passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}$/;
var passwordInput = document.getElementById("password");
if (!passwordPattern.test(passwordInput.value)) {
document.getElementById("passwordError").style.display = "inline"; // Display password error
return false;
}
return true;
}
// Validate the email entered by a user
function validateEmail()
{
var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
var emailInput = document.getElementById("email");
if (!emailPattern.test(emailInput.value)) {
document.getElementById("emailError").style.display = "inline"; // Display email error
return false;
}
return true;
}
// Validate the form
function validateForm() {
var isValid = true;
var errorElements = document.getElementsByClassName("error");
// Reset error message display
for (var i = 0; i < errorElements.length; i++) {
errorElements[i].style.display = "none";
}
// Validate each input
isValid = validatePassword();
isValid = validateEmail();
return isValid;
}
</script>
</head>
<body>
<form method="post" action="#" onsubmit="return validateForm();">
First name: <input type="text" name="fname">
<br><br>
Last name: <input type="text" name="lname">
<br><br>
Username: <input type="text" name="username" required>
<span id="usernameError" class="error">* Username is required</span>
<br><br>
Email: <input type="text" id="email" name="email" required>
<span id="emailError" class="error">* Valid email is required</span>
<br><br>
Password: <input type="password" id="password" name="password" required>
<span id="passwordError" class="error">* Length must be >=8 and should have 1 uppercase, 1 lowercase, 1 digit, and 1 special character</span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
  • 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.

    • Line 45: Websites want users to enter a valid email. We call the validateEmail() method.

      • 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.

  • Line 53: When the user fills out the form and clicks the “Submit” button, the form data is sent to the validateForm() function.

  • Line 58, 61, and 64: Notice the required attribute. A username, email, and password are required for registration. It won’t let the user submit the form if these fields are empty.

  • Line 59, 62, and 65: Error messages are displayed with CSS styling applied for username, email, and password, respectively.

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.

<?php
$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.

<?php
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 documentationThe 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 verification
Data verification

For example, the server stores the information passed during the successful registration in the Users table, which is a part of the website’s database.

username

fname

lname

email

password

BillJoe_123

Bill

Joe

bill.joe@gmail.com

nqi01w12nwjx

RoboRhapsody

Kim

Adams

kim.adams@gmail.com

9e2hjdwA7@8

SteveeTim_456

Steve

Tim

steve.tim@gmail.com

B928hwq%q1

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:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "simple_web_app_db";
// Establishing connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking if connected
if ($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";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
header('Location: index.html'); // Redirect back to the main page
}
?>
Registration successful: User record added in the database

In 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.

Happy learning!

Frequently Asked Questions

What is the difference between front-end and back-end development?

Front-end development focuses on the user interface and experience, dealing with languages like HTML, CSS, and JavaScript. Back-end development handles server-side operations, databases, and application logic using languages like PHP, Python, Ruby, Node.js, etc.

What is the difference between POST and GET methods in form submission?

How can I redirect users after a successful sign-up?

How can I validate form inputs in PHP?