Explain PHP Form Introduction
PHP forms are a way to collect user input and process it on the server. They are often used for tasks such as user registration, login, and data submission. Here’s a basic introduction to PHP forms, including examples and outputs.
1. HTML Form
First, you need an HTML form to collect user input. Here’s a simple example:
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Example</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="process.php" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Message:<br>
<textarea name="message" rows="4" cols="50" required></textarea><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In this form:
action="process.php"
specifies the PHP file that will process the form data.method="post"
indicates that form data will be sent via the HTTP POST method.
2. PHP Processing Script (process.php
)
Here’s a PHP script to handle the form submission:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect and sanitize form data
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Display collected data
echo "<h1>Form Submitted Successfully</h1>";
echo "<p><strong>Name:</strong> " . $name . "</p>";
echo "<p><strong>Email:</strong> " . $email . "</p>";
echo "<p><strong>Message:</strong> " . nl2br($message) . "</p>";
}
?>
How It Works
-
Form Submission: When the user fills out the form and clicks "Submit," the browser sends a POST request to
process.php
with the form data. -
PHP Processing:
process.php
checks if the request method is POST (to ensure the form was submitted). It then retrieves and sanitizes the input data usinghtmlspecialchars()
to prevent XSS (Cross-Site Scripting) attacks. -
Output Display: The sanitized data is displayed on the webpage.
Example Output
After submitting the form with the following inputs:
- Name: John Doe
- Email: john@example.com
- Message: Hello, I’d like to know more about your services.
The output might look like this:
<h1>Form Submitted Successfully</h1>
<p><strong>Name:</strong> John Doe</p>
<p><strong>Email:</strong> john@example.com</p>
<p><strong>Message:</strong> Hello, I’d like to know more about your services.</p>
This simple example demonstrates the basics of creating and processing a PHP form. For more advanced features, such as form validation and handling file uploads, you would need to add additional PHP logic.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.