1

In my .htaccess file, I have:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
require valid-user

<Files .htaccess>
deny from all 
</Files>

and the .htpasswd file has a valid user/password.

When I go to a PHP file, I need to get the username that was used to access the page. The PHP is accessed ok, so I know the user/pass are working, but I can't seem to get the username extracted.

I have tried both $_SERVER['REMOTE_USER'] and $_SERVER['PHP_AUTH_USER'], but both are empty. How can I make this work?

2 Answers 2

2

There are different ways PHP can store the username, so maybe give something like this a try.

<?php

$username_extracted = retrieve_php_username();

function retrieve_php_username() {
  $username = '';
  // Try to get the login name from the $_SERVER variable.
  if (isset($_SERVER['HTTP_AUTHORIZATION']) || isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
    $authorization_header = '';
    if (isset($_SERVER['HTTP_AUTHORIZATION']) && !empty($_SERVER['HTTP_AUTHORIZATION'])) {
      $authorization_header = $_SERVER['HTTP_AUTHORIZATION'];
    }
    // If using CGI on Apache with mod_rewrite, the forwarded HTTP header appears in the redirected HTTP headers.
    elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && !empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
      $authorization_header = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
    }
    // Resemble PHP_AUTH_USER and PHP_AUTH_PW for a Basic authentication from
    // the HTTP_AUTHORIZATION header. See http://www.php.net/manual/features.http-auth.php
    if (!empty($authorization_header)) {
      list($username_temp, $userpass_temp) = explode(':', base64_decode(substr($authorization_header, 6)));
      $username = $username_temp;
    }
  }
  // Check other possible values in different keys of the $_SERVER superglobal
  elseif (isset($_SERVER['REDIRECT_REMOTE_USER'])) {
    $username = $_SERVER['REDIRECT_REMOTE_USER'];
  }
  elseif (isset($_SERVER['REMOTE_USER'])) {
    $username = $_SERVER['REMOTE_USER'];
  }
  elseif (isset($_SERVER['REDIRECT_PHP_AUTH_USER'])) {
    $username = $_SERVER['REDIRECT_PHP_AUTH_USER'];
  }
  elseif (isset($_SERVER['PHP_AUTH_USER'])) {
    $username = $_SERVER['PHP_AUTH_USER'];
  }
  return $username;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Solved. I had an override in .htaccess to run php 5.5 and it was running under CGI which prevented pass-through of the authorization variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.