Web Hosting Talk







View Full Version : php, writing to .htaccess ?


acctman
06-13-2009, 02:41 PM
hi can someone assist me with help on how to write to a .htaccess file and insert a deny IP. what i'll need to do is insert above </Limit> and /n for new line


<Limit GET POST>
order deny,allow
allow from all
deny from 127.0.0.1
</Limit>

Kohrar
06-14-2009, 06:41 AM
Interesting problem. ;) If you want to go all crazy with fseek, here is my solution:

$fp = fopen('htaccess.txt', 'r+');
fseek($fp, 0, SEEK_END); // Go to the end of the file
fseek($fp, ftell($fp) - 9); // Go to the position where </Limit> is.
// 9 because there is 9 characters in '</Limit>\n'
fwrite($fp, "deny from 123.123.123.123\n");
fwrite($fp, "</Limit>\n");
fclose($fp);


Just make sure that your .htaccess has a new line after </Limit> for it to work properly.

Otherwise, I'd use file and put it before the last line, but you're opening the file twice and rewriting the entire file with this approach:


$htaccess = file('htaccess.txt');
$lines = count($htaccess);

$fp = fopen('htaccess.txt', 'w');

for ($i = 0; $i < $lines; $i++) {
if ($i == $lines - 1) // Edit: If you have more lines after </Limit> you have to change the number here.
fwrite($fp, "deny from 123.123.123.123\n");
fwrite($fp, $htaccess[$i]);
}
fclose($fp);


I think the second one may be a little bit more robust, but they both should work.

Kohrar
06-14-2009, 05:16 PM
Sorry about double posting, but I thought of another solution based on the second one when I went to bed which will be less problematic than the two I gave above:



$target = 'htaccess.txt';
$htaccess = file($target);
$lines = count($htaccess);

$fp = fopen($target, 'w');
for ($i = 0; $i < $lines; $i++) {
$currentLine = trim($htaccess[$i]);
if ($currentLine == '</Limit>')
fwrite($fp, "deny from 123.123.123.123\n");
fwrite($fp, $currentLine . "\n");
}
fclose($fp);


This will be a bit ineffecient, but since it is a .htaccess file, effeciency doesn't really matter too much. This will write your 'deny from x.x.x.x' right before the </limit> line. So there are no magic numbers to deal with unlike the implementation I gave in the previous post. :agree:

foobic
06-14-2009, 05:36 PM
I'd suggest a different method altogether. Instead of editing .htaccess every time, have your PHP script create a file named after each IP address you want to ban, then use mod_rewrite in .htaccess to detect the file and deny access.
Errordocument 403 403.html
# defined 403 document allows banned users to see "Access denied" page

RewriteEngine On

RewriteCond %{REQUEST_URI} !403.html
# always allow access to the 403 page

RewriteCond /path/to/access_dir/%{REMOTE_ADDR} -f
# limit rule to IPs recorded as filenames in access_dir directory

RewriteRule .* - [F,L]
# F = fail, ie. deny access with a 403 error