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
| function removeBOM(string $file)
{
$random_name = function() use ($file) {
$alpha = range('a', 'z');
shuffle($alpha);
$alpha = implode('', $alpha);
$temp = basename($file);
return basename($file).substr($alpha, 0, mt_rand(5, 10)).rand(100000, 999999);
};
if (is_file($file)) {
$bom = "\xef\xbb\xbf";
$fh = fopen($file, 'r');
$oct = fread($fh, 3); // read 3 first octets
if ($oct === $bom) { // BOM detected
$temp = dirname($file).DIRECTORY_SEPARATOR.$random_name();
$size = filesize($file);
$fc = fopen($temp, 'w');
// copy the file octet by octet starting after the BOM
for ($i = 3 ; $i < $size ; ++$i) {
fseek($fh, $i);
fwrite($fc, fgetc($fh));
}
fclose($fc);
}
fclose($fh);
// rename and keep the old one
if ($oct === $bom) {
rename($file, "{$file}.old");
rename($temp, $file);
}
}
} |
Partager