How can PHP developers ensure that their file upload functionality is robust and secure?

To ensure that file upload functionality in PHP is robust and secure, developers should validate file types, restrict file sizes, store files in a secure location outside of the web root directory, and sanitize file names to prevent directory traversal attacks.

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type.');
}

// Restrict file size
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
    die('File size is too large.');
}

// Store file in a secure location
$uploadDir = '/var/www/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);

// Sanitize file name
$cleanFileName = preg_replace("/[^a-zA-Z0-9.]+/", "", $_FILES['file']['name']);