Skip to content

Instantly share code, notes, and snippets.

@hbackman
Created September 9, 2021 17:50
Show Gist options
  • Save hbackman/06216c5b0704248a15d24cf65fcf68dc to your computer and use it in GitHub Desktop.
Save hbackman/06216c5b0704248a15d24cf65fcf68dc to your computer and use it in GitHub Desktop.
PSR Compliant Basic Auth Decode
<?php
/**
* Get the HTTP Basic Auth information from the request.
*
* @param ServerRequestInterface $request
*
* @return array
*/
function getBasicAuth(ServerRequestInterface $request): array
{
$header = $request->getHeader('authorization');
$header = reset($header);
preg_match("/^Basic (.*)$/", $header, $matches);
if (count($matches) <= 1) {
return [
'username' => null,
'password' => null
];
}
$token = $matches[1];
$token = base64_decode($token);
[ $username,
$password ] = explode(':', $token);
return compact('username', 'password');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment