Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a .htaccess file in PHP?

Tags:

php

.htaccess

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

like image 699
JasonDavis Avatar asked Jan 19 '10 00:01

JasonDavis


People also ask

How do I create a .htaccess file?

Having a dot in front of the name makes the file hidden. Use your preferred text editor, create a file named . htaccess on your desktop or any other local folder, add the desired text and then upload the file using an FTP client. Instructions on how to establish an FTP connection can be found here.

What is the htaccess file in PHP?

htaccess (Hypertext Access) file is an Apache distributed server configuration file. You can use the . htaccess file to set server configurations for a specific directory. This directory can be the root directory of your website or another subdirectory where the .

What is htaccess file example?

htaccess file can be found primarily in your website's root folder, for example: /var/www/html/. Essentially, every directory on the webserver can have a '. htaccess' file. Each directory can have only one .

Where do I put .htaccess file?

htaccess file location is most commonly found in your website's public_html folder.


1 Answers

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.

like image 106
hobodave Avatar answered Oct 29 '22 09:10

hobodave