If the header of the PHP file contains BOM information, a blank space will be output, which may cause problems in many cases, such as the inability to set the session or cookie, etc.
Principle:
UTF8 file. to add recognition information, Microsoft has the BOM: BOM -- Byte Order Mark, by default, the UTF-8 file Edited on Windows and other platforms will add 3 bytes of tag information to the header. during processing, the PHP engine will read the entire PHP code document, if the header of the PHP file contains BOM information, a blank space will be output, which may cause problems in many cases, such as the inability to set the session or cookie.
Solution:
Identify the three bytes of the header BOM and remove it. However, we generally do not know which file has a BOM or many files. in this case, batch processing is required. the following code mainly shows the batch processing status, it should be helpful to everyone's work.
Execution method:
Set a path and execute it directly.
The code is as follows:
// Set the root directory of the BOM to be cleared (all subdirectories and files are automatically scanned)
$ HOME = dirname (_ FILE __);
// If it is a Windows system, change it to: $ WIN = 1;
$ WIN = 0;
?>
UTF8 BOM cleaner
$ BOMBED = array ();
RecursiveFolder ($ HOME );
Echo 'These files had UTF8 BOM, but I cleaned them:
';
Foreach ($ BOMBED as $ utf) {echo $ utf ."
\ N ";}
Echo'
';
// Recursive scan
Function RecursiveFolder ($ sHOME ){
Global $ BOMBED, $ WIN;
$ Win32 = ($ WIN = 1 )? "\\":"/";
$ Folder = dir ($ sHOME );
$ Foundfolders = array ();
While ($ file = $ folder-> read ()){
If ($ file! = "." And $ file! = ".."){
If (filetype ($ sHOME. $ win32. $ file) = "dir "){
$ Foundfolders [count ($ foundfolders)] = $ sHOME. $ win32. $ file;
} Else {
$ Content = file_get_contents ($ sHOME. $ win32. $ file );
$ BOM = SearchBOM ($ content );
If ($ BOM ){
$ BOMBED [count ($ BOMBED)] = $ sHOME. $ win32. $ file;
// Remove BOM information
$ Content = substr ($ content, 3 );
// Write back to the original file
File_put_contents ($ sHOME. $ win32. $ file, $ content );
}
}
}
}
$ Folder-> close ();
If (count ($ foundfolders)> 0 ){
Foreach ($ foundfolders as $ folder ){
RecursiveFolder ($ folder, $ win32 );
}
}
}
// Search for BOM in the current file
Function SearchBOM ($ string ){
If (substr ($ string, 0, 3) = pack ("CCC", 0xef, 0xbb, 0xbf) return true;
Return false;
}
?>