View Full Version : Image character encoding

10-05-2006, 03:11 AM
I've made a PHP script which, when a non-HTML page is requested, passes it through by setting the appropriate MIME type header and then uses readfile($file_to_pass); to send the file to the browser.

Unfortunately, this seems to have run into a strange issue. I'm trying to convert my whole database/site to UTF-8 for pleasant international consistency, but since changing the encoding of a few of the PHP files, images no longer display correctly.

http://andrewsteele.co.uk/shared/templates/andrewsteele.co.uk/leaf.jpg is an example.

The weird thing is that if you save the image, open it in a text editor of your choice and then re-save it in 8-bit encoding rather than the UTF-8 it seems to open in by default, the image then works perfectly.

I thought that character sets didn't affect images.

What's going on, and what can I do?!

Any advice appreciated. :)

10-05-2006, 11:12 AM
Can you show some code?

10-05-2006, 01:33 PM
It's probably because GD doesn't work with UTF8. PHP doesn't fully support UTF yet.

10-07-2006, 11:05 AM
Some code:

function scms_pass_file($file_to_pass)
//set $ext, the file extension (the substring of everything after the dot in the basename(), ie filename, part of the path), and make it ready for a MySQL query (just adds 'quotes')
$ext = scms_db_2db(substr(basename($file_to_pass), strrpos(basename($file_to_pass), '.')+1));
//find out the MIME type from the database
if(!$mime_type = scms_db_query("SELECT mime_type FROM scms_mimetypes WHERE ext=".$ext))
//if the query above fails, look for no extension - the default MIME type
{ $mime_type = scms_db_query("SELECT mime_type FROM scms_mimetypes WHERE ext=''"); }
//use them ($ext is the extension of your file)
//scms_db_query returns FALSE when no rows are selected, so the if can simply be if the output variable
if ($mime_type) header("Content-Type: ".$mime_type);
header("Content-Length: ".@filesize($file_to_pass));
header("Cache-Control: max-age=86400");
return TRUE;

//call the just-defined function to pass the file

I have also noticed (now that my browser cache has expired!) that the same problem happens with CSS files. For some reason the change of encoding inserts invalid characters into the CSS and means that some instructions do not parse correctly.