1

I have a PHP script that generates 100s of directories and in these directories contain CSV files. I'm able to protect these CSV files using AuthUserFile if it points to an absolute .htpasswd file, but I want to point to a custom generated .htpasswd in each of these directories.

  • Is there a way to replace: AuthUserFile with the password itself? I have it pregenerated in my PHP script already.
  • OR how can I reference the .htpasswd file in the same directory it's in. Doing the following doesnt work: AuthUserFile './htpasswd'

1 Answers1

0
  • Is there a way to replace: AuthUserFile with the password itself? I have it pregenerated in my PHP script already.
  • OR how can I reference the .htpasswd file in the same directory it's in. Doing the following doesnt work: AuthUserFile './htpasswd'

You can do neither of these unfortunately. AuthUserFile (ie. HTTP authentication) requires an absolute file-path (or relative path to the ServerRoot) and Apache expression syntax is not supported in order to make this "dynamic" AFAIK (as it is with some other directives in Apache 2.4, eg. ErrorDocument).

However, since you are generating the directories then you could presumably generate the .htaccess(?) file and corresponding .htpasswd files for each directory? However, .htpasswd files should never be stored in the directory they are protecting, or even in the public HTML space. They should be stored outside of the public directory tree, above the document root. (And presumably you were originally wanting to avoid multiple .htaccess files, although with your suggestions I'm not so sure?)

Alternatively, since you are already using PHP for generating these directories and your PHP script already knows the relevant passwords, then why not use PHP to manage access to the CSV files?

For example:

  1. Use Apache mod_rewrite to internally rewrite the request for any "protected" .csv file to a PHP script. For example:

    RewriteEngine On
    
    # All requests for ".csv" files in the "/foo/" dir tree are routed to "/serve-csv.php"
    RewriteRule ^/?foo/.+\.csv$ /serve-csv.php [L]
    
  2. The PHP script knows the file being requested (eg. $_SERVER['REQUEST_URI']) and the users/passwords that are permitted to access this file.

  3. PHP can manage the HTTP Basic Authentication (that you appear to be using) or implement your own authentication interface (HTML forms etc.)

  4. If the user is authenticated then PHP reads the requested file and serves this to the client.

MrWhite
  • 11,643
  • 4
  • 25
  • 40