Unit V (Handling Forms)
Unit V (Handling Forms)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
$_POST["name"] → Retrieves the name field value.
$_POST["email"] → Retrieves the email field value.
$_SERVER["REQUEST_METHOD"] == "POST" → Ensures data is submitted via POST.
Using different Input Types
<form action="process.php" method="post">
Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
Gender:
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female <br>
Hobbies:
<input type="checkbox" name="hobby[]" value="Reading"> Reading
<input type="checkbox" name="hobby[]" value="Sports"> Sports <br>
Country:
<select name="country">
<option value="Nepal">Nepal</option>
<option value="India">India</option>
</select><br>
<input type="submit" value="Submit">
</form>
<input type="password"> → Hides characters for password fields.
<input type="radio"> → Allows one selection (e.g., gender).
<input type="checkbox"> → Allows multiple selections.
Retrieving form data
1. Retrieving Data Using $_GET
Used when the form method is GET.
Best for non-sensitive data.
Example:
<form action="process.php" method="get">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
echo "Hello, " . $_GET['name'];
?>
The URL will appear as:
example.com/process.php?name=John
2. Retrieving Data Using $_POST
Used when the form method is POST.
Suitable for forms with passwords, login, and large data.
<form action="process.php" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
echo "Hello, " . $_POST['name'];
?>
The URL remains clean without showing the data.
3. Retrieving Data Using $_REQUEST
Can retrieve data from both $_GET and $_POST.
Not recommended for security-sensitive applications.
<?php
if(isset($_REQUEST['name'])) {
echo "Hello, " . $_REQUEST['name'];
}
?>
Works with both GET and POST forms.
Processing forms in PHP
// Validating input
if (empty($name) || empty($email)) {
echo "All fields are required!";
} else {
// Sanitizing input
$name = htmlspecialchars($name);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
Syntax:
header("Header-Type: value");
Redirecting to another page:
header("Location: https://www.example.com");
exit(); // Stops script execution after redirection