
Getting Started with PHP: Building Web Forms
Creating a Basic HTML Form
To get started, we will create a basic HTML form. This form will collect a user's name and email address. Create a new file named form.php and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple PHP Form</title>
</head>
<body>
<h1>User Information Form</h1>
<form action="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>Handling Form Submission
Next, we need to handle the form submission. When the user submits the form, we will process the input data. Modify the form.php file to include the following PHP code at the top:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize input data
$name = htmlspecialchars(trim($_POST['name']));
$email = htmlspecialchars(trim($_POST['email']));
// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<h2>Thank you, $name!</h2>";
echo "<p>Your email address is: $email</p>";
} else {
echo "<h2>Invalid email format.</h2>";
}
}
?>Explanation of the Code
- Form Structure: The form uses the
POSTmethod to submit data to the same page (form.php). Each input field has a correspondinglabelfor accessibility.
- Form Handling: The PHP block checks if the request method is
POST, indicating that the form has been submitted. It retrieves the values ofnameandemailfrom the$_POSTsuperglobal.
- Sanitization: The
htmlspecialcharsfunction is used to prevent XSS (Cross-Site Scripting) attacks by converting special characters to HTML entities. Thetrimfunction removes any unnecessary whitespace.
- Validation: The
filter_varfunction is employed to validate the email format. If the email is valid, a thank-you message is displayed; otherwise, an error message is shown.
Best Practices for Form Handling
When working with forms in PHP, consider the following best practices:
| Best Practice | Description |
|---|---|
| Use HTTPS | Always use HTTPS to encrypt data submitted through forms. |
| Sanitize Input | Sanitize all user input to prevent XSS and SQL injection attacks. |
| Validate Input | Validate data on the server side to ensure it meets expected formats. |
| Use Prepared Statements | When interacting with databases, use prepared statements to prevent SQL injection. |
| Provide User Feedback | Always inform users of successful submissions or errors. |
Enhancing the Form with CSS
To improve the user experience, you can add some basic CSS styling. Add the following <style> section inside the <head> of your form.php file:
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
width: 300px;
}
input[type="text"],
input[type="email"] {
width: 100%;
padding: 10px;
margin: 5px 0 15px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
input[type="submit"] {
background-color: #4CAF50;
color: white;
padding: 10px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>Conclusion
In this tutorial, you learned how to create a simple web form using PHP, handle form submissions, and validate user input. You also explored best practices for secure form handling and enhanced the form's appearance with CSS. This foundational knowledge will enable you to build more complex forms and applications in PHP.
