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.