We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

tylerhall on 12/31/69


Tagged

authorize basic http login


Versions (?)


Who likes this?

19 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


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.