批量清理 php 文件的bom 头

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
header('Content-Type: text/html; charset=UTF-8');
$dir = ''; //需要处理的根目录,默认为当前目录
$suffix = 'php'; //需要处理的文件类型,默认为php文件
$files = getfiles($dir, $suffix);
print_r($files);
$i = 0;
$success = false;
foreach($files as $file) {
	$s = file_get_contents($file);
	if(isbom($s)) {
		echo $file.' 含有 BOM 头'."\r\n";
		$s = substr($s, 3);
		file_put_contents($file, $s);
		$i++;
		$success = true;
	}
}
if($success) {
	echo '发现'.$i.'个带有 bom 头的文件,已经清理完毕。';
} else {
	echo '没有发现带有 bom 头的文件。';
}

function getfiles($dir = '', $suffix = 'php') {
	!isset($_SERVER['FILES']) && $_SERVER['FILES'] = array();
	!is_array($_SERVER['FILES']) && $_SERVER['FILES'] = array();
	if(!empty($dir) && substr($dir, -1) != '/') $dir = $dir.'/';
	$files = glob($dir . '*');
	foreach($files as $file) {
		if(is_dir($file)) {
			getfiles($file.'/',$suffix);
		} else {
			if($suffix == '*' || pathinfo($file,PATHINFO_EXTENSION) == $suffix) $_SERVER['FILES'][] = $file;
		}
	}
	return $_SERVER['FILES'];
}

function isbom($str) {
	return substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf);
}