欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

检测php文件是否有bom头的代码

程序员文章站 2022-05-13 17:17:56
...
  1. //此文件用于快速测试UTF8编码的文件是不是加了BOM,并可自动移除
  2. //By Bob Shen
  3. $basedir="."; //修改此行为需要检测的目录,点表示当前目录

  4. $auto=1; //是否自动移除发现的BOM信息。1为是,0为否。
  5. //以下不用改动

  6. if ($dh = opendir($basedir)) {
  7. while (($file = readdir($dh)) !== false) {
  8. if ($file!='.' && $file!='..' && !is_dir($basedir."/".$file)) echo "filename: $file ".checkBOM("$basedir/$file")."
    ";
  9. }
  10. closedir($dh);
  11. }
  12. function checkBOM ($filename) {

  13. global $auto;
  14. $contents=file_get_contents($filename);
  15. $charset[1]=substr($contents, 0, 1);
  16. $charset[2]=substr($contents, 1, 1);
  17. $charset[3]=substr($contents, 2, 1);
  18. if (ord($charset[1])==239 && ord($charset[2])==187 && ord($charset[3])==191) {
  19. if ($auto==1) {
  20. $rest=substr($contents, 3);
  21. rewrite ($filename, $rest);
  22. return ("BOM found, automatically removed.");
  23. } else {
  24. return ("BOM found.");
  25. }
  26. }
  27. else return ("BOM Not Found.");
  28. }
  29. function rewrite ($filename, $data) {

  30. $filenum=fopen($filename,"w");
  31. flock($filenum,LOCK_EX);
  32. fwrite($filenum,$data);
  33. fclose($filenum);
  34. }
  35. ?>
复制代码