Skip to content
PHP Logo

How can file type validation be improved in PHP applications to prevent errors when uploading files like SVG images?

When validating file types in PHP applications, it's important to not solely rely on the file extension as it can be easily manipulated. Instead, use mime type validation to ensure that the file content matches the expected type. This can help prevent errors when uploading files like SVG images.

php
// Get the mime type of the uploaded file
$mime = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $_FILES['file']['tmp_name']);

// Validate if the file is an SVG image
if ($mime === 'image/svg+xml') {
    // Process the uploaded SVG file
} else {
    // Handle error - file is not an SVG image
}