当前位置:Gxlcms > PHP教程 > 用来解析.htpasswd文件的PHP类

用来解析.htpasswd文件的PHP类

时间:2021-07-01 10:21:17 帮助过:16人阅读

.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. }

人气教程排行