How can PHP code be improved for better security when handling file uploads?

When handling file uploads in PHP, it is essential to implement security measures to prevent malicious file uploads that could harm your server or compromise user data. One common security vulnerability is allowing users to upload executable files like PHP scripts, which could be used to execute arbitrary code on your server. To improve security, you can restrict the allowed file types, limit the file size, and store the uploaded files in a secure directory outside of the web root.

<?php
// Define allowed file types
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

// Define maximum file size (in bytes)
$maxSize = 1048576; // 1MB

// Define upload directory outside of web root
$uploadDir = '/var/www/uploads/';

// Check if file type and size are within limits
if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Move uploaded file to secure directory
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $_FILES['file']['name']);
    echo 'File uploaded successfully.';
} else {
    echo 'Invalid file type or size.';
}
?>