PHP, Programming

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

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.

Solving BOM of UTF-8 File Encoding problem with PHP session and header
When we create an empty file, normally it is a 0-byte file.

Solving BOM of UTF-8 File Encoding problem with PHP session and header
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)

Solving BOM of UTF-8 File Encoding problem with PHP session and header
Solving BOM of UTF-8 File Encoding problem with PHP session and header
Solving BOM of UTF-8 File Encoding problem with PHP session and header
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 ?

Solving BOM of UTF-8 File Encoding problem with PHP session and header
Solving BOM of UTF-8 File Encoding problem with PHP session and header
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 ?

Solving BOM of UTF-8 File Encoding problem with PHP session and header
Solving BOM of UTF-8 File Encoding problem with PHP session and header
Solving BOM of UTF-8 File Encoding problem with PHP session and header
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.