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

PHP实例:检测并清除文件开头的BOM信息

程序员文章站 2022-06-15 17:30:04
...
  1. ini_set('memory_limit', '-1');
  2. /*检测并清除BOM*/
  3. $basedir = dirname(__FILE__);//扫描当前文件路径 可自动设置
  4. $auto = 1;
  5. checkdir($basedir);
  6. function checkdir($basedir){
  7. if($dh = opendir($basedir)){
  8. while(($file = readdir($dh)) !== false){
  9. if($file != '.' && $file != '..'){
  10. if(!is_dir($basedir."/".$file)){
  11. echo "filename: $basedir/$file ".checkBOM("$basedir/$file")."
    ";
  12. }else{
  13. $dirname = $basedir."/".$file;
  14. checkdir($dirname);
  15. }
  16. }
  17. }//end while
  18. closedir($dh);
  19. }//end if($dh
  20. }//end function
  21. function checkBOM($filename){
  22. global $auto; // bbs.it-home.org
  23. $contents = file_get_contents($filename);
  24. $charset[1] = substr($contents, 0, 1);
  25. $charset[2] = substr($contents, 1, 1);
  26. $charset[3] = substr($contents, 2, 1);
  27. if(ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191){
  28. if($auto == 1){
  29. $rest = substr($contents, 3);
  30. rewrite ($filename, $rest);
  31. return "BOM found, automatically removed.";
  32. }else{
  33. return ("BOM found.");
  34. }
  35. }
  36. else return ("BOM Not Found.");
  37. }//end function
  38. function rewrite($filename, $data){
  39. $filenum = fopen($filename, "w");
  40. flock($filenum, LOCK_EX);
  41. fwrite($filenum, $data);
  42. fclose($filenum);
  43. }//end function
复制代码