Posted By

tylerhall on 11/30/-1


Tagged

authorize basic http login


Versions (?)

Who likes this?

27 people have marked this snippet as a favorite

daniel
luman
Roshambo
nex
jkochis
kawikak
mafro
funkyD
bitcrumb
vali29
hudge
willcodeforfood
benrasmusen
damarev
tzangms
JimiJay
jachin
SpinZ
romanos
joaosalless
salibaray
silentbob84
osirisinternet
bobbym245
mecha
tspitzr
ringo380


Authorize with basic HTTP using PHP


 / Published in: PHP
 

  1. function http_auth($un, $pw, $realm = "Secured Area")
  2. {
  3. if(!(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_USER'] == $un && $_SERVER['PHP_AUTH_PW'] == $pw))
  4. {
  5. header('WWW-Authenticate: Basic realm="$realm"');
  6. header('Status: 401 Unauthorized');
  7. exit(); //???
  8. }
  9. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: jachin on February 11, 2008

hi there

I like this function however I would change it to:

<function http_auth ($un, $pw, $realm = "Secured Area" ) { if ( ! ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) && $_SERVER['PHP_AUTH_USER'] == $un && $_SERVER['PHP_AUTH_PW'] == $pw ) ) { header( 'WWW-Authenticate: Basic realm="' . $realm . '"' ); header( 'Status: 401 Unauthorized' ); exit( 0 ); } }>

Posted By: jachin on February 11, 2008

Or even better function http_auth ($username, $password, $realm = "Secured Area" ) {

    if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
        if ( $_SERVER['PHP_AUTH_USER'] === $username && $_SERVER['PHP_AUTH_PW'] === $password ) {
            return true;
        }
    }
    header( 'WWW-Authenticate: Basic realm="' . $realm . '"' );
    header( 'Status: 401 Unauthorized' );
    exit( 0 );
}

More lines of code, but I find it a bit more readable.

You need to login to post a comment.