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

When handling file uploads using PHP, it is important to follow best practices to ensure security and prevent vulnerabilities such as file injection attacks. One key practice is to validate the file type and size before processing the upload. Additionally, it is recommended to store uploaded files outside of the web root directory to prevent direct access.

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png'];
$maxSize = 5242880; // 5MB

if (!in_array($_FILES['file']['type'], $allowedTypes) || $_FILES['file']['size'] > $maxSize) {
    die('Invalid file type or size.');
}

// Store uploaded file outside of web root directory
$uploadDir = '/path/to/upload/directory/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);

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