edit htaccess via php
I have a script that on certain events blocks someones ip via a开发者_StackOverflow社区 htaccess deny from. This is the code:
file_put_contents('.htaccess', 'deny from ' . $_SERVER['REMOTE_ADDR'] . "\n", FILE_APPEND);
Yet what i want is instead od deny from this user can i have it redirect the user to another page.
I can do this via:
Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_HOST} !^123\.45\.67\.89
RewriteRule \.html$ /alternate_page.html [R=302,L]
But is it possible to do it without opening the htaccess and appending to it. Instead use the file_put_contents
function
Thanks A Lot.
You don't need to use .htaccess for redirecting users to other pages, just use the location
header based on what you get from $_SERVER['REMOTE_ADDR']
:
header("Location: http://anothersite.com")
and don't forget this (from the PHP manual):
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called.
I would recommend storing IP addresses you do not want to allow in a database. This makes administration and if you want stats, they can be added easily as well (ie. How many times has this user tried to access the site after being denied, etd). You could even send certain IPs to different location if you wanted.
- Store the IP addresses in a database table
- When a user comes to the page check to see if their IP is in the table
- If so increment stats counter (if desired) and redirect user to new location
- Or continue loading the current page
Use php's Header function Header('Location: [url here]');
to redirect them and remember it must be before any other content is sent to the page.
What you can do is have your .htaccess file like this:
Options +FollowSymLinks
RewriteEngine on
# ADD RULES HERE
RewriteCond x x # This is a dummy condition that is always true
RewriteRule \.html$ /aternate_page.html [R=302,L]
Then you can have your replacement work like this:
<?php
file_put_contents(".htaccess",str_replace("# ADD RULES HERE","# ADD RULES HERE\nRewriteCond %{REMOTE_HOST} ^".$_SERVER['REMOTE_ADDR']."$",file_get_contents(".htaccess"));
?>
HTH
(Edit: This doesn't seem quite right... So may need a little editing. Hope the general idea helps, though.)
The proper way would be to use a gatekeeper function, which checks the IP, and forwards the request to the required page on need.
<?php
header('Location: http://www.yoursite.com/new_page.php');
?>
You should call this before any output is sent to the browser, including any HTML tags or white space. The common way is to have a 'forward' function wrapping the header command, and do access control first, before sending any content.
精彩评论