Search code examples
phphttp-headerssubstr

Set the header( content-type: image/<ANY IMG FORMAT>)


The php file that handles the images I display only allows one image format, either .jpg, .png, .bmp, etc but not all. The imageName stores the file name of the image stored in the database including its format. this is my code, so far it doesn't work yet and I'm not sure if that's allowed. Can you help me fix it please?

$con = mysqli_connect("localhost","root","","tickets");
$ticket = 109;
$result = mysqli_query($con,"SELECT image, imageName FROM tix WHERE tktNum=$ticket");


while($row = mysqli_fetch_array($result))
{
    $image = $row['image'];
    $imageName = $row['imageName'];
    $format = substr( $imageName, -3 ); //gets the last 3 chars of the file name, ex: "photo1.png" gets the ".png" part
    header('content-type: image/' . $format);
}

Solution

  • The solution is to read in the file and decide which kind of image it is and basednd on it send out the appropriate header.

    $filename = basename($file);
    $file_extension = strtolower(substr(strrchr($filename,"."),1));
    
    switch( $file_extension ) {
        case "gif": $ctype="image/gif"; break;
        case "png": $ctype="image/png"; break;
        case "jpeg":
        case "jpg": $ctype="image/jpeg"; break;
        case "svg": $ctype="image/svg+xml"; break;
        default:
    }
    
    header('Content-type: ' . $ctype);