Nov 24, 2010

Solving BOM of UTF-8 File Encoding problem with PHP session and header




UTF-8 is a popular File Encoding on the internet.
However, when we use UTF-8 with PHP using session and header there are some error occurs.


When we create an empty file, normally it is a 0-byte file.


And then, we save it as UTF-8 File Encoding.
Although we never type any text in it, the size of file will increase 3 bytes...
We call that 3 bytes as BOM (Byte Order Mark)




When we use session_start() or header().
PHP will send a error message like this:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent

So, how could we solve it ?



If you are using Windows OSs it is an easy task to solve it.
You can install Notepad++ which is a free, powerful text editor.
Open the file with Notepad++, then browse Format on the menu bar and select Convert to UTF-8 without BOM
(Sorry about the image. I am using Chinese Transitional of Windows XP Professional and Notepad++)

Solved ? No ! We cannot install Notepad++ using Linux, Unix or Mac OS.
How could we solve that problem ?




You should write an other PHP file to remove the BOM of the target file.
The converter (file) like this:
<?
$pathname = "./test.php"; // change the pathname to your target file(s) which you want to remove the BOM.
$file_handler = fopen($pathname, "r");
$contents = fread($file_handler, filesize($pathname));
fclose($file_handler);
for ($i = 0; $i < 3; $i++){
    $bytes[$i] = ord(substr($contents, $i, 1));
}
if ($bytes[0] == 0xef && $bytes[1] == 0xbb && $bytes[2] == 0xbf){
    $file_handler = fopen($pathname, "w");
    fwrite($file_handler, substr($contents, 3));
    fclose($file_handler);
    printf("%s BOM removed.<br/>\n", $pathname);
}
?>


Then run this file to remove the BOM.

You also can write a standalone program like Java or C++ (or any cross-platform language) to resolve this problem.


2 comments:

Prant said...

Bunch of thanks!!!
Was searching for such a best solution... :)

Mary Brown said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP Training in chennai | PHP Training Course

PHP Training in chennai | Online PHP Course

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code