当前位置: 网学 > 编程文档 > PHP > 正文

用来解析.htpasswd文件的PHP类

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/06/18

网学网为广大网友收集整理了,用来解析.htpasswd文件的PHP类,希望对大家有所帮助!

.htpasswd 文件示例:
user1:{SHA}kGPaD671VNU0OU5lqLiN/h6Q6ac=
user2:{SHA}npMqPEX3kPQTo+x/+ZckHDrIcQI=
user3:{SHA}q1Fh2LTUjjkncp11m0M9WUH5Zrw=
复制代码 代码如下:
class Htpasswd {
private $file = '''';
private $salt = ''AynlJ2H.74VEfI^BZElc-Vb6G0ezE9a55-Wj'';
private function write($pairs = array()) {
$str = '''';
foreach ($pairs as $username => $password) {
$str .= "$username:{SHA}$password\n";
}
file_put_contents($this -> file, $str);
}
private function read() {
$pairs = array();
$fh = fopen($this -> file, ''r'');
while (!feof($fh)) {
$pair_str = str_replace("\n", '''', fgets($fh));
$pair_array = explode('':{SHA}'', $pair_str);
if (count($pair_array) == 2) {
$pairs[$pair_array[0]] = $pair_array;
}
}
return $pairs;
}
private function getHash($clear_password = '''') {
if (!empty($clear_password)) {
return base64_encode(sha1($clear_password, true));
} else {
return false;
}
}
public function __construct($file) {
if (file_exists($file)) {
$this -> file = $file;
} else {
die($file." doesn''t exist.");
return false;
}
}
public function addUser($username = '''', $clear_password = '''') {
if (!empty($username) && !empty($clear_password)) {
$all = $this -> read();
if (!array_key_exists($username, $all)) {
$all[$username] = $this -> getHash($clear_password);
$this -> write($all);
}
} else {
return false;
}
}
public function deleteUser($username = '''') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
unset($all[$username]);
$this -> write($all);
} else {
return false;
}
}
public function doesUserExist($username = '''') {
$all = $this -> read();
if (array_key_exists($username, $all)) {
return true;
} else {
return false;
}
}
public function getClearPassword($username) {
return strtolower(substr(sha1($username.$this -> salt), 4, 12));
}
}

使用方法
复制代码 代码如下:
$passwdHandler = new Htpasswd(''/home/myuser/.htpasswd'');
// Add a user with name ''user1'' and password ''I prefer to use passphrase rather than password.'' if it doesn''t exist in .htpasswd.
$passwdHandler -> addUser(''user1'', ''I prefer to use passphrase rather than password.'');
// Delete the user ''user1'' if it exists in .htpasswd.
$passwdHandler -> deleteUser(''user1'');
// Check if user ''user1'' exists in .htpasswd.
if ($passwdHandler -> doesUserExist(''user1'')) {
// User ''user1'' exists.
}

网学推荐

免费论文

原创论文

浏览:
设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
湘ICP备09003080号