Search code examples
phpapache.htaccessapache2.htpasswd

Passwordprotecting a Single PHP file with Apache2 or PHP independantly from anything else


Dear folks, Inside folder images I would like to password protect a single php file render.php I already have in that folder my .htaccess as well as my .htpasswd files however they dont work

.htaccess in folder /images

// does not work ??
<Files render.php>
  AuthName "Login"
  AuthType Basic
  AuthUserFile /var/www/vhosts/site.com/httpdocs/images/.htpasswd
  require valid-user
</FilesMatch>

.htpasswd

admin:818jp2uNLY6ZW     
# generated with http://www.4webhelp.net/us/password.php

As soon as I set the rules in htaccess of that folder, all stuff in that folder seems get weirdly processed, css files insite that folder get corrupted etc. Why does this not work ?

PS I am also perfectly fine (in fact would prefer, if possible at all) to use a password setting within php file itself, that way I will be sure nothing else gets affected than only that php file no matter its name or location ( probably more elegant and timess ) though I saw everyone using htaccess so there must be an advantage there, right?

Thanks very much for your suggestions!


Solution

  • You can perform this auth in PHP as shown in the manual:

    <?php
    if (!isset($_SERVER['PHP_AUTH_USER']) || $_SERVER['PHP_AUTH_USER'] != 'admin' || $_SERVER['PHP_AUTH_PW'] != 'foobar') {
        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Unauthorized';
        exit;
    }