PHP Form Handling Example
Let's go through a simple example of PHP form handling using both GET and POST methods. In this example, we'll create a basic form to collect user information (name and email) and display the submitted data on the server side.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Form Handling Example</title>
</head>
<body>
<h2>User Information Form</h2>
<!-- Form using the GET method -->
<form action="process_form.php" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit (GET)">
</form>
<hr>
<!-- Form using the POST method -->
<form action="process_form.php" method="post">
<label for="name_post">Name:</label>
<input type="text" id="name_post" name="name_post" required>
<label for="email_post">Email:</label>
<input type="email" id="email_post" name="email_post" required>
<input type="submit" value="Submit (POST)">
</form>
</body>
</html>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Handle form submission using the GET method
$name = isset($_GET['name']) ? $_GET['name'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
// Display the submitted data
echo "<h3>Submitted Data (GET)</h3>";
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle form submission using the POST method
$name_post = isset($_POST['name_post']) ? $_POST['name_post'] : '';
$email_post = isset($_POST['email_post']) ? $_POST['email_post'] : '';
// Display the submitted data
echo "<h3>Submitted Data (POST)</h3>";
echo "Name: " . htmlspecialchars($name_post) . "<br>";
echo "Email: " . htmlspecialchars($email_post);
} else {
// Invalid request method
echo "Invalid request method.";
}
?>
In this example:
form_example.html
) contains two forms, one using the GET method and another using the POST method.process_form.php
) checks the request method and retrieves the form data accordingly using $_GET
or $_POST
.echo
.
To test this example, save the HTML code in a file named form_example.html
and the PHP code in a file named process_form.php
. Open the form_example.html
file in your web browser and submit the forms to see the data displayed on the server side based on the chosen form submission method (GET or POST).
Thank you.