Ugacomp

A Beginner’s Guide to Using Forms and User Input in PHP

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM

CLOUD VPS M

$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM

CLOUD VPS L

$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

Creating dynamic and interactive web applications often involves handling user input through forms. PHP provides robust features for processing form data. This beginner’s guide will walk you through the basics of using forms and handling user input in PHP, with practical command examples.

Setting Up a Simple HTML Form

Let’s start by creating a basic HTML form to collect user input. Save the following code in a file named index.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Form Example</title>
</head>
<body>
    <h2>Simple Form</h2>
    <form method="post" action="process.php">
        <label for="username">Username:</label>
        <input type="text" name="username" required>

        <label for="password">Password:</label>
        <input type="password" name="password" required>

        <button type="submit">Submit</button>
    </form>
</body>
</html>

This form includes fields for a username and password. The method attribute is set to “post,” and the action attribute specifies the PHP file that will process the form data.

Processing Form Data in PHP

To handle form submissions in PHP, you typically use the $_POST superglobal to retrieve data sent via the HTTP POST method. Here’s a basic example:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user input
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Further processing or validation can be done here
}

In this code:

  • $_SERVER["REQUEST_METHOD"] checks if the form was submitted using the POST method.
  • $username and $password are assigned the values from the “username” and “password” fields in the submitted form.

Now, let’s create the process.php file to handle the form data:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user input
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Perform validation or other processing as needed
    // For simplicity, we'll just display the input
    echo "<h3>Submitted Data:</h3>";
    echo "<p>Username: $username</p>";
    echo "<p>Password: $password</p>";
}
?>

This PHP code snippet is a simple form-handling script that operates when the submitted form uses the HTTP POST method. The if ($_SERVER["REQUEST_METHOD"] == "POST") condition ensures that the code within the block runs only when a form is submitted using the POST method.

Inside the block, the script retrieves user input from the submitted form. It assigns the values of the “username” and “password” fields to the variables $username and $password, respectively. These fields are commonly part of an HTML form where users input their username and password.

Following the input retrieval, the script displays the submitted data for demonstration purposes. The echo statements output HTML code that shows a header (“Submitted Data:”) and paragraphs containing the submitted username and password.

Handling Form Validation in PHP

Basic validation involves ensuring that required fields are not empty. Here’s a simple validation example:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user input
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Basic validation
    if (empty($username) || empty($password)) {
        echo "Both username and password are required.";
    } else {
        // Valid input - proceed with further processing
    }
}

In this code:

  • empty($username) checks if the username field is empty.
  • empty($password) checks if the password field is empty.
  • An error message is echoed if either field is empty, otherwise, the script proceeds.

Sanitizing User Input and Enhancing Form Security

Sanitizing user input is crucial for security. The htmlspecialchars function helps prevent cross-site scripting (XSS) attacks by converting special characters to HTML entities:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve and sanitize user input
    $username = htmlspecialchars(trim($_POST["username"]));
    $password = htmlspecialchars(trim($_POST["password"]));

    // Validation and further processing
}

In this code:

  • htmlspecialchars is applied to both username and password to sanitize input.
  • trim removes leading and trailing whitespaces from the input.

Let’s expand the process.php file to include server-side validation:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve and sanitize user input
    $username = htmlspecialchars(trim($_POST["username"]));
    $password = htmlspecialchars(trim($_POST["password"]));

    // Validate input
    if (empty($username) || empty($password)) {
        echo "<h3>Error:</h3>";
        echo "<p>Username and password are required!</p>";
    } else {
        // Process the valid input
        echo "<h3>Submitted Data:</h3>";
        echo "<p>Username: $username</p>";
        echo "<p>Password: $password</p>";
        // Additional processing or database interactions can be added here
    }
}
?>

This PHP code snippet is designed to process form submissions sent using the HTTP POST method. The if ($_SERVER["REQUEST_METHOD"] == "POST") statement ensures that the code block is executed only when a form is submitted.

Within the block, the script retrieves and sanitizes user input from the submitted form. The htmlspecialchars function is used to convert special characters to HTML entities, helping to prevent potential security vulnerabilities. The trim function removes any leading or trailing whitespaces from the user input.

After sanitizing the input, the script proceeds to validate it. The empty function checks if both the username and password fields are not empty. If either is empty, an error message is displayed indicating that both fields are required.

In the case of valid input, the script prints a header and paragraphs displaying the submitted username and password. Additionally, there is a comment suggesting that developers can include additional processing or database interactions at this point, such as storing the data in a database.

Capturing and Handling Form Submissions in PHP

Now that you’ve implemented basic form validation, let’s take the next step and explore how to capture form submissions securely and handle them effectively in PHP.

Improving PHP Script for Form Processing

Update the process.php file to include more robust handling of form submissions:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve and sanitize user input
    $username = htmlspecialchars(trim($_POST["username"]));
    $password = htmlspecialchars(trim($_POST["password"]));

    // Validate input
    if (empty($username) || empty($password)) {
        echo "<h3>Error:</h3>";
        echo "<p>Username and password are required!</p>";
    } else {
        // Process the valid input
        echo "<h3>Submitted Data:</h3>";
        echo "<p>Username: $username</p>";

        // Hash the password for security
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        echo "<p>Hashed Password: $hashedPassword</p>";

        // Additional processing or database interactions can be added here
    }
}
?>

In this updated script, the password is hashed using the password_hash function, enhancing security. Storing plain-text passwords is a significant security risk, and hashing helps protect user credentials.

Handling File Uploads

Forms often include file upload functionality. Let’s extend our example to handle file uploads securely:

<!-- Updated form with file upload -->
<form method="post" action="process.php" enctype="multipart/form-data">
    <!-- Existing form fields -->

    <label for="file">Upload File:</label>
    <input type="file" name="file" id="file">

    <button type="submit">Submit</button>
</form>

Update the process.php script to handle file uploads:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Existing code for username and password

    // Handle file upload
    if (isset($_FILES["file"])) {
        $file = $_FILES["file"];

        // Check for upload errors
        if ($file["error"] === UPLOAD_ERR_OK) {
            $uploadPath = "uploads/" . basename($file["name"]);

            // Move the uploaded file to the desired directory
            move_uploaded_file($file["tmp_name"], $uploadPath);
            echo "<p>File uploaded successfully: $uploadPath</p>";
        } else {
            echo "<p>Error uploading file.</p>";
        }
    }
}
?>

This PHP code is designed to process data submitted through a web form, particularly when the form uses the HTTP POST method. It first checks if the form was indeed submitted using POST ($_SERVER["REQUEST_METHOD"] == "POST").

Inside this condition, there’s code handling username and password, which is not shown in this snippet but assumed to be present.

Also, the code includes a part to handle file uploads. It checks if a file was included in the form submission (isset($_FILES["file"])). If a file is present, it further checks for any upload errors. If there are no errors ($file["error"] === UPLOAD_ERR_OK), it defines a destination path in the “uploads/” directory based on the file name. The script then moves the uploaded file from its temporary location ($file["tmp_name"]) to the specified directory using move_uploaded_file. Finally, it echoes a success message with the uploaded file’s path. If there are any errors during the file upload process, it echoes an error message.

Enhancing User Experience with PHP and AJAX

Now that you’ve mastered the fundamentals of form handling and validation in PHP, let’s take a step further by incorporating AJAX (Asynchronous JavaScript and XML) to enhance the user experience.

Implementing Real-Time Validation

Adding real-time validation to your form can provide users with instant feedback as they type. Let’s enhance our form with AJAX to check the availability of a username:

<!-- Updated form with real-time validation -->
<form method="post" action="process.php" id="myForm">
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" required>
    <span id="usernameStatus"></span>

    <label for="password">Password:</label>
    <input type="password" name="password" id="password" required>

    <button type="submit">Submit</button>
</form>

<script>
    // AJAX for real-time username validation
    document.getElementById("username").addEventListener("input", function () {
        var username = this.value;
        var statusSpan = document.getElementById("usernameStatus");

        // Send an AJAX request to check username availability
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "checkUsername.php", true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                statusSpan.innerHTML = xhr.responseText;
            }
        };
        xhr.send("username=" + username);
    });
</script>

Create a new file named checkUsername.php to handle the AJAX request:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = htmlspecialchars(trim($_POST["username"]));

    // Simulate checking username availability
    $available = checkUsernameAvailability($username);

    if ($available) {
        echo "<span style='color: green;'>Username available!</span>";
    } else {
        echo "<span style='color: red;'>Username not available.</span>";
    }
}

function checkUsernameAvailability($username) {
    // Implement your logic to check username availability (e.g., query a database)
    // For demonstration purposes, return true if username is not empty
    return !empty($username);
}
?>

This example demonstrates how to use AJAX to check the availability of a username in real-time. The checkUsername.php file simulates the process of checking username availability, and you can replace it with your logic, such as querying a database.

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.
 

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.