当前位置 : 主页 > 网络编程 > PHP >

bom头和文件编码检查.php

来源:互联网 收集:自由互联 发布时间:2021-06-28
bom头和文件编码检查.php Start';auto_dir($dir);echo ' Finished ';/** * 检测文件编码 * @param string $file 文件路径 * @return string|null 返回 编码名 或 null */function detect_encoding($file) { $list = array('GBK', 'UT
bom头和文件编码检查.php
 Start';
auto_dir($dir);
echo '

Finished

'; /** * 检测文件编码 * @param string $file 文件路径 * @return string|null 返回 编码名 或 null */ function detect_encoding($file) { $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'); $str = file_get_contents($file); foreach ($list as $item) { $tmp = mb_convert_encoding($str, $item, $item); if (md5($tmp) == md5($str)) { return $item; } } return null; } /** * 自动解析编码读入文件 * @param string $file 文件路径 * @param string $charset 读取编码 * @return string 返回读取内容 */ function auto_read($file, $charset='UTF-8') { $list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'); $str = file_get_contents($file); foreach ($list as $item) { $tmp = mb_convert_encoding($str, $item, $item); if (md5($tmp) == md5($str)) { return mb_convert_encoding($str, $charset, $item); } } return ""; } function auto_dir($path){ //自定义函数递归的复制带有多级子目录的目录 if($dir_handle = opendir($path)){ while( $filename = readdir($dir_handle)){ if( ($filename != '.') && ($filename != '..')){ $sub_file = $path. '/'. $filename; if(is_dir($sub_file)){ auto_dir($sub_file); } //设置要检查的文件类型 if(is_file($sub_file) && ( (substr($filename, -4) == '.php') || (substr($filename, -4) == '.htm') || (substr($filename, -5) == '.html') || (substr($filename, -3) == '.js'))){ checkBOM($sub_file); $encode = detect_encoding($sub_file); if ($encode == 'GBK') { $tmp_str = 'GBK'; } else { $tmp_str = ''. $encode. ''; } echo '---------------------------------->'. $tmp_str; echo '
'; } } } closedir($dir_handle); } } function checkBOM ($filename) { echo $filename .'-------->'; global $auto; $contents=file_get_contents($filename); $charset[1]=substr($contents, 0, 1); $charset[2]=substr($contents, 1, 1); $charset[3]=substr($contents, 2, 1); if (ord($charset[1])==239 && ord($charset[2])==187 && ord($charset[3])==191) { if ($auto==1) { $rest=substr($contents, 3); //rewrite ($filename, $rest); echo " BOM found, automatically removed."; } else { echo " BOM found."; } } else { echo "BOM Not Found."; } //echo ''; } function rewrite ($filename, $data) { $filenum=fopen($filename,"w"); flock($filenum,LOCK_EX); fwrite($filenum,$data); fclose($filenum); }
上一篇:encryption_helper.php
下一篇:test.php
网友评论