CheckBOM.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: 中闽 < 1464674022@qq.com >
  5. * Date: 2020/2/4
  6. * Time: 12:47
  7. */
  8. namespace app\common\command;
  9. use think\console\Command;
  10. use think\console\Input;
  11. use think\console\input\Argument;
  12. use think\console\input\Option;
  13. use think\console\Output;
  14. class CheckBOM extends Command
  15. {
  16. /**
  17. * 批量检测文件是否有bom
  18. * php think CheckBOM "D:\www\php"
  19. */
  20. protected function configure()
  21. {
  22. $this->setName('CheckBOM')
  23. ->addArgument('basedir', Argument::OPTIONAL, "base dir", ".")
  24. ->addOption('rewrite', 'r', Option::VALUE_NONE, 'delete bom')
  25. ->setDescription('check files if has bom');
  26. }
  27. protected function execute(Input $input, Output $output)
  28. {
  29. $basedir = $input->getArgument("basedir");//需要检测的目录,点表示当前目录
  30. $this->runDir($basedir, $output, $input->hasOption('rewrite'));
  31. }
  32. private function runDir($basedir, $output, $rewrite)
  33. {
  34. if (file_exists($basedir)) {
  35. if ($dh = opendir($basedir)) {
  36. while (($file = readdir($dh)) !== false) {
  37. if ($file != '.' && $file != '..') {
  38. $path = $basedir . DS . $file;
  39. if (!is_dir($path)) {
  40. $res = $this->checkBOM($path, $rewrite);
  41. if ($res != "ok")
  42. $output->writeln($path . ' - ' . $res);
  43. } else {
  44. $this->runDir($path, $output, $rewrite);
  45. }
  46. }
  47. }
  48. closedir($dh);
  49. }
  50. }
  51. }
  52. private function checkBOM($filename, $rewrite = false)
  53. {
  54. $contents = file_get_contents($filename);
  55. $charset[1] = substr($contents, 0, 1);
  56. $charset[2] = substr($contents, 1, 1);
  57. $charset[3] = substr($contents, 2, 1);
  58. if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
  59. if ($rewrite) {
  60. $rest = substr($contents, 3);
  61. $this->rewrite($filename, $rest);
  62. return ('BOM found, automatically removed');
  63. } else {
  64. return ('BOM found');
  65. }
  66. } else {
  67. return ("ok");
  68. }
  69. }
  70. private function rewrite($filename, $data)
  71. {
  72. $filenum = fopen($filename, "w");
  73. flock($filenum, LOCK_EX);
  74. fwrite($filenum, $data);
  75. fclose($filenum);
  76. }
  77. }