轻松解决php网站头部空一行的问题 bom清除代码附上

今天用dede开发。生成的时候。老是上面有空格一行。就是换行了。用火狐看了下。发现是上面有个空格。

百度找了一下方法。发现是bom的问题。于是有了下面这款代码。复制直接放到要清除 bom的目录里。然后运行即可.


  1. <?php 
  2.  
  3. if (isset($_GET['dir'])){ //设置文件目录  
  4.  
  5. $basedir=$_GET['dir'];  
  6.  
  7. }else{  
  8.  
  9. $basedir = '.';  
  10.  
  11. }  
  12.  
  13. $auto = 1;  
  14.  
  15. checkdir($basedir);  
  16.  
  17. function checkdir($basedir){  
  18.  
  19. if ($dh = opendir($basedir)) {  
  20.  
  21. while (($file = readdir($dh)) !== false) {  
  22.  
  23. if ($file != '.' && $file != '..'){  
  24.  
  25. if (!is_dir($basedir."/".$file)) {  
  26.  
  27. echo "filename: $basedir/$file ".checkBOM("$basedir/$file")." <br>";  
  28.  
  29. }else{  
  30.  
  31. $dirname = $basedir."/".$file;  
  32.  
  33. checkdir($dirname);  
  34.  
  35. }  
  36.  
  37. }  
  38.  
  39. }  
  40.  
  41. closedir($dh);  
  42.  
  43. }  
  44.  
  45. }  
  46.  
  47. function checkBOM ($filename) {  
  48.  
  49. global $auto;  
  50.  
  51. $contents = file_get_contents($filename);  
  52.  
  53. $charset[1] = substr($contents, 0, 1);  
  54.  
  55. $charset[2] = substr($contents, 1, 1);  
  56.  
  57. $charset[3] = substr($contents, 2, 1);  
  58.  
  59. if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {  
  60.  
  61. if ($auto == 1) {  
  62.  
  63. $rest = substr($contents, 3);  
  64.  
  65. rewrite ($filename, $rest);  
  66.  
  67. return ("<font color=red>BOM found, automatically removed._<a href='http://www.chenxuanyi.cn'>http://www.chenxuanyi.cn</a></font>");  
  68.  
  69. } else {  
  70.  
  71. return ("<font color=red>BOM found.</font>");  
  72.  
  73. }  
  74.  
  75. }  
  76.  
  77. else return ("BOM Not Found.");  
  78.  
  79. }  
  80.  
  81. function rewrite ($filename, $data) {  
  82.  
  83. $filenum = fopen($filename, "w");  
  84.  
  85. flock($filenum, LOCK_EX);  
  86.  
  87. fwrite($filenum, $data);  
  88.  
  89. fclose($filenum);  
  90.  
  91. }  
  92.  
  93. ?> 
  94.  
  95.  
  96.