I am making a script in which php will fwrite and it ads it after the </file> tag and it doesnt get included. The main purpose is to log each IP in this .htaccess file in order to not have access to this specific file. Here is my code: (Searching about 3+ hours on google & php.net). I have thought if there is a way to read from the file .htaccess where the "word" </file> is and before it add the $ip. Or some other way to get the $badpersonip inside the <file forum.php *(I can not use a database so it needs to be done solely from PHP and .htaccess)
<?php
$badpersonip = $_SERVER['REMOTE_ADDR'];
echo "You have been banned $badpersonip , dont spam!! <br> ";
$ip = "deny from $badpersonip \n";
$banip = '.htaccess';
$fp = fopen($banip, "a");
$write = fputs($fp, $ip);
?>
Also here is my .htaccess code:
<files forum.php>
Order Allow,Deny
Allow from all
deny from 127.0.2.1
deny from 127.1.2.1
</files>
deny from 127.0.0.3
As you see it ads the new IP but on the bottom AFTER the files tag has closed. :(
Thank you for your help really appreciated.
If instead of using fwrite()
you read the whole thing into a string with file_get_contents()
, you can easily do str_replace()
to replace the existing </files>
with the new line and </files>
// Read the while file into a string $htaccess
$htaccess = file_get_contents('.htaccess');
// Stick the new IP just before the closing </files>
$new_htaccess = str_replace('</files>', "deny from $badpersonip\n</files>", $htaccess);
// And write the new string back to the file
file_put_contents('.htaccess', $new_htaccess);
This isn't recommended if you expect the file to become very large, but for a few dozen or few hundred IPs it should work fine. This won't work exactly as is if you have more than one </files>
in that .htaccess file. That would require more careful parsing to find the correct closing tag.
If preserving whitespace (if you have indentation before </files>
) is important to you, you look into using preg_replace()
in lieu of the simpler str_replace()
.
Another method to this would be to use file()
to read the .htaccess into an array of its lines, locate the line containing </files>
and insert a new array element before it then join the lines back together and write it to the file.