Apache本地自动解析虚拟域名

使用本地虚拟域名解析,更加能够模拟域名在线访问的环境。

如下代码,可以实现本地自动添加域名解析

<?php
#将php文件放在xampp目录下,执行即可根据目录名生成本地解析的虚拟域名
define('DS', DIRECTORY_SEPARATOR);
define('WEBDIR', __DIR__ . DS . 'htdocs' . DS);
define('HOST', 'C:' . DS . 'Windows' . DS . 'System32' . DS . 'drivers' . DS . 'etc' . DS . "hosts");
define('VHOST', __DIR__ . DS . 'apache' . DS . 'conf' . DS . 'extra' . DS . "httpd-vhosts.conf");

$dirs = scandir(WEBDIR);

$hosts = file(HOST, FILE_IGNORE_NEW_LINES);

foreach ($dirs as $dir) {
    if ($dir !== '.' && $dir !== '..') {
        if (strpos($dir, '.') > 0) {
            $server_name = $dir;
            $dir_name = realpath(WEBDIR . $dir);
            $r_vhost[] = get_vhost_str($dir_name, $server_name);
            #写入host文件
            $this_host_str = get_host_str($server_name);
            if (!in_array($this_host_str, $hosts)) {
                $r_host[] = $this_host_str;
            }
        }
    }
}

if($r_vhost) file_put_contents(VHOST, implode("", $r_vhost));
if($r_host) file_put_contents(HOST, implode("", $r_host));

echo '执行结束,请重启Apache服务器';

function get_host_str($server_name) {
    return '127.0.0.1 ' . $server_name . "\r\n";
}

function get_vhost_str($dir_name, $server_name) {
    $str = <<<EOT
<VirtualHost *:80>
    ServerName {$server_name}
    DocumentRoot "{$dir_name}"
    <Directory "{$dir_name}">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>    
</VirtualHost>


EOT;

    return $str;
}
如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注