用php去除bom頭

最近在用dede開發一個網站的時候,發現網站在本地沒什麼問題,可是上傳到服務器上面去以後,在首頁會默認的生成一串的字符串,以下圖所示:

 

百度了以後,發現好多的解決方法都是說的把文件存儲爲utf-8無bom模式,可是發現我用了這個方法以後,這字符串仍是在~php

後面經人提點說有php方法能夠去除~而後找到如下代碼:html

 1 <?php
 2 if (isset($_GET['dir'])) { //設置文件目錄 
 3     $basedir = $_GET['dir'];
 4 } else {
 5     $basedir = '.';
 6 }
 7 
 8 $auto = 1;
 9 checkdir($basedir);
10 
11 function checkdir($basedir)
12 {
13     if ($dh = opendir($basedir)) {
14         while (($file = readdir($dh)) !== false) {
15             if ($file != '.' && $file != '..') {
16                 if (!is_dir($basedir . "/" . $file)) {
17                     echo "filename: $basedir/$file " . checkBOM("$basedir/$file") . " <br>";
18                 } else {
19                     $dirname = $basedir . "/" . $file;
20                     checkdir($dirname);
21                 }
22             }
23         }
24         closedir($dh);
25     }
26 }
27 function checkBOM($filename)
28 {
29     global $auto;
30     $contents   = file_get_contents($filename);
31     $charset[1] = substr($contents, 0, 1);
32     $charset[2] = substr($contents, 1, 1);
33     $charset[3] = substr($contents, 2, 1);
34     if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
35         if ($auto == 1) {
36             $rest = substr($contents, 3);
37             rewrite($filename, $rest);
38             return ('<font color="red">BOM found, automatically removed.</font>'); 
39         } else {
40             return ('<font color="red">BOM found.</font>');
41         }
42     } else
43         return ("BOM Not Found.");
44 }
45 
46 function rewrite($filename, $data)
47 {
48     $filenum = fopen($filename, "w");
49     flock($filenum, LOCK_EX);
50     fwrite($filenum, $data);
51     fclose($filenum);
52 }
53 ?>

具體使用方法以下(此流程只針對於php小白~):服務器

1.新建一個php文件,命名你本身隨便取,我這裏就取名爲:withoutBoml.php;網站

2.將文件上傳到根目錄下面(所謂的根目錄就是wwwroot或者htdocs);spa

3.而後運行此段php代碼:http://你的網站域名/withoutBoml.php(好比說你的網站是www.haha.com,那麼就運行http://www.haha.com/withoutBoml.php).rest

 

運行完以後再看你的網站,發現真的沒有了哦~~ code

 

10月24日更新htm

感謝@ 都瓦克因 ,告訴了我報錯緣由是return裏面輸出的html語句雙引號衝突了,把最外層的雙引號修改成單引號就能夠了;blog

相關文章
相關標籤/搜索