How can PHP functions like ref.mime-magic and ref.fileinfo help in ensuring file security?

PHP functions like ref.mime-magic and ref.fileinfo can help in ensuring file security by allowing us to determine the actual file type of an uploaded file. This can prevent malicious users from disguising harmful files as harmless ones. By checking the file type before processing or executing it, we can mitigate the risk of security vulnerabilities.

// Using ref.mime-magic to check the file type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $_FILES['file']['tmp_name']);

if ($mime_type == 'image/jpeg' || $mime_type == 'image/png') {
    // Process the file
} else {
    // Handle invalid file type
}

finfo_close($finfo);