Search code examples
phpbasic-authentication

PHP basic auth doesn't work


I am trying to implement small API and for this I must check user's API keys with basic auth, but for some reason even simplest example doesn't work:

<?php

include '../config.inc.php';

$user = $_SERVER['PHP_AUTH_USER'];    
$validated = false;
if( $user == $api_key );
    $validated = true;
if (!$validated) {
  header('WWW-Authenticate: Basic realm="API"');
  header('HTTP/1.0 401 Unauthorized');
  exit ("Not authorized");
}

and I think that the problem is that I'am using mod_rewrite for accessing api itself (different api modules are included depends on what page have been accessed), here it is:

RewriteEngine On
RewriteBase /my_admin/api/
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^(.*)$ index.php

When accessing index.php I got this error:

Notice: Undefined index: PHP_AUTH_USER in C:\xampp\htdocs\my_admin\api\index.php on line 5

However, on the upper folder it works fine. What could cause this problem and how to solve the issue? Thank you.


Solution

  • There are a few issues in your code. First you need to check if you actually got the user:

    $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : null;
    

    Then your if statement doesn't do anything and $validated will always be true. To resolve this, remove the semi-colon:

    if($user && $user == $api_key ) $validated = true;
    

    Or even better:

    $validated = $user && $user == $api_key
    

    Also don't check with isset since the variable is definitely set, just check that it's non-null as in my change above.