Forms allow users to input data on a website. PHP can be used to handle form submissions, validate data, and display results.
To create a form in HTML, use the <form>
tag:
<form action="process.php" method="post">
Name: <input type="text" name="name">
Email: <input type="email" name="email">
</form>
When the form is submitted, PHP can access the data using the $_POST
superglobal:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
echo "Hello, $name! Your email is $email.";
}
?>
To validate form data, you can check if the inputs are empty:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['name']) || empty($_POST['email'])) {
echo "Name and email are required.";
} else {
echo "Form submitted successfully.";
}
}
?>
Create a form that collects the user's name, email, and message. Display the submitted data on a new page.