当前位置:Gxlcms > PHP教程 > PHP实例:检测并清除文件开头的BOM信息

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

时间:2021-07-01 10:21:17 帮助过:23人阅读

  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

人气教程排行