What best practices should be followed when handling file uploads in PHP?

When handling file uploads in PHP, it is important to follow best practices to ensure the security and integrity of the uploaded files. One key practice is to validate the file type and size to prevent malicious files from being uploaded. Additionally, store the uploaded files in a secure directory outside of the web root to prevent direct access. Finally, consider renaming the uploaded files to prevent overwriting existing files.

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 2 * 1024 * 1024; // 2MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Store uploaded file in a secure directory
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo 'File uploaded successfully.';
    } else {
        echo 'Error uploading file.';
    }
} else {
    echo 'Invalid file type or size.';
}