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
-
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)
-
$_POSTgets form data. -
htmlspecialchars()prevents XSS (cross-site scripting). -
You can also use
$_GETformethod="GET"forms.
✅ Validating Form Data (Basic)
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):
PHP (handle.php):
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. |
