如何使用PHP批量去除文件UTF8 BOM信息

若是PHP文件頭部包含BOM信息,就會輸出一個空白,在不少時候會帶來問題,好比咱們session沒法工做、cookie沒法設置等等問題php

原理:html

UTF8文件,微軟爲了增長一個識別信息,有了BOM這個東西:BOM —— Byte Order Mark,缺省在Windows等平臺上編輯的UTF8文件會在頭部增長3個字節的標記信息,咱們PHP引擎在處理的時候會完整讀取整個PHP代碼文檔, 若是PHP文件頭部包含BOM信息,就會輸出一個空白,在不少時候會帶來問題,好比咱們session沒法工做、cookie沒法設置等等問題。cookie


解決方法:session

把頭部BOM的3個字節信息識別出來,而後剔除掉。不過通常狀況咱們不知道哪一個文件有BOM,或者是有不少文件,這個時候,就須要進行批量處理了,下面代碼主要就是展示了批量處理的狀況,應該會對你們工做中有幫助。ui


執行方法:xml

設置一個路徑,而後直接執行就行。htm



<?php 遞歸

// 設定你要清除BOM的根目錄(會自動掃描全部子目錄和文件)utf-8

$HOME = dirname(__FILE__);文檔

// 若是是Windows系統,修改成:$WIN = 1;

$WIN = 0;

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>UTF8 BOM 清除器</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>

</head>

<body>

<?php

$BOMBED = array();

RecursiveFolder($HOME);

echo '<h2>These files had UTF8 BOM, but i cleaned them:</h2><p class="FOUND">';

foreach ($BOMBED as $utf) { echo $utf ."<br />\n"; }

echo '</p>';

// 遞歸掃描

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;

     // 移出BOM信息

     $content = substr($content,3);

     // 寫回到原始文件

     file_put_contents($sHOME . $win32 . $file, $content);

    }

   }

  }

 }

 $folder->close();

 if(count($foundfolders) > 0) {

  foreach ($foundfolders as $folder) {

   RecursiveFolder($folder, $win32);

  }

 }

}

// 搜索當前文件是否有BOM

function SearchBOM($string) { 

  if(substr($string,0,3) == pack("CCC",0xef,0xbb,0xbf)) return true;

  return false; 

}

?>

</body>

</html>

相關文章
相關標籤/搜索