Raja Gopal Raja Gopal - 2 months ago 20
PHP Question

PHP - Writing to Host file programmatically

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 ...

Answer

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.