Add and delete domain names to .htaccess

I have a .htaccess file with rewrite conditions in it, and I would like a way to update it easily by filling out a form and submitting it. It will need to show what domains already exist and let me choose which ones to delete and the ability to add a domain name.

Here is the example .htaccess rules:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://somedomain.com/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^http://somedomain.com$      [NC]
RewriteCond %{HTTP_REFERER} !^http://www.somedomain.com/.*$      [NC]
RewriteCond %{HTTP_REFERER} !^http://www.somedomain.com$      [NC]
RewriteRule .*\.(jpg|jpeg|gif|png|bmp|js)$ - [F,NC]
LVL 10
ray-solomonAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
TeRReFConnect With a Mentor Commented:
That is quite danerous! GIving your webserver rights to write to a .htaccess file means that naughty people can do so as well via the same webserver. You will have to take all the security measures known to men to make it as safe as possible :)

Anyway, here's a script that does it.
Make sure you set $htfile with the path to your .htaccess file.
Also, make sure, your webserver user has rights to write to .htaccess
Also, create a .htaccess.old in the same dir as .htaccess, with the same permissions set to it. (that's your backup file if something goes wrong)

<?php
      // change this to the full path to your .htaccess file
      $htfile = 'text.txt';
      
      function getlines() {
            $lines = file($GLOBALS['htfile']);
            $GLOBALS['s'] = '';
            foreach ($lines as $line) {
                  $line = str_replace(array("\n", "\r"), '', $line);
                  $s .= '<option value="'.$line.'">'.$line.'</option>'."\n        ";
            }
            $GLOBALS['s'] = $s;
            $GLOBALS['lines'] = $lines;
      }

      function showform() {
            getlines();
            echo
<<<EOT
<html>
  <head>
    <title>
      Blah
    </title>
  <head>
  <body>
    <form action="htaccess.php?cmd=remove" method="POST">
      <p>Hold CTRL to select multiple entries.</p>
      <select multiple class="text1" name="entries[]" cols="15" size="15">
        {$GLOBALS['s']}
      </select>
      <br />
      <input type="submit" value="Remove"/>
    </form>
    <br />
    <form action="htaccess.php?cmd=add" method="POST">
      <input type="text" name="addline" /> Add line
      <br />
      <input type="submit" value="Add"/>
    </form>
  </body>
</html>
EOT;
      }

function remove() {
      $a = (array_key_exists('entries', $_POST)) ? $_POST['entries'] : array();
      if (count($a)) {
            getlines();
            if (count($GLOBALS['lines']))
                  file_put_contents($GLOBALS['htfile'].'.old', $GLOBALS['lines']);
            else
                  die("No lines were read from .htaccess, cannot continue");
            $newlines = array();
            foreach ($GLOBALS['lines'] as $line) {
                  if (!in_array(trim($line), $a))
                        $newlines[] = $line;
            }
            if (file_put_contents($GLOBALS['htfile'], $newlines) > 0)
                  echo 'Removing seems to be done<br />'."\n";
            else
                  echo 'Error writing to file<br />'."\n";
            showform();
      }
}

      $valid_commands = array('add', 'remove', 'showform');
      $command = (array_key_exists('cmd', $_REQUEST) ? $_REQUEST['cmd'] : 'showform');
      if (in_array($command, $valid_commands))
                $content = $command();
        else
                $content = showform();

function add() {
      $s = (array_key_exists('addline', $_POST) && trim($_POST['addline'] != '')) ? $_POST['addline'] : false;
      getlines();
      array_push($GLOBALS['lines'], $s);
      if (file_put_contents($GLOBALS['htfile'], $GLOBALS['lines']) > 0)
            echo 'Adding seems to be done<br />'."\n";
      showform();
}

?>
0
 
TeRReFCommented:
By the way, the script assumes it's called htaccess.php, change the script if you want to give it another name...
0
 
TeRReFCommented:
Any luck?
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
ray-solomonAuthor Commented:
I get this error when trying to add or remove a line. I was sure this is caused by the directory or files not being writeble.
I put this in a subdirectory called js so I could change permissions to the directory and files in it, but this did not work either.

What is the correct chmod permissions for each files(s) and directory.

Fatal error: Call to undefined function: file_put_contents() on line 52

0
 
ray-solomonAuthor Commented:
My directory structure:

/
/js/.htaccess
/js/htaccess.php
/js/myjsfile.js

0
 
ray-solomonAuthor Commented:
Yes I understand the security implications. I am trying to figure out a way to use this .htaccess file in a subdirectory instead of the root so I can edit in there instead. I tried many combinations of permissions for the .htaccess, htaccess.php and the js directory to make the script work, but I see no solution yet.

I wonder if a symlink in the root that points to the .htaccess file that is outside of the root will work. Then I could have a script update the real .htaccess file by using an exec call from within the root.

I never tried creating a symbolic link of a .htaccess file in the root. Theoretically, this should work, shouldn't it?

So the new structure would look like this:

/var/www/.htaccess
/var/www/html/{symlink}
/var/www/html/js/file.js
0
 
ray-solomonAuthor Commented:
I meant this:

/var/www/.htaccess
/var/www/html/{symlink}
/var/www/html/js/file.js
/var/www/html/js/htaccess.php -using exec call-
0
 
ray-solomonAuthor Commented:
Actually I think that last question is more appropriate in the apache section.. Thanks for your help TeRReF as always.
0
 
TeRReFCommented:
You're welcome.
0
 
TeRReFCommented:
I see now (sorry I didn't notice it before) that this is the error:
Fatal error: Call to undefined function: file_put_contents() on line 52

That is a PHP issue. It means that file_put_contents is not in your version of PHP. It's a PHP5 function. I shall rewrite the code a bit to make it work for you. I think I'll have some time later today.
0
 
ray-solomonAuthor Commented:
okay, thank you. I'll be waiting
0
 
TeRReFCommented:
Hi ray-solomon,

I'm so sorry, I totally forgot about this question.
Before I rewrite the code, there is another solution that you might consider. I don't know if you're familia with PEAR? It's a collection of classes/ functions that extend PHP functionality. One of them is called compat.
Compat gives you a lot of PHP5 functions in your PHP4 version of PHP. You will find a lot of handy functions available.
You can download it here:
http://pear.php.net/package/PHP_Compat
After downloading, you just look through all the files until you find the function you need and add this file to your project (in your case file_put_contents.php)
Then you include it in the PHP code I wrote for you with:
include_once('file_put_contents.php');
Add it just under the:
<?php

The function should be available in your code now, and it should work...

Let me know if this helps...

Frank
0
 
ray-solomonAuthor Commented:
I get this error when trying to do that:
include_once('file_put_contents.php');

Warning: main(file_put_contents.php): failed to open stream: No such file or directory in /home/im4mlm/public_html/htaccess.php on line 2

Warning: main(): Failed opening 'file_put_contents.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/im4mlm/public_html/htaccess.php on line 2
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.