0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[PHP]ベーシック認証の実装

Posted at

はじめに

Railsを学んでいるときにも実装したBasic認証について、PHPでも同様にやってみようと思います。

実装

やり方はとても簡単です。以下の2つのファイルを作成してください。

  • .htaccess
  • .htpasswd

次に、以下のようにmainte.phpを作成してください(パスワードの暗号化で使用します)。

mainte.php
<?php

//パスワードの暗号化
echo(password_hash('password123',PASSWORD_BCRYPT));
//$2y$10$gcXSxuDRPEbIAL5chj/hZOY.xmx7dm56pnZBIktVR.FMuk7AFjLfm
?>

もちろん設定ファイルにパスワードをそのまま記載するのはもってのほかです!
そのため、上記のように、password_hashを使用してパスワードの暗号化を行います。
今回は、パスワード「password123」を設定してます。

次に、Basic認証の設定をしていきます。
Basic認証を実装するには、以下のようにAuthType Basicとします。

.htaccess
AuthType Basic
AuthName "IDとパスワードを入力してください"
AuthUserFile /Applications/MAMP/htdocs/php_test/.htpasswd
require valid-user

次に、.htpasswdに、許可するユーザを登録します。
この際に、先ほど暗号化したパスワードをユーザ名とセットで記載してやります。

.htpasswd
admin:$2y$10$gcXSxuDRPEbIAL5chj/hZOY.xmx7dm56pnZBIktVR.FMuk7AFjLfm

これで全て設定は完了です。
再度アクセスしてみましょう!以下の画面が出てこれば成功です!

スクリーンショット 2021-05-31 14.32.16.png

おわりに

Railsの時とは全く違う方法での実装の仕方でした。こうした違いについて気をつけながら学んでいこうと思います!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?