What are best practices for handling user-generated content in PHP applications to prevent security risks?
User-generated content in PHP applications can pose security risks such as SQL injection, cross-site scripting (XSS), and file upload vulnerabilities. To prevent these risks, it is important to sanitize and validate user input, use prepared statements for database queries, escape output when displaying content, and restrict file types and sizes for uploads.
// Sanitize and validate user input
$userInput = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);
// Use prepared statements for database queries
$stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:user_input)");
$stmt->bindParam(':user_input', $userInput);
$stmt->execute();
// Escape output when displaying content
echo htmlspecialchars($userInput);
// Restrict file types and sizes for uploads
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 1048576; // 1MB
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}