devling
devling

Reputation: 301

How about failed attempts for htaccess password protected directories

This question is related to a previous question I asked, but it's a different.

I'm using htaccess to control login to http://somesite.com/folder.

Once logged in, I have php code in folder/index.php to check the username and password used to login: $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW']. I log that info to a database.

This works when the user supplies a good username and password, but when it's incorrect, nothing happens - I suppose because /index.php is never reached.

Is there a way to login also failed login attempts?

Upvotes: 3

Views: 3582

Answers (2)

Artefacto
Artefacto

Reputation: 97835

EDIT

There's a simple way to do it. In your .htaccess, add

ErrorDocument 401 /path/to/log.php

This log.php is then called when a login attempt fails (you can put it behind the protected directory as well, it will be reached even though the login fails). Note that the browser doesn't know whether some resource needs authentication, so you'll always get a hit for the first attempt. These attempts, however, will not include any username and you can detect them (well, you can distinguish them from when the user enters no username, but you get the idea) by checking whether $_SERVER['PHP_AUTH_USER'] is empty.

Original

Well, no, as you say /index.php is never reached.

What you can do is not to rely on Apache at all and handle the authentication only with PHP. This manual page shows you how. This has a big disadvantage. Let's say you protected an entire directory. This directory has PHP files, images and whatnot. Now, to enforce the authentication, you must route everything through a PHP file. If you had only PHP files, you could do it with an include. If you have static contented, you must route it with a rewrite-rule through a PHP files that reads and outputs the static content, which will hurt the performance.

Upvotes: 4

joeynelson
joeynelson

Reputation: 405

If your goal is to lock out users who repeatedly fail authentication, you could keep using Apache basic auth and just install fail2ban. Set it and forget it!

Upvotes: 1

Related Questions