What security measures should be implemented to prevent malicious file uploads in PHP?

To prevent malicious file uploads in PHP, it is important to implement security measures such as validating file types, restricting file sizes, and storing uploaded files in a secure directory outside of the web root.

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}

// Restrict file size
$maxFileSize = 1048576; // 1 MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds the limit of 1MB.');
}

// Store uploaded file in a secure directory
$uploadDir = '/var/www/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.';
}