What are the best practices for handling file uploads in PHP to prevent security vulnerabilities?

When handling file uploads in PHP, it is crucial to implement security measures to prevent vulnerabilities such as file injection and execution. One common best practice is to validate file types and extensions to ensure that only allowed file types are uploaded. Additionally, storing uploaded files in a secure directory outside of the web root and renaming them to prevent malicious execution are important steps to enhance security.

// Example of handling file uploads in PHP with security measures

// Define allowed file types
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

// Get uploaded file information
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Check if file type is allowed
if (!in_array($fileType, $allowedTypes)) {
    die('Error: Invalid file type.');
}

// Move uploaded file to secure directory
$uploadPath = 'uploads/' . uniqid() . '.' . $fileType;
if (move_uploaded_file($fileTmpName, $uploadPath)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}