ホームページ  >  記事  >  バックエンド開発  >  ホストを変更する PHP スクリプト

ホストを変更する PHP スクリプト

WBOY
WBOYオリジナル
2016-07-25 08:43:28890ブラウズ
  1. define('HOST_FILE', 'C:WindowsSystem32driversetchosts');
  2. $hm = new HostManage(HOST_FILE); $env = $argv[1]; $env)) {
  3. $hm->delAllGroup();
  4. } else {
  5. $hm->addGroup($env);
  6. }
  7. class HostManage {
  8. // ホスト ファイル パス
  9. protected $file;
  10. // ホストレコード配列
  11. protected $hosts = array();
  12. // 設定ファイルのパス、デフォルトは '.ini' です
  13. protected $configFile
  14. // ini 設定ファイルから読み取られる設定配列
  15. protected $config; = array();
  16. // 設定ファイルで設定する必要があるドメイン名
  17. protected $domain = array()
  18. // 設定ファイルによって取得される IP データ
  19. protected $ip = array();
  20. public function __construct($file, $config_file = null) {
  21. $this->file = $file;
  22. if ($config_file) {
  23. $this->configFile = $config_file } else {
  24. $this; ->configFile = __FILE__
  25. }
  26. $this->initHosts()
  27. ->initCfg()
  28. パブリック関数 __destruct() {
  29. $this->write() ;
  30. }
  31. public function initHosts() {
  32. $lines = file($this->file);
  33. foreach ($lines as $line) {
  34. $line = トリム($line); $line) || $line[0] == '#') {
  35. 継続
  36. }
  37. $this->hosts[$item[1] ]] = $item[0] }
  38. return $this;
  39. public function initCfg() {
  40. if (! file_exists($this->configFile)) {
  41. $this->config = array (); } else {
  42. $this->config = (parse_ini_file($this->configFile, true))
  43. }
  44. $this->domain = array_keys($this->config['ドメイン']) ;
  45. $this->ip = $this->config['ip'];
  46. $this; }
  47. /**
  48. * 設定ファイル内のドメインのホストを削除します
  49. */
  50. パブリック関数 delAllGroup() {
  51. foreach ($this ->ドメインを $domain として) {
  52. $this->delRecord($domain); }
  53. }
  54. /**
  55. * 指定された IP にドメインを設定します
  56. * @param type $env
  57. * @return HostManage
  58. */
  59. public function addGroup($env) {
  60. if ( ! isset( $this->ip[$env])) {
  61. return $this; }
  62. foreach ($this->domain as $domain) {
  63. $this->addRecord($domain, $this -> ip[$env]);
  64. }
  65. $this; }
  66. /**
  67. * ホストレコードを追加します
  68. * @param type $ip
  69. * @param type $domain
  70. */
  71. function addRecord($domain, $ip) {
  72. $this->hosts ] = $ ip;
  73. return $this; }
  74. /**
  75. * ホストレコードを削除します
  76. * @param type $domain
  77. */
  78. function delRecord($domain) {
  79. unset($this->hosts[$domain]);
  80. }
  81. /**
  82. * ホストファイルに書き込みます
  83. */
  84. public function write() {
  85. $str = '';
  86. foreach ($this->hosts as $domain => $ip) {
  87. $str .= $ip . $ドメイン
  88. }
  89. file_put_contents($this->file, $str);
  90. return $this }
  91. }
コードをコピーします
使用法:
    php hosts.php local # ドメイン名はローカルマシン 127.0.0.1 を指します
  1. php hosts.php dev # ドメイン名は開発マシン 192.168.1.100 を指します
  2. php hosts.php #ドメイン名のホスト構成を削除します
コードをコピーします

ホスト、PHP

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。