Use PHP to Dynamically Add To .htaccess File?

痴心易碎 提交于 2019-12-12 08:11:57

问题


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

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