问题
What I am trying to do is automate the process of going live with websites. These websites are all 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 do is add a domain alias for domain.com, and then point it to my server IP and the htaccess file makes it view what is in the /folder.
It works fine but we are planning to have hundreds of websites and adding that snippet of code to the htaccess manually can get pretty annoying. Since all I am changing is domain.com and the /folder, is there a way to use PHP to dynamically add to the bottom of the .htaccess file if I create a form and tell it the domain and the folder, it will add it to the bottom of the htaccess file?
That would save so much time.
Thanks so much.
回答1:
I really do not recommend to allow php to add ANYTHING into .htaccess, it's a big security risk.
//but here is your code
$f = fopen(".htaccess", "a+");
fwrite($f, "your content");
fclose($f);
回答2:
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 0644
permissions on .htaccess
(as php runs under the same user as file's owner)
回答3:
Sure. Its just another file as long as the process has permission to write to the file.
回答4:
A pretty comfortable way is using the PEAR class File_HtAccess. But as told before you shouldn't write the file from a PHP-Script that is accessible via web.
来源:https://stackoverflow.com/questions/6358330/use-php-to-dynamically-add-to-htaccess-file