axy/htpasswd

与 htpasswd 文件一起工作

2.0.0 2023-03-18 20:38 UTC

This package is auto-updated.

Last update: 2024-09-19 13:34:18 UTC


README

与 htpasswd 文件一起工作(PHP)。

Latest Stable Version Minimum PHP Version Tests Coverage Status License

文档

该库提供了用于操作 htpasswd 文件的程序 API(有关控制台实用程序,请参阅 axypro/htpasswd-cli)。

use axy\htpasswd\PasswordFile;

$file = new PasswordFile('/path/to/.htpasswd');
$file->setPassword('nick', 'password');
$file->setPassword('john', '123456');
$file->save();

当前支持的以下算法(PasswordFile::* 的常量)

  • ALG_MD5:Apache APR1-MD5 算法(默认值)
  • ALG_BCrypt:Blowfish
  • ALG_SHA1:SHA-1
  • ALG_CRYPT:crypt(unix)
  • ALG_PLAIN:纯文本(在某些平台上的服务器不支持)。
__construct([string $filename])

构造函数接受 htpasswd 文件名称。

NULL:控制台实用程序的选项 -n 的类似物

$file = new PasswordFile();
$file->setPassword('nick', 'password');
$file->getContent(); // out of the "file" content

$file->save(); // Exception FileNotSpecified
setPassword(string $user, string $password [, string $algorithm, [array $options]): bool

为用户 $user 设置密码 $password。使用 $algorithm 进行散列(默认为 Apache MD5)。

$options 是散列选项的数组。仅支持 BCrypt 的 cost(范围在 4 到 31 之间的整数)

如果已创建新用户,则返回 TRUE。如果已更改现有用户的密码,则返回 FALSE

remove(string $user): bool

从文件中删除用户。如果已删除用户,则返回 TRUE。如果找不到用户,则返回 FALSE

verify(string $user, string $password): bool

如果 $user 存在并且密码为 $password,则返回 TRUE

isUserExist(string $user): bool

如果文件中存在用户,则返回 TRUE

if (!$file->isUserExist('john')) {
    echo 'John? I do not known you.';
    exit();
}
if (!$file->verify('john', 'password')) {
    echo 'You are not John! You are an impostor!';
    exit();
}
echo 'Hello, John';
getContent(void): string

返回文件内容(不保存)。

save(void): void

将内容保存到文件中(如果指定)。

htpasswd 实用程序相比(请参阅选项 -c),现有文件始终更改(不会覆盖)。如果不存在,则创建文件。

setFileName(string $filename): void

设置新的文件名。将加载旧文件的内容并将其保存到新文件中(在 save() 之后)。

getFileName(void): string

返回当前指定的文件名。

异常

axy\htpasswd\errors 命名空间中。

  • InvalidFileFormat:密码文件格式无效。
  • FileNotSpecified:如果构造函数中没有指定文件,则从 save() 抛出。