最近在玩PHP的時候,遇到下面這個錯誤訊息:
Warning: Cannot modify header information – headers already sent by
經查才發現是PHP在執行UTF-8的檔案時,BOM檔頭一直無法清掉。
將下列程式碼儲存成PHP檔,並將此檔案複製至根目錄下執行,這樣就會自動檢查所有檔案,並清除UTF-8檔的BOM檔頭。
1: <?php2: //remove the utf-8 boms3: //by magicbug at gmail dot com4: if (isset($_GET[’dir’])){ //config the basedir5: $basedir=$_GET[’dir’];6: }else{7: $basedir = ".";8: }9: $auto = 1;10:11: checkdir($basedir);12:13: function checkdir($basedir){14: if ($dh = opendir($basedir)) {15: while (($file = readdir($dh)) !== false) {16: if ($file != "." && $file != ".."){17: if (!is_dir($basedir."/".$file)) {18: echo "filename: $basedir/$file ".checkBOM("$basedir/$file")."";19: }else{20: $dirname = $basedir."/".$file;21: checkdir($dirname);22: }23: }24: }25: closedir($dh);26: }27: }28:29: function checkBOM ($filename) {30: global $auto;31: $contents = file_get_contents($filename);32: $charset[1] = substr($contents, 0, 1);33: $charset[2] = substr($contents, 1, 1);34: $charset[3] = substr($contents, 2, 1);35: if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {36: if ($auto == 1) {37: $rest = substr($contents, 3);38: rewrite ($filename, $rest);39: return ("BOM found, automatically removed.40: ");
41: } else {42: return ("BOM found.43: ");
44: }45: }46: else return ("BOM Not Found.47: ");
48: }49:50: function rewrite ($filename, $data) {51: $filenum = fopen($filename, "w");52: flock($filenum, LOCK_EX);53: fwrite($filenum, $data);54: fclose($filenum);55: }56: ?>
沒有留言:
張貼留言
注意:只有此網誌的成員可以留言。