Principle:
UTF8 file, Microsoft to add a recognition information, with the BOM this thing: Bom--byte order mark, the default on Windows and other platforms edited UTF8 file will add 3 bytes of markup information on the head, Our PHP engine in the process of processing will read the entire PHP code document, if the php file header contains BOM information, will output a blank, in many cases will bring problems, such as our session can not work, cookies can not set up and so on.
Workaround:
Identify the 3-byte information of the header BOM and remove it. But generally we do not know which file has a BOM, or there are a lot of files, this time, you need to bulk processing, the following code is mainly to show the situation of batch processing, should be helpful to everyone in the work.
How to execute:
Set a path, and then execute directly on the line.
Copy Code code as follows:
<?php
Set the root directory where you want to clear the BOM (automatically scans all subdirectories and files)
$HOME = DirName (__file__);
If it is a Windows system, modify to: $WIN = 1;
$WIN = 0;
?>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>utf8 BOM Cleaner </title>
<style>
body {font-size:10px; font-family:arial, Helvetica, Sans-serif; background: #FFF; color: #000;}
. FOUND {color: #F30; font-size:14px; font-weight:bold;}
</style>
<body>
<?php
$BOMBED = Array ();
Recursivefolder ($HOME);
Echo ' foreach ($BOMBED as $utf) {echo $utf. " <br/>\n "; }
Echo ' </p> ';
Recursive scan
function Recursivefolder ($sHOME) {
Global $BOMBED, $WIN;
$win = ($WIN = = 1)? "\\" : "/";
$folder = Dir ($sHOME);
$foundfolders = Array ();
while ($file = $folder->read ()) {
if ($file!= "." and $file!= "...") {
if (filetype ($sHOME. $win $file) = = "Dir") {
$foundfolders [Count ($foundfolders)] = $sHOME. $win 32. $file;
} else {
$content = file_get_contents ($sHOME. $win $file);
$BOM = Searchbom ($content);
if ($BOM) {
$BOMBED [Count ($BOMBED)] = $sHOME. $win 32. $file;
To remove the BOM information
$content = substr ($content, 3);
Write back to original file
File_put_contents ($sHOME. $win $file, $content);
}
}
}
}
$folder->close ();
if (count ($foundfolders) > 0) {
foreach ($foundfolders as $folder) {
Recursivefolder ($folder, $win 32);
}
}
}
Search the current file for a BOM
function Searchbom ($string) {
if (substr ($string, 0,3) = = Pack ("CCC", 0XEF,0XBB,0XBF)) return true;
return false;
}
?>
</body>