How to Handle Forms with PHP (GET and POST Methods Explained)
When building dynamic websites using PHP, you need to get and process the user input data. Here comes the forms, and using PHP, it's easy to handle form data using the GET and POST methods.
GET Method
The GET method sends the form's data using the URL:
<form action="contacts.php" method="get">
<label for="name">Name:</label>
<input type="text" name="name" required>
<label for="email">Email:</label>
<input type="email" name="email" required>
<input type="submit" value="Send">
</form>
POST Method
The POST method sends the form's data in the background:
<form action="contacts.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" required>
<label for="email">Email:</label>
<input type="email" name="email" required>
<input type="submit" value="Send">
</form>
Handle Form Data with PHP Using Post
Create a file named contacts.php to receive the data from the form using the POST method:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
Handle Form Data with PHP Using Get
Change the method in your form to GET:
<?php
if (isset($_GET['name']) && isset($_GET['email'])) {
$name = $_GET['name'];
$email = $_GET['email'];
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>