Digest認証のパスワードファイルを作成するphpスクリプト

php IT Tips

通常、レンタルサーバ等では管理画面よりBasic認証に必要なためのファイルを作ることが出来ますが
Basic認証よりセキュアなDigest認証を公式にサポートしていないサーバが多いと思います。
然しSSHがない環境でも、phpでDigest認証のパスワードを作ることが出来ます。

Digest認証については、Basic認証よりセキュアなDigest認証を使う方法を参照のこと。

下記PHPは取扱に注意すること。

# /path/to/htdigest.php
#!/usr/bin/php
<?php
/*
 * This script is create Digest Authentication files.
 */

// ".htdigest"'s path
$path = "/path/to/.htdigest";

// Common realms
$realm = array(
    0 => "This contents can join at Administrators only.",
    1 => "Members only.",
);
 
// Login users setting
$users = array(
    0=>array(
        "name"     => "admin",
        "realm"    => $realm[0],
        "password" => "adminpassword",
    ),
    1=>array(
        "name" => "member",
        "realm" => $realm[1],
        "password" => "memberpassword",
    ),
);
 // Create Crypted password
foreach ($users as $val)
{
    $put[] = sprintf('%s:%s:%s',$val["name"],$val["realm"],md5(sprintf('%s:%s:%s',$val["name"],$val["realm"],$val["password"])));
}

// Create .htdigest
$fp = @fopen($path,"w");
@($fp,implode("\n",$put)."\n");
@fclose($fp);

.htaccessによる認証の分け方+Digest認証の設定方法
# Administrator's contents
<Location "/members/admin">
    AuthType Digest
    AuthName "This contents can join at Administrators only."
    AuthUserFile /path/to/.htdigest
    Require valid-user
</Location>

# Members's contents
<Location "/members/public">
    AuthType Digest
    AuthName "Members only."
    AuthUserFile /path/to/.htdigest
    Require valid-user
</Location>

コメント

タイトルとURLをコピーしました