Handling user input is a vital part of web development, as it allows you to create interactive web applications. In this lesson, we'll explore how to create and process HTML forms using PHP, including input validation and security best practices.
Creating an HTML Form
To create an HTML form, use the <form>
element and various input elements, such as <input>
, <textarea>
, and <select>
. You must specify a method (GET
or POST
) and an action (the URL of the PHP script that will process the form data).
<form method="POST" action="process_form.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<br>
<input type="submit" value="Submit">
</form>
In your PHP script, you can access the submitted form data through the $_GET
or $_POST
superglobal arrays, depending on the form method you specified.
$name = $_POST["name"];
$email = $_POST["email"];
It's crucial to validate user input before processing it, as it helps prevent security vulnerabilities and ensures that the data is in the correct format.
if (empty($name)) {
echo "Name is required.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
}
htmlspecialchars()
to convert special characters to HTML entities, which prevents Cross-Site Scripting (XSS) attacks.$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
Practice PHP forms and input handling by completing the following exercises: