Are there best practices for handling file uploads in PHP to ensure security and prevent vulnerabilities?

When handling file uploads in PHP, it is crucial to implement security measures to prevent vulnerabilities such as file injection or execution. One best practice is to validate file types and sizes before processing them. Additionally, storing uploaded files outside of the web root directory can prevent direct access to them by users.

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

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/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);

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