The Missing Link Between Filename and Content-Type
The core issue in your current implementation stems from a fundamental misunderstanding of how HTTP headers interact with file formats. You are extracting the file extension from the filename string stored in your database and blindly appending it to the Content-Type header. While this logic holds for standard extensions like .jpg, .png, or .gif, it fails immediately when dealing with newer or less common formats, most notably WebP or AVIF.
When you execute $format = substr($imageName, -3), you are assuming that every image file extension is exactly three characters long and that the header mapping is static based on that string. If a user uploads a .webp image, your script sets Content-Type: image/webp. However, if the server configuration or your specific PHP setup doesn't recognize this new mime type without explicit registration, or if the client (browser) expects a different signature, the browser will refuse to display the image. More critically, relying on the filename extension for security is a known vulnerability vector. If your database contains corrupted entries where imageName says .jpg but the binary data is actually executable PHP code, blindly setting the header based on that string could lead to severe vulnerabilities if your server allows it.
The robust solution requires decoupling the file format detection from the filename string and instead inspecting the actual binary content of the image. This is known as "Magic Bytes" or "File Signature" detection. Every valid image file starts with a unique sequence of bytes that acts as a fingerprint. For example, JPEG files always start with FF D8 FF, PNG files begin with 89 50 4E 47 0D 0A 1A 0A, and WebP files start with FF FF.
To fix your code, you should stop parsing the $imageName string for the header and instead use PHP's built-in detection capabilities or a dedicated library. The most reliable approach without external dependencies is to check the first few bytes of the image data returned by your query. However, since you are using mysqli_fetch_array, the image data arrives as a binary string. You can determine the correct MIME type before sending the header by checking these signatures.
Here is a corrected approach that inspects the content rather than the name:
<?php
$con = mysqli_connect("localhost", "root", "", "tickets");
$ticket = 109;
// Use prepared statements to prevent SQL injection on $ticket
$stmt = $con->prepare("SELECT image, imageName FROM tix WHERE tktNum=?");
$stmt->bind_param("i", $ticket);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$imageData = $row['image'];
if (empty($imageData)) {
echo "No image found for ticket #{$ticket}.";
continue;
}
// Determine MIME type based on the first few bytes (Magic Numbers)
// We assume the data is binary. In a real app, ensure $imageData is not truncated.
$length = strlen($imageData);
if ($length < 6) {
continue;
}
$headerHex = bin2hex(substr($imageData, 0, 8));
// Define mappings for common image signatures
$mimeMap = [
'ffd8ff' => 'image/jpeg',
'89504e47' => 'image/png',
'3c3f786d6c' => 'image/svg+xml', // SVG starts with <?xml
'47494638' => 'image/gif', // GIF usually starts with 47 49 46 (GIF)
'ffd8ff' => 'image/jpeg', // WebP often shares JPEG header but needs specific check or lib
];
// For WebP and other modern formats, simple hex checks can be tricky.
// A more robust method involves using the ImageMagick library or fileinfo extension.
// Recommended: Use finfo_file if you have a temporary path,
// OR use getimagesize which validates the binary structure strictly.
if (function_exists('getimagesize')) {
$size = @getimagesizefromstring($imageData);
if ($size && isset($size['mime'])) {
header('Content-Type: ' . $size['mime']);
// Ensure headers are sent only once
if (!headers_sent()) {
echo "<img src='data:$size['mime'];base64," . base64_encode($imageData) . "' alt='Ticket Image'>";
}
} else {
die("Invalid image format detected for ticket #{$ticket}.");
}
} else {
// Fallback logic if getimagesize is unavailable, though strongly discouraged
echo "Image format not supported by current PHP configuration.";
}
}
$stmt->close();
$con->close();
?>
The key here is getimagesizefromstring(). This function attempts to parse the binary stream. If it succeeds, it returns an array containing the MIME type that matches the actual data, regardless of what the filename claims to be. If the binary data is corrupted or not a valid image, it returns false, allowing you to handle the error gracefully instead of serving a broken image or executing dangerous code.
Relying on substr($imageName, -3) is fragile because it assumes the file system naming convention matches reality and that all extensions are uniform in length (ignoring .webp which is 4 chars). By validating the MIME type against the binary signature, you ensure that the browser renders exactly what was uploaded, maintaining security and compatibility across modern formats like WebP and AVIF.