What are the limitations of using file extensions as the sole method of verifying file types in PHP?

File extensions can be easily manipulated or changed, leading to potential security vulnerabilities if they are relied upon as the sole method of verifying file types in PHP. To mitigate this risk, it is recommended to use file validation libraries or functions that can inspect the actual file contents to determine its type.

// Example of using the Fileinfo extension to validate file types based on file contents

// Create a new Fileinfo object
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);

// Get the MIME type of a file
$mime = finfo_file($fileInfo, $file_path);

// Check if the MIME type is allowed
if ($mime == 'image/jpeg' || $mime == 'image/png') {
    // File type is allowed
    echo 'File type is allowed';
} else {
    // File type is not allowed
    echo 'File type is not allowed';
}

// Close the Fileinfo object
finfo_close($fileInfo);