Home  »  Htaccess  »  Control htaccess Basic Authentication with PHP and mod_rewrite

by 8 comments

Recently the following topic was started in the htaccessElite forum

Contents [hide]

What happens is that the member logs into a membership program (which starts $_SESSION["uname"] and $_SESSION["pword"]. Once logged in they are directed to a screen that shows them the protected directories that they are allowed to visit. They then click that link and it takes them to the directory and the apache login prompt asks them AGAIN for the username and password which is stored in the .htpasswd as well as the database.What I want to do is bypass the 2nd (apache login) prompt and give them direct access using the $_SESSION variables. But meanwhile keeping the .htaccess file to stop others from gaining access or linking directly to that directory and if no $_SESSION variables are present, utilize the apache login prompt. Hope that makes sense.
A better approach might be to move all this protected content into a directory that is not accesible from the Web. That is to say, a place that is accessible as part of the server's filesystem, but cannot be reached via HTTP. YOu can move these files to a directory 'above Web root' or simply place them in a subdirectory that is password-protected or made HTTP-inaccessbile using acccess-control directives in .htaccess.Then modify the script so that instead of doing an HTTP redirect, it instead takes the requested HTTP URL, changes it into a filename in the protected filespace, and then opens the requested file, reads it, and outputs the file data to the requesting client -- this latter step being no more than a 'print' statement in PHP.But another step is required, since all we've done so far is to make the HTTP-inaccessible filespace accessible via HTTP again. You need some way of checking that the user is authorized to access your content. I'd suggest making your script check for a cookie before opening the file in the protected space. Then modify the pages on your site that serve to 'authorize' the visitor so that they set the required cookie. An alternative is to use server-side user sessions to do the same thing.So our example in step-wise form looks like this:Visitor views 'authorization' page - Maybe just your home page or any page with protected content included.Page contains JavaScript or triggers server-side code to set a short-term session cookie on the visitor's machine.Visitor requests .avi file.Script checks for presence and validity of cookie, and if correct:- Opens .avi file in protected area,- Reads data from .avi file- prints data- exits.Else if the cookie is missing or incorrect, print an error message and exit.There are many ways to do this, and the above is just an example. The key is to distinguish the difference between external HTTP URL requests and internal server filesystem requests.
#function get401Page($file) {#$out = "GET $file HTTP/1.1rn";#$out .= "Host: ".x401_host."trn";#$out .= "Connection: Closern";#$out .= "Authorization: Basic ".base64_encode(x401_user.":".x401_pass)."rn";#$out .= "rn";
  1. PHP: CURL, Client URL Library Functions
  2. PHP header
  3. PHP: HTTP Authentication
  4. Curl Tutorial
  5. Sending POST data with curl

Example 1

< ?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(CURLOPT_USERPWD, '[username]:[password]')

$data = curl_exec();

Example 2:

< ?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(CURLOPT_USERPWD, '[username]:[password]')

$data = curl_exec();

Using AddHandler

You can use a handler setup in .htaccess. You could code:

AddHandler mywrapper .html
Action mywrapper /secure.php

in your .htaccess file. Then everytime somebody access a file that ends in .html it will execute the php script secure.php. Now you just write a script that implments the security you need. The user has no clue that there is a php script that is doing security. If you have other file types you just add AddHandler mywrapper .xxx where xxx is all of the file types you want to secure.I recently had to do this because I needed to use a back end security product that there was no built in support for in Apache and the 20 lines of PHP code was 1,000 times simpler for me than attempting to write C/C++ code to do what I wanted.


February 26th, 2007

Comments Welcome

  • Alfred

    I would like to implement the AddHandler tip to restrict access to CONTENT.HTML (and other HTML files) to authorised users.

    Content of .htaccess:

    AddHandler mywrapper .html
    Action mywrapper /secure.php

    Contents of secure.php:

    die('You are not authorised to access this content!');
    } else {

    How do I get CONTENT.HTML to display if $_SESSION['authorised'] is true?

  • John Drummond

    At last, I found this at AlistApart: How to Succeed With URLs

    if (session_is_registered(pdb_sessname))
      if(file_exists($DOCUMENT_ROOT.$REQUEST_URI) and
  • Jaime

    Funny. I have the EXACT same problem as alfred. I am trying to protect mp3/etc.. files on my site with a simple php session check routine, though after it succeeds I am lost as to how to resume the normal GET operation.

    Any help or pointers would be greatly appreciated.

  • Jaime

    Ok, I got it to work with the following code. I use mine to protect mp3 files on my site.

    if (file_exists($fqfile))
     header("Cache-Control: public, must-revalidate");
     header("Pragma: hack"); // not sure what this does but it works
     header("Content-Type: " . $mm_type);
     header("Content-Length: " .(string)(filesize($fqfile)) );
     header('Content-type: audio/mpeg');
     //header('Content-Disposition: attachment; filename="'.$filename.'"');
     header("Content-Transfer-Encoding: binaryn");
  • Richard Cox

    Tried accessing , I get requests for user id and password. It seems to ignore passwords three times then I see "401 Authorization Required along with:

    Authorization Required
    This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.

    Apache/2.2.3 (CentOS) Server Port 80

    Seeing this is an Apachie server, can you tell me why it is not processing the password? FYI I direct dial into my ISP using WindowsXP, Intrernet Explorer 8. This is the first time I've encountered this issue but recognized from the php code example provided it has something to do with htaccess.

  • Tony

    Thanks, super useful!

    Under "Using AddHandler" you say: Then every time somebody access a file that ends in .html it will execute the php script secure.php. Now you just write a script that implements the security you need.

    My question is: How do we return to that file? It works, in that when I request test.htm it is displaying my auth.php output. But how do I write the auth.php to say "If the username is correct, display test.htm like normal"?


  • Bryant

    Alfred did you ever figure out how to do that? I'm running into similar issues myself.

  • gerry freed

    I have a site in which I am getting two classes of users to login with different access rights. That works fine for one class but the others need to get into an .htaccess protected file area and I want to bypass the Apache authentication form. I seem to hitting the same snags as the readers of this thread.

    Has anyone got some code that works that I can use without straining my tired brain too much?

Related Articles

My Online Tools
Popular Articles

Hacking and Hackers

The use of "hacker" to mean "security breaker" is a confusion on the part of the mass media. We hackers refuse to recognize that meaning, and continue using the word to mean someone who loves to program, someone who enjoys playful cleverness, or the combination of the two. See my article, On Hacking.
-- Richard M. Stallman


It's very simple - you read the protocol and write the code. -Bill Joy

Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution 3.0 License, just credit with a link.
This site is not supported or endorsed by The Apache Software Foundation (ASF). All software and documentation produced by The ASF is licensed. "Apache" is a trademark of The ASF. NCSA HTTPd.
UNIX ® is a registered Trademark of The Open Group. POSIX ® is a registered Trademark of The IEEE.

+Askapache | askapache

Site Map | Contact Webmaster | License and Disclaimer | Terms of Service

↑ TOPMain