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!
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.
<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.
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
// 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 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
// 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.
To handle errors gracefully, we'll create an error array and check for errors before processing the data.
<?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.
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! π€π