When dealing with file uploads in PHP, what security considerations should be taken into account to prevent potential vulnerabilities?

When dealing with file uploads in PHP, it is crucial to validate file types, limit file size, and store uploaded files in a secure location outside of the web root directory to prevent potential vulnerabilities such as file inclusion attacks or malicious file execution.

// Validate file type
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_extensions)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

// Limit file size
$max_file_size = 5 * 1024 * 1024; // 5 MB
if ($_FILES['file']['size'] > $max_file_size) {
    die('File size exceeds the limit of 5 MB.');
}

// Store uploaded file in a secure location
$upload_dir = '/path/to/secure/directory/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
    echo 'File uploaded successfully.';
} else {
    die('Failed to upload file.');
}