ラボ > PHP:PATHやURL関連

PHPでBASIC認証

作成日:2018-01-24, 更新日:2018-02-14

サンプル

function iniBasicAuth() {
   header("WWW-Authenticate: Basic realm=\"Enter your account.\"");
   header("HTTP/1.0 401 Unauthorized");
   
   //キャンセル時の表示
   echo "Authorization Required";
   exit;
}

$id = "id_zebra";
$pw = "pw_zebra";

$isAuth = false;
if (!empty($_SERVER["PHP_AUTH_USER"]) && !empty($_SERVER["PHP_AUTH_PW"])) {
   if ($_SERVER["PHP_AUTH_USER"]===$id && $_SERVER["PHP_AUTH_PW"]===$pw) {
      // 認証成功
      $isAuth = true;
   }
}

if ( $isAuth ) {
   echo "success";
}
else {
   // 
   iniBasicAuth();
}

関連項目

.htaccessでBASIC認証