What are the best practices for securely handling user-generated content in PHP applications?

User-generated content in PHP applications can pose security risks if not handled properly. To securely handle user-generated content, it's important to validate and sanitize input data to prevent SQL injection, cross-site scripting (XSS), and other vulnerabilities. Additionally, storing uploaded files in a secure directory and restricting file types can help prevent malicious code execution.

// Validate and sanitize user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);

// Store uploaded files in a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
$allowedExtensions = ['jpg', 'png', 'gif'];
$extension = pathinfo($uploadFile, PATHINFO_EXTENSION);

if (in_array($extension, $allowedExtensions)) {
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
} else {
    echo 'Invalid file format';
}