What steps should be taken to ensure the security of file uploads in PHP?

To ensure the security of file uploads in PHP, it is important to validate the file type, restrict file size, and store the 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. Allowed types are JPEG, PNG, GIF.');
}

// Restrict file size
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
    die('File size exceeds limit. Please upload a smaller file.');
}

// Store uploaded file in a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}