Forms and User Input in PHP
Handling forms and user input is a crucial part of web development. PHP provides tools to process form data, validate input, and ensure security.
Handling Form Data
To handle form data, you need to access the data sent by the user through the form. This data is available in PHP’s global $_GET
and $_POST
arrays, depending on the method used in the form.
- Accessing Form Data:
// Example form data access
$name = $_POST['name']; // For POST method
$email = $_GET['email']; // For GET method
GET and POST Methods
Forms can use either the GET
or POST
method to send data to the server.
-
GET Method:
- Data is appended to the URL as query parameters.
- Suitable for non-sensitive data or data that does not affect server state.
- Form Example:
<form method="get" action="process.php"> <input type="text" name="search" /> <input type="submit" /> </form>
-
POST Method:
- Data is sent in the body of the request, not visible in the URL.
- Suitable for sensitive data or large amounts of data.
- Form Example:
<form method="post" action="process.php"> <input type="text" name="name" /> <input type="submit" /> </form>
Form Validation
Validating form input is essential to ensure that data meets specific criteria before processing.
- Server-Side Validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
if (empty($name)) {
echo "Name is required.";
} elseif (!preg_match("/^[a-zA-Z-' ]*$/", $name)) {
echo "Only letters and white space allowed.";
}
}
- Client-Side Validation: Use HTML5 attributes to provide immediate feedback to users.
<form method="post" action="process.php">
<input type="text" name="name" required pattern="[a-zA-Z\s]+" />
<input type="submit" />
</form>
Sanitizing and Escaping Input
Sanitizing and escaping input data are crucial for preventing security issues such as SQL injection and XSS attacks.
-
Sanitizing Input:
- Remove or encode unwanted characters from user input.
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
-
Escaping Output:
- Convert special characters to HTML entities to prevent XSS.
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
-
Using Prepared Statements:
- For database queries, use prepared statements to avoid SQL injection.
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (:name)"); $stmt->execute(['name' => $name]);
Handling forms and user input effectively involves capturing, validating, and securing data to ensure a robust and secure application. By using proper methods and techniques, you can manage user interactions and maintain data integrity.