tags:

views:

335

answers:

2

On my PHP site I would like to sometimes show a maintenance page to users. I know I can do this in PHP very easily but I would rather use an htaccess file, I think performance may be better this way. So what I am wanting to know is can I modify a htaccess file in PHP? If it is possible I am thinking either,

1 - Have to files and 1 will have the code below in it and the other will not, both files would contain my other htaccess stuff as well. Then php can rename these 2 files when I run an admin script to switch which file is shown, by changing it's name to .htaccess

2- Read the contents of the current .htaccess file and APPEND the code below into it, then also be able to remove it from the file if needed.

RewriteEngine On
RewriteBase / 
RewriteCond %{REQUEST_URI} !^/maintenance\.php$
RewriteRule ^(.*)$ http://domain.com/maintenance.html [R=307,L]

My goal is to build an admin script that can have 1 click processing to change the maintenance page to show or not to show.

Please any sample code or tips on how to do this or if it is even possible to modify a .htaccess file from PHP

+8  A: 

You can use fopen to open and fwrite to write to a file. You'll want to open it in append mode, read the manual to see which applies.

That said, this sounds like a strange way to go about doing things.

I accomplish what you're trying to do using just rewrite rules that check for file presence:

RewriteCond %{DOCUMENT_ROOT}/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /maintenance.html [L]

If the maintenance.html file is present, then my site is under maintenance.

hobodave
Thanks, I wasn't sure if this was some sort of protected file or not, I don't really have much experience working with files.
jasondavis
I agree with the solution here. I know programs like Cpanel and Wordpress will write to / autogenerate .htaccess code. But it seems like a ten-ton hammer for something that's easily done another way.
Bryan M.
+4  A: 

I would strongly recommend not writing .htaccess from PHP. You would have to give the web server user (who traditionally has very low privilege) write access to .htaccess; all you need is one exploitable script and an attacker could be effectively reconfiguring your server.

For an in-app-switches maintenance mode stick to having PHP itself return the maintenance page. When you are doing maintenance on the app itself it is easy enough to temporarily rename a file into .htaccess's position to enable the maintenance rewrite.

bobince