LoginSignup
9
15

More than 5 years have passed since last update.

PHPでBASIC認証

Last updated at Posted at 2016-10-02

無料でSSL証明書の取得が簡単になった今、ひょっとしてBASIC認証の仕組みって意外と便利に使えるのではないでしょうか。Railsと同じ要領で使えるメソッドを書いてみました。

function http_basic_authenticate_with($name,$password,$realm = "Protected area"){
  if (!isset($_SERVER['PHP_AUTH_USER']) || !($_SERVER['PHP_AUTH_USER'] == $name && $_SERVER['PHP_AUTH_PW'] == $password )) {
    header('WWW-Authenticate: Basic realm="'.$realm.'"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Not allowed to access.';
    exit;
  }
}

PHPスクリプトの先頭に記述するとBASIC認証が必要なページになります。

http_basic_authenticate_with("user","pass");  

客先へのプレビューの際や、ちょっとした管理機能の運用なんかには必要十分かと思います。ソースコードにパスワードが残ると困る場合は、「$_ENV」などを使って外部の値を渡す方法もあります。

参考URL

9
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
15