Ben
Ben

Reputation: 68648

Getting basic-auth username in php

How can I access the apache basic-auth username in a PHP script?

Upvotes: 20

Views: 30574

Answers (4)

domsson
domsson

Reputation: 4681

It would seem that the location depends on the server in use:

  • $_SERVER["REMOTE_USER"] - CGI standard
  • $_SERVER["PHP_AUTH_USER"] - APACHE
  • $_SERVER["AUTH_USER"] - IIS

Upvotes: 3

Phil
Phil

Reputation: 595

At my clients hoster $_SERVER['PHP_AUTH_USER'] and $_SERVER["HTTP_AUTHORIZATION"] were empty but $_SERVER["REMOTE_USER"] was set!

if ($_SERVER["REMOTE_USER"] == "admin")
    echo "Welcome, admin!";
else
    echo "Access denied";

Upvotes: 1

Alexandar Penkin
Alexandar Penkin

Reputation: 76

Check what you have in $_SERVER (print_r($_SERVER)), sometimes $_SERVER['PHP_AUTH_USER'] is not available.

If you have value for $_SERVER["HTTP_AUTHORIZATION"], you may use:

if (isset($_SERVER["HTTP_AUTHORIZATION"]) {
        $auth = $_SERVER["HTTP_AUTHORIZATION"];
        $auth_array = explode(" ", $auth);
        $un_pw = explode(":", base64_decode($auth_array[1]));
        $un = $un_pw[0];
        $pw = $un_pw[1];
    }

(copied from https://www.codepunker.com/blog/php-a-primer-on-the-basic-authorization-header)

Upvotes: 4

William Entriken
William Entriken

Reputation: 39313

Simply access this variable:

$_SERVER['PHP_AUTH_USER']

Upvotes: 20

Related Questions