PHP Form Handling with Examples

Hey friend! 👋 So, you want to learn how to handle forms in PHP? Awesome! Forms are like the backbone of web applications they let users interact with your website by submitting data. Whether it’s a login form, a contact form, or a survey, PHP makes it super easy to handle form data. Let’s dive in and learn how to do this step by step. I’ll keep it simple and fun, promise!

 

 

php form handling with examples

 

 

 

What is Form Handling?

 

Form handling is the process of collecting data from users through HTML forms and processing it using a server-side language like PHP. When a user fills out a form and hits "Submit," the data is sent to the server, where PHP can work its magic.

 

Let’s Start with a Simple HTML Form

 

First, we need an HTML form. Let’s create a basic form with two fields: name and email.

 


<!DOCTYPE html>
<html>
<head>
    <title>My First PHP Form</title>
</head>
<body>
    <h1>Contact Me!</h1>
    <form action="process_form.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>
    

 

Here’s what’s happening:

 

  • The action attribute tells the form where to send the data (in this case, process_form.php).
  • The method attribute specifies how to send the data. We’re using POST because it’s more secure for sensitive data.


Tip : Always sanitize and validate user input to prevent security vulnerabilities like SQL injection and XSS attacks. Use functions like htmlspecialchars() and filter_var() to ensure data is safe before processing or displaying it.



 

Handling the Form Data in PHP

 

Now, let’s create the process_form.php file to handle the form submission.

 


<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form data
    $name = $_POST["name"];
    $email = $_POST["email"];

    // Display the data
    echo "<h1>Thank You!</h1>";
    echo "<p>Your name is: " . htmlspecialchars($name) . "</p>";
    echo "<p>Your email is: " . htmlspecialchars($email) . "</p>";
} else {
    // If the form isn't submitted, show an error
    echo "<p>Oops! Something went wrong.</p>";
}
?>
    

 

What’s Going On Here?

 

  1. Check if the form is submitted: We use $_SERVER["REQUEST_METHOD"] to check if the form was sent using the POST method.
  2. Get the form data: We use the $_POST superglobal to access the form data. For example, $_POST["name"] grabs the value from the "name" input field.
  3. Display the data: We use echo to show the submitted data. Notice the htmlspecialchars() function? It’s a security measure to prevent XSS attacks by converting special characters to HTML entities.

 

Adding Validation (Because Safety First!)

 

Let’s make sure the user enters valid data. Here’s how we can add some basic validation:

 


<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form data
    $name = trim($_POST["name"]);
    $email = trim($_POST["email"]);

    // Validate the data
    $errors = [];

    if (empty($name)) {
        $errors[] = "Name is required.";
    }

    if (empty($email)) {
        $errors[] = "Email is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format.";
    }

    // If there are no errors, display the data
    if (empty($errors)) {
        echo "<h1>Thank You!</h1>";
        echo "<p>Your name is: " . htmlspecialchars($name) . "</p>";
        echo "<p>Your email is: " . htmlspecialchars($email) . "</p>";
    } else {
        // Show errors
        echo "<h1>Oops!</h1>";
        foreach ($errors as $error) {
            echo "<p>" . htmlspecialchars($error) . "</p>";
        }
    }
}
?>
    

 

What’s New?

 

  • trim(): Removes extra spaces from the input.
  • empty(): Checks if a field is empty.
  • filter_var(): Validates the email format.
  • Error handling: If there are errors, we display them instead of the submitted data.


Tip : Use the appropriate HTTP method (POST for sensitive data and GET for non-sensitive data) to ensure data is transmitted securely and efficiently. Remember, POST hides data in the request body, while GET appends it to the URL.



 

Bonus: Using GET Instead of POST

 

Sometimes, you might want to use the GET method instead of POST. For example, in search forms. Here’s how it works:

 

  1. Change the form’s method to GET:
    
    <form action="process_form.php" method="GET">
                
  2. In PHP, use $_GET instead of $_POST:
    
    $name = $_GET["name"];
    $email = $_GET["email"];
                

 

The main difference is that GET sends data in the URL, while POST sends it in the background. Use POST for sensitive data and GET for non-sensitive data.

 

 

Done.!

 

And that’s it, friend! 🎉 You’ve just learned how to handle forms in PHP. Here’s a quick recap:

 

  1. Create an HTML form.
  2. Use $_POST or $_GET to access form data in PHP.
  3. Validate the data to keep things secure.
  4. Display the data or show errors.

 

Now go ahead and build your own forms! Whether it’s a contact form, a login page, or a survey, you’ve got the skills to handle it.  😊

 

Happy coding! 🚀

chandrakumar

Hi, Am Chandra Kumar, I have completed my graduation in B.E computer science and Engineering. I am the founder of Dailyaspirants and I have been doing blogging and website design and development .since 2018 and 8+experience gained in this field.

*

Post a Comment (0)
Previous Post Next Post