[PHP for Beginners] The Heart of a Website! How to Receive Data from Forms
A "Contact Us" form is essential for any website. It's a vital window that connects site operators with visitors, allowing you to receive questions and feedback—truly the heart of a website. However, many people might feel it's difficult, wondering, "I want to create a form, but how do I receive the submitted data?"
This article will carefully explain the core process of "receiving data from an HTML form with PHP and displaying it on a confirmation page" in a way that even beginners can understand. This time, using a simple mail form with three fields—`name`, `email`, and `message`—as an example, we will learn how to implement both the input form and the confirmation screen in a single file. We've prepared code that works just by copying and pasting, so please experience the joy of making things "work"!
To get your PHP running (development environment), if you haven't set up XAMPP yet, please refer to [PHP for Beginners] A Complete Guide to Downloading and Installing XAMPP!. After installation, place your PHP file in the specified folder (like `htdocs`), and you're all set!
1. How Web Forms Work: HTML and PHP Working Together
A web form is broadly composed of two parts.
- HTML: The "front-end" part where users input text.
- PHP: The "back-end" part that receives and processes the submitted data.
First, let's look at the HTML <form> tag. This is the body of the form.
<!-- Specify the data submission destination (action) and method -->
<form action="receive.php" method="POST">
<!-- Each input field is given a "name" to receive the data in PHP -->
<p>Name: <input type="text" name="user_name"></p>
<p>Email: <input type="email" name="user_email"></p>
<p><button type="submit">Send</button></p>
</form>
The important parts are `method="POST"` and the `name` attribute of each input field. `POST` is a secure method for sending data without displaying it in the URL, and it's commonly used for forms. The name given to the `name` attribute becomes the "key" for receiving the data on the PHP side.
On the PHP side, you use a special variable called `$_POST` (a superglobal variable) to receive the data. By specifying the HTML's `name` attribute as the key, like `$_POST['user_name']`, you can retrieve the entered value.
<?php
// Display the data sent from the input field named "user_name"
echo $_POST['user_name'];
// Display the data sent from the input field named "user_email"
echo $_POST['user_email'];
// Check all data sent via POST (for debugging)
print_r($_POST);
?>
This collaboration between HTML and PHP is the basic mechanism of web forms.
2. In Practice! Creating an Input Form and Confirmation Screen in One File
Now, let's implement the functionality for an input form and a confirmation screen in a single PHP file. The advantage of this method is that file management becomes simpler. The following code is a complete sample that you can copy and paste into a file to immediately check its operation in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Form</title>
<style>
body { font-family: sans-serif; line-height: 1.7; padding: 20px; max-width: 600px; margin: auto; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input[type="text"], input[type="email"], textarea {
width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;
}
textarea { height: 120px; }
.confirmation-table { width: 100%; border-collapse: collapse; }
.confirmation-table th, .confirmation-table td { border: 1px solid #ddd; padding: 12px; text-align: left; }
.confirmation-table th { background-color: #f2f2f2; width: 30%; }
button { padding: 10px 20px; border: none; background-color: #007bff; color: white; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #0056b3; }
</style>
</head>
<body>
<?php
// Branch the process based on whether there is a POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// --- Display the confirmation screen ---
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
$email = htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8');
?>
<h1>Confirm Your Entry</h1>
<p>If the following content is correct, please press the submit button.</p>
<table class="confirmation-table">
<tr>
<th>Name</th>
<td><?php echo $name; ?></td>
</tr>
<tr>
<th>Email Address</th>
<td><?php echo $email; ?></td>
</tr>
<tr>
<th>Message</th>
<td><?php echo nl2br($message); ?></td>
</tr>
</table>
<p>*Note: This sample does not perform actual email submission.</p>
<?php } else { ?>
// --- Display the input form ---
<h1>Contact Us</h1>
<form action="" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
</div>
<button type="submit">Confirm Input</button>
</form>
<?php } ?>
</body>
</html>
The key point of this code is the conditional branch `if ($_SERVER['REQUEST_METHOD'] === 'POST')`. The `$_SERVER['REQUEST_METHOD']` holds how the page was accessed (GET or POST).
- When you first open the page: It's a normal access, so it's `GET`. The `if` statement is `false`, and the input form inside the `else` block is displayed.
- When you submit the form: It is sent with `method="POST"`, so the `if` statement is `true`, and the confirmation screen is displayed.
Also, by leaving the form's `action` attribute empty like `action=""`, the data is submitted to the file itself. This allows you to represent two screens with one file.
3. Points to Be Careful About (Input Validation)
On a real website, it's possible for users to not enter anything or to send malicious data. Therefore, a process called **validation**, which checks if the received data is as expected, is essential.
Here, let's add simple validation to check that each item is not empty.
<?php
// Processing on the confirmation screen side (inside the if statement)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$errors = []; // Array to store error messages
// Name validation
if (empty($name)) {
$errors[] = 'Name is required.';
}
// Email address validation
if (empty($email)) {
$errors[] = 'Email address is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'The email address format is incorrect.';
}
// Message validation
if (empty($message)) {
$errors[] = 'Message is required.';
}
// Branch the process based on whether there are errors
if (!empty($errors)) {
// If there are errors: display error messages
echo '<h1>Input Error</h1>';
echo '<ul style="color: red;">';
foreach ($errors as $error) {
echo '<li>' . htmlspecialchars($error) . '</li>';
}
echo '</ul>';
echo '<a href="javascript:history.back();">Return to form</a>';
} else {
// If there are no errors: display the confirmation screen
// ... (confirmation screen display code from the previous example) ...
}
}
?>
In this example, we use `empty()` to check if each input is not empty, and the convenient `filter_var()` function to validate that the email address format is correct. This creates a more practical flow where error messages are displayed if there are errors, and the user proceeds to the confirmation screen if not.
4. Summary and Next Steps
In this article, we learned the basic mechanism of web forms and the entire process from receiving data with PHP to displaying a confirmation screen. The `$_POST` variable and branching the process with an `if` statement are the core parts of creating a form. Sending an email involves server settings and is a bit more complex, but if you master this flow from input to confirmation, you can apply it to any form.
As for the next steps, they include:
- Processing to actually send an email using PHP's `mb_send_mail()` function when the "Send" button is pressed on the confirmation screen.
- More advanced validation (character limits, allowing only specific character types, etc.).
- Redirecting to a "Thank You page" after submission is complete.
We will cover these in detail on another occasion. For now, try creating your own original form based on this code!