. Htgroup file example:
Admin: user2
Editor: user1 user3
Writer: user3
Copy codeThe Code is as follows:
Class Htgroup {
Private $ file = '';
Private function write ($ groups = array ()){
$ Str = '';
Foreach ($ groups as $ group => $ users ){
$ Users_str = '';
Foreach ($ users as $ user ){
If (! Empty ($ users_str )){
$ Users_str. = '';
}
$ Users_str. = $ user;
}
$ Str. = "$ group: $ users_str \ n ";
}
File_put_contents ($ this-> file, $ str );
}
Private function read (){
$ Groups = array ();
$ Groups_str = file ($ this-> file, FILE_IGNORE_NEW_LINES );
Foreach ($ groups_str as $ group_str ){
If (! Empty ($ group_str )){
$ Group_str_array = explode (':', $ group_str );
If (count ($ group_str_array) = 2 ){
$ Users_array = explode ('', $ group_str_array [1]);
$ Groups [$ group_str_array [0] = $ users_array;
}
}
}
Return $ groups;
}
Public function _ construct ($ file ){
If (file_exists ($ file )){
$ This-> file = $ file;
} Else {
Die ($ file. "doesn't exist .");
Return false;
}
}
Public function addUserToGroup ($ username = '', $ group = ''){
If (! Empty ($ username )&&! Empty ($ group )){
$ All = $ this-> read ();
If (isset ($ all [$ group]) {
If (! In_array ($ username, $ all [$ group]) {
$ All [$ group] [] = $ username;
}
} Else {
$ All [$ group] [] = $ username;
}
$ This-> write ($ all );
} Else {
Return false;
}
}
Public function deleteUserFromGroup ($ username = '', $ group = ''){
$ All = $ this-> read ();
If (array_key_exists ($ group, $ all )){
$ User_index = array_search ($ username, $ all [$ group]);
If ($ user_index! = False ){
Unset ($ all [$ group] [$ user_index]);
If (count ($ all [$ group]) = 0 ){
Unset ($ all [$ group]);
}
$ This-> write ($ all );
}
} Else {
Return false;
}
}
}
Copy codeThe Code is as follows:
$ GroupHandler = new Htgroup ('/home/myuser/. htgroup ');
// Add user 'user1' to group 'admin' in. htgroup. Group will be automatically created if it doesn' t exist.
$ GroupHandler-> addUserToGroup ('user1', 'admin ');
// Delete user 'user1' from group 'admin' in. htgroup. Group will be automatically removed if it doesn' t contain any users.
$ GroupHandler-> deleteUserFromGroup ('user1', 'admin ');