Handling user input is a crucial aspect of web development. This tutorial covers how to collect data from HTML forms, validate it, and process it using PHP.
Handling HTML Input with PHP
1. Creating an HTML Form
To handle user input, you first need to create an HTML form. Here's a simple example:
<form method="post" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
This form collects a user's name and email address and submits it to a file named process.php
.
2. Processing the Input in PHP
In process.php
, you can access the submitted data using the $_POST
superglobal array:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST["name"]);
$email = htmlspecialchars($_POST["email"]);
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
The htmlspecialchars()
function is used to prevent XSS (Cross-Site Scripting) attacks by escaping special characters.
3. Validating User Input
Before processing the input, you should validate it to ensure it meets the expected format. Here’s how to validate the name and email:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars(trim($_POST["name"]));
$email = htmlspecialchars(trim($_POST["email"]));
$errors = [];
// Validate name
if (empty($name)) {
$errors[] = "Name is required.";
} elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
$errors[] = "Only letters and white space are allowed in the name.";
}
// Validate email
if (empty($email)) {
$errors[] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
// Display errors or process the input
if (!empty($errors)) {
foreach ($errors as $error) {
echo "<p>$error</p>";
}
} else {
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
}
?>
4. Using GET Method
Alternatively, you can use the GET method to submit the form. The process is similar, but the data will be sent in the URL.
<form method="get" action="process.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<input type="submit" value="Submit">
</form>
In process.php
, you can access the data using $_GET
:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = htmlspecialchars($_GET["name"]);
$email = htmlspecialchars($_GET["email"]);
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
5. Summary
Handling HTML input in PHP involves creating forms, processing submitted data, and validating user input. By following best practices, such as using htmlspecialchars()
for escaping output and validating input, you can create secure and reliable applications.