Use PHP to dynamically add to .htaccess file?

What I'm trying to do is automate the process of moving from websites. These websites are dynamically created using htaccess, so here is an example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^(.*)$ /folder%{REQUEST_URI}?%{QUERY_STRING} [QSA,L]

What I am doing is adding a domain alias for domain.com, and then pointing it to my server IP address, and the htaccess file allows me to see what is in the / folder.

It works great, but we plan to have hundreds of websites and adding this piece of code to htaccess manually can be quite annoying. Since all I am changing is domain.com and / folder, is there a way to use PHP to dynamically add the .htaccess file to the bottom of the file, if I create a form and tell it the domain and folder, will it add it to the bottom of the htaccess file?

This will save so much time.

Many thanks.

+5
source share
4 answers

I really do not recommend allowing php to add ANYTHING to .htaccess, this is a big security risk.

//but here is your code
$f = fopen(".htaccess", "a+");
fwrite($f, "your content");
fclose($f);
+26
source

Here you go:

function writeht($domain, $folder)
{
    $fp = fopen('.htaccess','a+');
    if($fp)
    {
        fwrite($fp,'

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{HTTP_HOST} ^(www\.)?'.str_replace('.','\.',$domain).'$ [NC]
RewriteRule ^(.*)$ /'.$folder.'%{REQUEST_URI}?%{QUERY_STRING} [QSA,L]');
        fclose($fp);
    }
}

//usage: writeht("domain.biz","yourfolder");

Works fine for me with permissions 0644on .htaccess(since php works under the same name as the file owner)

+6
source

. , .

+4

- PEAR File_HtAccess. , , PHP- Script, .

+2

All Articles