In web development, forms are essential for collecting user input. Whether you're building a contact form, a login page, or any other type of interactive application, understanding how to create and process HTML forms using PHP is crucial. This tutorial will guide you through the basics of creating HTML forms and processing them with PHP.
HTML forms allow users to enter data that can be sent to a server for processing. The form data is typically submitted via HTTP methods like GET or POST. In this tutorial, we'll focus on using the POST method, which is more secure for sending sensitive information.
When a form is submitted, the data is sent to the server-side script specified in the action attribute of the <form> tag. PHP scripts can then access and process this data using superglobal arrays like $_POST.
Let's start by creating a simple HTML form that collects a user's name and email.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
</head>
<body>
<form action="process_form.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In this example, the form is set to submit data to a PHP script named process_form.php using the POST method.
Now, let's create the process_form.php file to handle the submitted data.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "<h2>Form Submitted</h2>";
echo "<p>Name: " . $name . "</p>";
echo "<p>Email: " . $email . "</p>";
}
?>
In this PHP script, we first check if the form was submitted using the POST method. We then retrieve the values of the name and email fields from the $_POST superglobal array. The htmlspecialchars() function is used to prevent XSS (Cross-Site Scripting) attacks by converting special characters to HTML entities.
When you submit the form, the output will look like this:
<h2>Form Submitted</h2>
<p>Name: John Doe</p>
<p>Email: john.doe@example.com</p>
In the next section, we'll explore how to validate user input in PHP forms to ensure that the data meets specific criteria before processing it. This is crucial for maintaining the integrity and security of your application.
Stay tuned for more tutorials on PHP form validation!