Created
September 4, 2022 13:29
-
-
Save idokd/91a47db2d7ac6ea2d4da422a7a5268f2 to your computer and use it in GitHub Desktop.
PHP Basic Authentication Header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$realm = 'My Realm Name'; | |
//user => password | |
$users = [ 'user1' => 'pass1', 'user2' => 'pass2' ]; | |
$authenticated = !empty( $_SERVER[ 'PHP_AUTH_DIGEST' ] ); | |
if ( $authenticated && !( $data = http_digest_parse( $_SERVER[ 'PHP_AUTH_DIGEST' ] ) ) || !isset( $users[ $data[ 'username' ] ] ) ) { | |
$authenticated = false; | |
} else { | |
// generate the valid response | |
$A1 = md5( $data[ 'username' ] . ':' . $realm . ':' . $users[ $data[ 'username' ] ] ); | |
$A2 = md5( $_SERVER[ 'REQUEST_METHOD' ] . ':' . $data[ 'uri' ] ); | |
$valid_response = md5( $A1 . ':' . $data[ 'nonce' ] . ':' . $data[ 'nc' ] . ':' . $data[ 'cnonce' ] . ':' . $data[ 'qop' ] . ':' . $A2 ); | |
if ( $data[ 'response' ] != $valid_response ) $authenticated = false; | |
} | |
if ( !$authenticated ) { | |
header( 'HTTP/1.1 401 Unauthorized' ); | |
header( 'WWW-Authenticate: Digest realm="' . $realm . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5( $realm ) . '"' ); | |
die( 'Text to send if user hits Cancel button' ); | |
} | |
// Whatever is here, will shown if user is authenticated. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment