Skip to content

PHP Form Handling

PHP Form Handling: Securely Processing User Input

Section titled “PHP Form Handling: Securely Processing User Input”

HTML forms are the primary way users interact with web applications. PHP provides mechanisms to receive and process data submitted through these forms using the superglobal arrays $_GET and $_POST.

Security is paramount when handling form data. Never trust user input directly. Always validate and sanitize data on the server-side before using it.

This example shows a basic HTML form with fields for name and email, submitting data using the POST method.

File: user_form.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Form</title>
</head>
<body>
<h2>User Information Form</h2>
<form action="welcome.php" method="post">
<div>
<label for="name">Name:</label><br>
<input type="text" id="name" name="user_name" required>
</div>
<br>
<div>
<label for="email">E-mail:</label><br>
<input type="email" id="email" name="user_email" required>
</div>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>

When the user fills this form and clicks “Submit”, the browser sends the data (user_name and user_email) via an HTTP POST request to the welcome.php script specified in the action attribute.

The PHP script receives the submitted data in the $_POST superglobal array. It’s crucial to validate and sanitize this data.

File: welcome.php (Handling POST request)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
<?php
declare(strict_types=1);
// Check if the form was submitted using POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// --- Data Retrieval and Basic Validation ---
// Use filter_input for safer access and basic sanitization/validation
// FILTER_SANITIZE_SPECIAL_CHARS is a good default for data intended for HTML output
$name = filter_input(INPUT_POST, 'user_name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'user_email', FILTER_VALIDATE_EMAIL);
// Trim whitespace
$name = trim($name ?? '');
$errors = [];
// --- More Specific Validation ---
if (empty($name)) {
$errors[] = "Name is required.";
}
// You might add more name validation (e.g., length, characters allowed)
if ($email === false) {
$errors[] = "A valid email address is required.";
} elseif ($email === null || $email === '') {
// filter_input returns null if var not set, false if filter fails
// We check for empty string too just in case
$errors[] = "Email address is required.";
}
// --- Process Data or Display Errors ---
if (empty($errors)) {
// Data is considered valid for this example
// IMPORTANT: Sanitize again specifically for the context where data is used!
// Using htmlspecialchars here ensures safe display in HTML.
echo "<p>Welcome, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "!</p>";
// It's usually safe to display a validated email directly, but htmlspecialchars adds an extra layer.
echo "<p>Your email address is: " . htmlspecialchars($email, ENT_QUOTES, 'UTF-8') . "</p>";
// --- Further Processing ---
// Now you could safely:
// - Store the data in a database (using prepared statements!)
// - Send an email
// - etc.
} else {
// Display errors
echo "<h2>Please correct the following errors:</h2>";
echo "<ul>";
foreach ($errors as $error) {
echo "<li>" . htmlspecialchars($error, ENT_QUOTES, 'UTF-8') . "</li>";
}
echo "</ul>";
// Optionally, redirect back to the form with error messages
}
} else {
// Handle cases where the script is accessed directly without POST data
echo "<p>Form submission method not recognized.</p>";
// Redirecting back to the form is often a good user experience
// header('Location: user_form.html');
// exit;
}
?>
</body>
</html>

Key Security Steps Shown:

  • Check Request Method: Ensure the script processes data only when submitted via the expected method (POST).
  • Use filter_input(): Retrieve input variables safely. It provides basic filtering/validation options.
  • Validate: Check if required fields are present (empty()) and if data conforms to expected formats (FILTER_VALIDATE_EMAIL). Add more specific validation as needed (length, allowed characters, etc.).
  • Sanitize for Output: Use htmlspecialchars() when echoing user-provided data back into HTML to prevent Cross-Site Scripting (XSS) attacks.
  • Handle Errors: Inform the user clearly about validation errors.

If the form method was get, the data would be appended to the URL as query parameters (e.g., welcome_get.php?user_name=John&user_email=john%40example.com). In PHP, this data would be accessible via the $_GET superglobal array.

HTML using GET:

<form action="welcome_get.php" method="get">
<!-- input fields -->
</form>

PHP processing GET (welcome_get.php):

<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = filter_input(INPUT_GET, 'user_name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_GET, 'user_email', FILTER_VALIDATE_EMAIL);
// ... rest of validation and processing similar to POST example ...
if (!empty($name)) { // Basic check
echo "Welcome (from GET), " . htmlspecialchars($name ?? '', ENT_QUOTES, 'UTF-8') . "!";
}
}
?>

Both methods send data as key-value pairs, accessible in PHP via $_GET and $_POST (and combined in $_REQUEST, though using $_GET/$_POST explicitly is clearer).

  • $_GET: Data is sent in the URL’s query string. Visible to users, logged by servers, limited in length (around 2000 characters typically), can be bookmarked.
  • $_POST: Data is sent in the HTTP request body. Not visible in the URL, no practical length limit, cannot be directly bookmarked.
  • For non-sensitive data retrieval (e.g., search queries, page numbers).
  • When you want the result page to be bookmarkable/shareable with parameters.
  • For idempotent requests (requests that don’t change server state; multiple identical GET requests should have the same effect as one).

Never use GET for submitting passwords, sensitive data, or actions that modify data on the server.

  • For submitting sensitive data (passwords, personal information).
  • For actions that change server state (creating users, submitting orders, deleting data).
  • When submitting large amounts of data.
  • When uploading files.
  • Cross-Site Request Forgery (CSRF): Protect forms that perform actions using CSRF tokens.
  • File Uploads: Handle file uploads with extreme care (check file type, size, scan for malware, store securely).
  • Rate Limiting: Prevent brute-force attacks on login or submission forms.
  • Input Validation: Be strict with validation. Only allow expected characters and formats.
  • HTTPS: Always use HTTPS to encrypt data transmission between the browser and server.

Mastering secure form handling is crucial for building robust and safe PHP applications.