Php

Working with Forms

Working with Forms in PHP

Forms are how users send data to your server (e.g., login, registration, search). PHP helps process this data.


Step 1: Create an HTML Form

html
<form method="POST" action="process.php">
Name: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
  • method="POST" sends data securely.

  • action="process.php" tells the form where to send the data.


Step 2: Handle Form Data in PHP (process.php)

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];

echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email);
}
?>

  • $_POST gets form data.

  • htmlspecialchars() prevents XSS (cross-site scripting).

  • You can also use $_GET for method="GET" forms.


✅ Validating Form Data (Basic)

php
if (empty($name) || empty($email)) {
echo "All fields are required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format.";
} else {
echo "Form submitted successfully!";
}

Security Tips

Practice Why it’s Important
htmlspecialchars() Prevents script injection
filter_var() Validates & sanitizes user input
$_SERVER["REQUEST_METHOD"] Confirms the request type is correct
Use POST over GET For sensitive data

Example: Complete Form Handler

HTML (form.html):

html
<form method="POST" action="handle.php">
<input type="text" name="name" placeholder="Your Name">
<input type="submit" value="Send">
</form>

PHP (handle.php):

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST["name"]);

if (empty($name)) {
echo "Please enter your name.";
} else {
echo "Hello, " . htmlspecialchars($name) . "!";
}
}
?>


Superglobals for Form Data

Variable Purpose
$_POST Data from POST forms
$_GET Data from URL (GET method)
$_REQUEST Both POST and GET
$_SERVER Info about headers, paths, script, etc.

Leave a Reply

Your email address will not be published. Required fields are marked *