PHP Form Handling πŸ“πŸŽ―

beginner
16 min

PHP Form Handling πŸ“πŸŽ―

Welcome to this comprehensive guide on PHP Form Handling! By the end of this tutorial, you'll be able to create, handle, and validate forms using PHP in your web projects. Let's dive in!

Understanding PHP Forms πŸ“

A PHP form is a method for collecting user input via a webpage. It consists of an HTML form with input fields, and PHP scripts to process the submitted data.

html
<form action="process.php" method="post"> <!-- Input fields, submit button, etc. --> </form>

πŸ’‘ Pro Tip: Always use the method="post" attribute in your form to ensure data security.

Sending Data to PHP Script 🎯

When a user submits a form, the data is sent to the specified PHP script (process.php in our example). Let's create a simple PHP script to process our form data.

php
<?php // Get form data $name = $_POST['name']; $email = $_POST['email']; // Output form data echo "Name: $name"; echo "<br>"; echo "Email: $email"; ?>

πŸ“ Note: The $_POST array contains the data sent by the HTML form when the form is submitted using the POST method.

Validating Form Data 🎯

Validating form data is crucial to ensure the quality of data being stored or processed. Here's a simple validation example for a user's email address.

php
<?php // Get form data $email = $_POST['email']; // Validate email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { die("Invalid email format."); } // Output form data echo "Email: $email"; ?>

πŸ’‘ Pro Tip: Use PHP's built-in filter_var() function for basic data validation.

Handling Form Errors 🎯

To handle errors gracefully, we'll create an error array and check for errors before processing the data.

php
<?php // Initialize error array $errors = []; // Get form data $name = $_POST['name']; $email = $_POST['email']; // Validate name if (empty($name)) { $errors[] = "Name is required."; } // Validate email if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; } // Check for errors if (!empty($errors)) { // Output errors and form foreach ($errors as $error) { echo $error . "<br>"; } // Display form echo <<<FORM <form action="process.php" method="post"> <label for="name">Name:</label> <input type="text" name="name" id="name"> <label for="email">Email:</label> <input type="email" name="email" id="email"> <input type="submit" value="Submit"> </form> FORM; } else { // Process data without errors // ... } ?>

πŸ’‘ Pro Tip: Use empty() function to check if a variable is empty or not.

Quiz

Quick Quiz
Question 1 of 1

Which PHP variable contains the data sent by an HTML form using the POST method?

That's it for this lesson! You now have a solid understanding of PHP Form Handling. In the next lesson, we'll dive into PHP sessions and cookies. Keep coding! πŸ€–πŸš€