PHP - Writing to Host file programmatically

夙愿已清 提交于 2019-12-25 09:15:56

问题


I am doing my project implementation in localhost Xampp installation

Part of my project is ,

When the user sign up on my page he will be asked for his desired sub domain and from then on his URL will be :

chosensubdomain.mysite.com

Everything works perfectly , except for sub domain i have to manually add the entries in windows host file as follows

127.0.0.1       chosensubdomain.mysite.com   abc.mysite.com  xyz.mysite.com

What i want was when the form submits the host file should be added up with a entry

I am not sure that whether it is possible to make entry in Windows Host file programmatically using PHP .

Kindly help me out with this mates ...


回答1:


While this is very possible, a better, time saving approach will be to use your programming language of choice to dynamically create sub-folders on the server then use a .htaccess file to rewrite http://foo.com/bar to http://bar.foo.com. This should help you if you're on a live server or you use Zpanel on a local machine (For ease of advanced dns control) else you can manually add a catch-all (*) sub-domain in your host file.

*.foo.com       IN  A       127.0.0.1

If you still want to do it the ol' way, you have to use PHP's I/O functions to append text dynamically to your host file.

$sub_domain = "   foo.bar.com";
$append = file_put_contents('C:\Windows\System32\drivers\etc\hosts', $sub_domain.PHP_EOL , FILE_APPEND | LOCK_EX);

I actually think this answers your question better.




回答2:


Keeping writing new entries to hosts is not a good way.

Here is my idea: Use Dnsmasq on your local environment.

For Example: Setup Dnsmasq on OSX

The rule for dnsmasq should be set to resolve any domain ending with mysite.com to 127.0.0.1

In such way, all your subdomain matched on your local environment will point to localhost, which get your problem solved.

In production environment, you may set a wildcard A or AAAA (maybe) record for your domain.



来源:https://stackoverflow.com/questions/39671989/php-writing-to-host-file-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!