用来解析 .htpasswd 文件的 PHP 类

原创
2016-07-25 09:05:01 541浏览
.htpasswd 文件示例:

user1:{SHA}kGPaD671VNU0OU5lqLiN/h6Q6ac=
user2:{SHA}npMqPEX3kPQTo+x/+ZckHDrIcQI=
user3:{SHA}q1Fh2LTUjjkncp11m0M9WUH5Zrw=
  1. class Htpasswd {
  2. private $file = '';
  3. private $salt = 'AynlJ2H.74VEfI^BZElc-Vb6G0ezE9a55-Wj';
  4. private function write($pairs = array()) {
  5. $str = '';
  6. foreach ($pairs as $username => $password) {
  7. $str .= "$username:{SHA}$password\n";
  8. }
  9. file_put_contents($this -> file, $str);
  10. }
  11. private function read() {
  12. $pairs = array();
  13. $fh = fopen($this -> file, 'r');
  14. while (!feof($fh)) {
  15. $pair_str = str_replace("\n", '', fgets($fh));
  16. $pair_array = explode(':{SHA}', $pair_str);
  17. if (count($pair_array) == 2) {
  18. $pairs[$pair_array[0]] = $pair_array[1];
  19. }
  20. }
  21. return $pairs;
  22. }
  23. private function getHash($clear_password = '') {
  24. if (!empty($clear_password)) {
  25. return base64_encode(sha1($clear_password, true));
  26. } else {
  27. return false;
  28. }
  29. }
  30. public function __construct($file) {
  31. if (file_exists($file)) {
  32. $this -> file = $file;
  33. } else {
  34. die($file." doesn't exist.");
  35. return false;
  36. }
  37. }
  38. public function addUser($username = '', $clear_password = '') {
  39. if (!empty($username) && !empty($clear_password)) {
  40. $all = $this -> read();
  41. if (!array_key_exists($username, $all)) {
  42. $all[$username] = $this -> getHash($clear_password);
  43. $this -> write($all);
  44. }
  45. } else {
  46. return false;
  47. }
  48. }
  49. public function deleteUser($username = '') {
  50. $all = $this -> read();
  51. if (array_key_exists($username, $all)) {
  52. unset($all[$username]);
  53. $this -> write($all);
  54. } else {
  55. return false;
  56. }
  57. }
  58. public function doesUserExist($username = '') {
  59. $all = $this -> read();
  60. if (array_key_exists($username, $all)) {
  61. return true;
  62. } else {
  63. return false;
  64. }
  65. }
  66. public function getClearPassword($username) {
  67. return strtolower(substr(sha1($username.$this -> salt), 4, 12));
  68. }
  69. }
复制代码
  1. $passwdHandler = new Htpasswd('/home/myuser/.htpasswd');
  2. // Add a user with name 'user1' and password 'I prefer to use passphrase rather than password.' if it doesn't exist in .htpasswd.
  3. $passwdHandler -> addUser('user1', 'I prefer to use passphrase rather than password.');
  4. // Delete the user 'user1' if it exists in .htpasswd.
  5. $passwdHandler -> deleteUser('user1');
  6. // Check if user 'user1' exists in .htpasswd.
  7. if ($passwdHandler -> doesUserExist('user1')) {
  8. // User 'user1' exists.
  9. }
复制代码


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:最最最简单的模板引擎:PHP原生模板引擎 下一条:php的多语言解决方案

相关文章

查看更多