Forum Moderators: coopster

Message Too Old, No Replies

Help me for I am but a fool: Server authorization woes

Pressing cancel gets you into restricted area.

         

fwordboy

9:56 am on Feb 26, 2004 (gmt 0)

10+ Year Member



Heres my code (obviously i've changed the username and the password). It pops up the username/password prompt and typing in the correct username and password gets you into the site but simply pressing cancel gets you in there as well, help me.

<?php
$dbh=mysql_connect ("localhost", "db_username", "db_password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("db_name");


$authorized = FALSE;

if ((isset($_SERVER['PHP_AUTH_USER']) AND isset($_SERVER['PHP_AUTH_PW'])) ) {

$query ="SELECT username FROM users WHERE username='{$_SERVER['PHP_AUTH_USER']}' and
password='{$_SERVER['PHP_AUTH_PW']}'";

$result = mysql_query ($query);
$row = @mysql_fetch_array ($result);
if ($row) {
$authorized = TRUE;
}

}

if (!$authorized){
header('WWW-Authenticate: Basic realm="localhost"');
header('HTTP/1.0 401 Unauthorized');
}

?>
<html>
etc
</html>

mykel79

11:05 am on Feb 26, 2004 (gmt 0)

10+ Year Member



I'm not sure, but it might be that mysql_fetch_array returns an empty array when there is no result (and not NULL).
Try this:
if ($row['username']!='') {

instead of
if ($row) {

Also, you have to be very careful when doing logins. It migh be better to do it like this:

$query ="SELECT username, password FROM users WHERE username='{$_SERVER['PHP_AUTH_USER']}' and
password='{$_SERVER['PHP_AUTH_PW']}'";
$result = mysql_query ($query);
$row = @mysql_fetch_array ($result);
IF (($row['username']==$_SERVER['PHP_AUTH_USER']) && ($row['password']==$_SERVER['PHP_AUTH_PW'])) {
.
.

Why? Well, if the user can get this string:
' or password like='%

to be accepted as the password and username1 as the user, then you would be in trouble. The query would look like this:
SELECT username FROM users WHERE username='username1' and
password='' or password like '%'

The way you have the code now, this would always let him login as username1.

fwordboy

4:13 pm on Feb 26, 2004 (gmt 0)

10+ Year Member



thanks for the response but none of your suggestions help.

jatar_k

6:26 pm on Feb 26, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The thing that I don't really understand what steps are going here.

Do you have apache protecting the dir via htaccess?

Netizen

7:31 pm on Feb 26, 2004 (gmt 0)

10+ Year Member



I think you need an exit call in your if:

if (!$authorized){
header('WWW-Authenticate: Basic realm="localhost"');
header('HTTP/1.0 401 Unauthorized');
exit;
}