Skip to content
PHP Logo

Are there any specific PHP functions or libraries recommended for validating file types, such as PDFs?

When validating file types, such as PDFs, in PHP, it's important to use a reliable method to ensure that the file is indeed in the expected format. One recommended approach is to use the `finfo` function, which is part of the Fileinfo extension in PHP. This function can be used to determine the MIME type of a file, allowing you to verify that it is a PDF before processing it further.

php
// Validate file type using finfo
$filePath = 'path/to/your/file.pdf';
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $filePath);
finfo_close($finfo);

if ($mimeType === 'application/pdf') {
    // File is a PDF, proceed with processing
    // Your code here
} else {
    // File is not a PDF, handle the error accordingly
    echo 'Invalid file type';
}