|
Posted by Jeremy on 10/17/07 22:56
Jeremy wrote:
> David Hennessy wrote:
>> Jeremy wrote:
>>> David Hennessy wrote:
>>>> Hi! Is there any way to limit the number of retries when using HTTP
>>>> authentication in PHP?
>>>>
>>>
>>> Despite what everyone else says, this is possible with PHP (though
>>> not with Apache's built-in HTTP authentication, AFAIK).
>>>
>>> Read this:
>>>
>>> http://us2.php.net/manual/en/features.http-auth.php
>>>
>>> The idea is that when the user first tries to access the document,
>>> you send an HTTP 401 header. At this point, you can also keep track
>>> of this as an "attempt" in whatever fashion you like (local database
>>> of IP addresses, for example). Now, each time the user types a new
>>> password you'll check it, and if it's wrong you'll send another 401
>>> header. Keep track of how many times this happens, and if the number
>>> of attempts exceeds your limit, send a 403 (forbidden) instead of a 401.
>>
>>
>> Hi Jeremy,
>>
>> Do you have a reference or an example to demonstrate this? I've
>> extensively consulted the URL you referenced, and don't see anything
>> to suggest the functionality you're describing. From my own tests, it
>> appears that the authentication challenge pop-up does not return to
>> the PHP script until the user either enters a correct password or hits
>> "cancel" -- so there's no place to interrupt until the authentication
>> bit is done. Am I misunderstanding?
>>
>
> Yes, you are misunderstanding. Every time you enter a password, whether
> it's correct or not, it is sent to the PHP script for validation.
>
> Here's some pseudocode, using a session cookie to track number of
> retries (which in practice, you probably shouldn't do):
>
> <?php //to make all the longtag pundits happy
>
> // again, you probably shouldn't use a session mechanism
> // for counting retries
> session_start();
>
>
> // the $_SERVER keys for authentication only work under mod_php
> // valid_user is a hypothetical function that checks the l/p
> if(!valid_user($_SERVER["PHP_AUTH_USER"],
> $_SERVER["PHP_AUTH_PW"]))
> {
> // limit to 15 tries
> if((++$_SESSION["login_attempts"]) > 15)
> {
> header("HTTP/1.1 403 Forbidden");
> // show error document here if you wish
> }
> else
> {
> header("HTTP/1.1 401 Authorization Required");
> }
>
> die;
> }
>
> // if your code makes it here, it should be a valid user
> // so output your document.
> ?>
Oops - you also need the "WWW-Authenticate" header after the 401 header.
Check the PHP document link for details on that.
Jeremy
[Back to original message]
|