檢查php檔案中是否含有bom的php檔案

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   檔案   ar   

原文連結: http://www.cnblogs.com/Athrun/archive/2010/05/27/1745464.html

另一篇文章:《關於bom.php》,http://hi.baidu.com/aullik5/blog/item/f0e589127a28a2f0f7039e5e.html

另一篇文章:《[BOM]PHP程式的UTF8神秘編碼問題之解》,http://www.mlecms.com/tech/56.html

  類似WINDOWS內建的記事本等軟體,在儲存一個以UTF-8編碼的檔案時,會在檔案開始的 地方插入三個不可見的字元(0xEF 0xBB 0xBF,即BOM)。它是一串隱藏的字元,用於讓記事本等編輯器識別這個檔案是否以UTF-8編碼。對於一般的檔案,這樣並不會產生什麼麻煩。但對於 PHP來說,BOM是個大麻煩。

  PHP並不會忽略BOM,所以在讀取、包含或者引用這些檔案時,會把BOM作為該檔案開頭本文的一部分。根據嵌入式語言的特點,這串字元將被直接執行(顯示)出來。由此造成即使頁面的 top padding 設定為0,也無法讓整個網頁緊貼瀏覽器頂部,因為在html一開頭有這3個字元呢!

  最大的麻煩還不是這個。受COOKIE送出機制的限制,在這些檔案開頭已經有BOM的檔案中,COOKIE無法送出(因為在COOKIE送出前PHP已經送出了檔案頭),所以登入和登出功能失效。一切依賴COOKIE、SESSION實現的功能全部無效。 
<?php/*檢測並清除BOM*/  if(isset($_GET[‘dir‘])){      $basedir=$_GET[‘dir‘];  }else{      $basedir = ‘.‘;  }   $auto = 1;   checkdir($basedir);  function checkdir($basedir){      if($dh = opendir($basedir)){          while(($file = readdir($dh)) !== false){              if($file != ‘.‘ && $file != ‘..‘){                  if(!is_dir($basedir."/".$file)){                      echo "filename: $basedir/$file ".checkBOM("$basedir/$file")." <br>";                  }else{                      $dirname = $basedir."/".$file;                      checkdir($dirname);                  }              }          }//end while      closedir($dh);      }//end if($dh  }//end function  function checkBOM($filename){      global $auto;      $contents = file_get_contents($filename);      $charset[1] = substr($contents, 0, 1);       $charset[2] = substr($contents, 1, 1);       $charset[3] = substr($contents, 2, 1);       if(ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191){          if($auto == 1){              $rest = substr($contents, 3);              rewrite ($filename, $rest);              return "<font color=red>BOM found, automatically removed.</font>";          }else{              return ("<font color=red>BOM found.</font>");          }      }       else return ("BOM Not Found.");  }//end function  function rewrite($filename, $data){      $filenum = fopen($filename, "w");      flock($filenum, LOCK_EX);      fwrite($filenum, $data);      fclose($filenum);  }//end function  ?>

完畢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.