Welcome to this comprehensive guide on PHP Forms! This tutorial is designed to help you navigate through essential PHP Forms concepts as part of our PHP tutorial series on CodeYourCraft. π
<a name="intro"></a>
PHP Forms are an integral part of web development. They allow users to interact with a website, submitting information that can then be processed and stored in a database.
In this tutorial, we'll create various PHP forms, handle user input, validate data, sanitize inputs, and store data in a database. π‘ Pro Tip: Always validate and sanitize user input to prevent security vulnerabilities!
<a name="basic-forms"></a>
Let's start by creating a simple form using HTML and PHP. Save this as form.php.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic PHP Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="submit_form.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">
<label for="message">Message:</label>
<textarea name="message" id="message"></textarea>
<button type="submit">Submit</button>
</form>
</body>
</html>Now let's create the script to handle the form submission, submit_form.php.
<?php
// You can save this in a separate file named submit_form.php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Now we can use these variables to do something, like storing them in a database.<a name="handling-submissions"></a>
When a user submits the form, the browser sends a POST request to the server with the form data. PHP stores this data in the $_POST array.
<a name="user-input"></a>
In the example above, we collected the user's name, email, and message by using the $_POST array. We accessed the form data by using the same name attribute that was set in the HTML <input> and <textarea> elements.
<a name="input-validation"></a>
It's essential to validate user input to ensure the data provided is accurate and secure. Here's an example of validating the email input.
<?php
// ... previous code ...
// Validate the email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format.");
}<a name="sanitizing-input"></a>
Sanitizing user input protects your website from potential security threats, such as SQL Injection attacks. Here's an example of sanitizing the user's input using PHP's built-in functions.
<?php
// ... previous code ...
// Sanitize the name
$name = htmlspecialchars($name);
// Sanitize the email
$email = htmlspecialchars($email);
// Sanitize the message
$message = htmlspecialchars($message);<a name="storing-data"></a>
Now that we've validated and sanitized the user's input, let's store it in a database. First, ensure you have a MySQL database and a table to store the form data.
Here's an example of using PHP's PDO extension to connect to the database and store the form data.
<?php
// ... previous code ...
// Database connection
$db = new PDO('mysql:host=localhost;dbname=form_db', 'username', 'password');
// Prepare the SQL statement
$stmt = $db->prepare("INSERT INTO form_data (name, email, message) VALUES (?, ?, ?)");
$stmt->execute([$name, $email, $message]);
// Redirect the user to a confirmation page
header("Location: confirmation.php");
exit();<a name="form-errors"></a>
If there's an issue with the user input, you may want to display errors to the user. Here's an example of storing the errors in an array and displaying them if there are any.
<?php
$errors = [];
// Validate the name
if (empty($name)) {
$errors[] = "Please enter your name.";
}
// Validate the email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
// If there are no errors, process the form submission
if (empty($errors)) {
// ... previous code to store data in the database ...
}
?>
<!-- In the HTML form, display the errors if there are any -->
<?php if (!empty($errors)): ?>
<div class="error">
<?php foreach ($errors as $error): ?>
<p><?= htmlspecialchars($error); ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?><a name="quiz"></a>
Now that you've learned the basics of PHP Forms, test your knowledge with this quick quiz!
Which PHP function can be used to sanitize user input?