Solved

Add and delete domain names to .htaccess

Posted on 2006-07-11
13
339 Views
Last Modified: 2008-02-01
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]
0
Comment
Question by:ray-solomon
  • 7
  • 6
13 Comments
 
LVL 29

Accepted Solution

by:
TeRReF earned 500 total points
Comment Utility
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
 
LVL 29

Expert Comment

by:TeRReF
Comment Utility
By the way, the script assumes it's called htaccess.php, change the script if you want to give it another name...
0
 
LVL 29

Expert Comment

by:TeRReF
Comment Utility
Any luck?
0
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
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
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
My directory structure:

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

0
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
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
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
Actually I think that last question is more appropriate in the apache section.. Thanks for your help TeRReF as always.
0
 
LVL 29

Expert Comment

by:TeRReF
Comment Utility
You're welcome.
0
 
LVL 29

Expert Comment

by:TeRReF
Comment Utility
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
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
okay, thank you. I'll be waiting
0
 
LVL 29

Expert Comment

by:TeRReF
Comment Utility
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
 
LVL 10

Author Comment

by:ray-solomon
Comment Utility
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

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now