What best practices can PHP developers follow to ensure secure file uploads and prevent malicious uploads?

To ensure secure file uploads and prevent malicious uploads, PHP developers can follow best practices such as validating file types, restricting file sizes, storing files outside the web root directory, and using unique file names. By implementing these measures, developers can mitigate the risk of malicious file uploads compromising their application's security.

// 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 = 1000000; // 1MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds limit. Maximum file size allowed is 1MB.');
}

// Store file outside web root directory
$uploadPath = '/var/www/uploads/' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);

// Use unique file names
$uniqueFileName = uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath . $uniqueFileName);