Solved

Add and delete domain names to .htaccess

Posted on 2006-07-11
13
345 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
ID: 17088724
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
ID: 17088732
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
ID: 17092974
Any luck?
0
 
LVL 10

Author Comment

by:ray-solomon
ID: 17093243
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
ID: 17093263
My directory structure:

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

0
 
LVL 10

Author Comment

by:ray-solomon
ID: 17097341
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 10

Author Comment

by:ray-solomon
ID: 17097348
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
ID: 17097547
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
ID: 17098045
You're welcome.
0
 
LVL 29

Expert Comment

by:TeRReF
ID: 17098057
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
ID: 17119876
okay, thank you. I'll be waiting
0
 
LVL 29

Expert Comment

by:TeRReF
ID: 17119984
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
ID: 17131978
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

863 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

25 Experts available now in Live!

Get 1:1 Help Now