What are the best practices for handling form data, especially file uploads, in PHP to ensure both security and functionality?

When handling form data, especially file uploads, in PHP, it is crucial to validate and sanitize user input to prevent security vulnerabilities such as SQL injection and file upload attacks. One common best practice is to use PHP's built-in functions like filter_input() and filter_var() to validate input data. Additionally, when handling file uploads, always store uploaded files in a secure directory outside of the web root and use functions like move_uploaded_file() to move the files to the desired location.

// Example code snippet for handling file uploads securely in PHP

// Validate and sanitize input data
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$uploadedFile = $_FILES['file'];

// Check if file was uploaded successfully
if ($uploadedFile['error'] === UPLOAD_ERR_OK) {
    // Specify the directory to store uploaded files
    $uploadDir = '/path/to/secure/directory/';
    
    // Generate a unique filename to prevent overwriting existing files
    $fileName = uniqid() . '_' . basename($uploadedFile['name']);
    
    // Move the uploaded file to the secure directory
    if (move_uploaded_file($uploadedFile['tmp_name'], $uploadDir . $fileName)) {
        echo 'File uploaded successfully!';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Error uploading file: ' . $uploadedFile['error'];
}