rikudou / http-basic-auth
无需框架的简单HTTP基本认证
v1.0
2017-05-16 13:18 UTC
This package is auto-updated.
Last update: 2024-09-07 02:38:16 UTC
README
此模块无需任何框架,非常简单。
安装
composer require rikudou/http-basic-auth
使用
<?php use Rikudou\HttpBasicAuth; // message displayed in standard browser window $message = "Please input your username and password!"; // add the message to the object $auth = new HttpBasicAuth($message); // set the callback, it accepts two parameters, username and password and should // return true (auth succeeded) or false (auth failed) // in callback you can do pretty much everything, connect to your db, call classes, etc. // the callback can be any callable (see https://php.ac.cn/manual/en/language.types.callable.php) $auth->setCallback(function($username, $password) { if($username == "foo" && $password == "bar") { return true; } return false; }); $result = $auth->auth(); if($result) { // auth succeeded } else { // auth failed }
回调也可以在构造函数中设置
<?php use Rikudou\HttpBasicAuth; $auth = new HttpBasicAuth("Please, authorize", function($username, $password){ return true; });
当未提供回调或回调不可调用时,auth()
方法可能会抛出异常。
<?php use Rikudou\HttpBasicAuth; $auth = new HttpBasicAuth("Authorize"); try { $auth->auth(); } catch (Exception $exception) { var_dump($exception->getCode() == HttpBasicAuth::ERR_NO_CALLBACK); // true } $auth->setCallback(1); // invalid callback try { $auth->auth(); } catch (Exception $exception) { var_dump($exception->getCode() == HttpBasicAuth::ERR_CALLBACK_NOT_CALLABLE); // true }