{"id":16618505,"url":"https://github.com/dimo414/php-auth","last_synced_at":"2025-10-05T13:57:08.134Z","repository":{"id":155531045,"uuid":"234510626","full_name":"dimo414/php-auth","owner":"dimo414","description":"PHP Authentication project, page locking, username password lock, user manager","archived":false,"fork":false,"pushed_at":"2020-02-08T21:01:02.000Z","size":85,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-05-29T16:35:07.135Z","etag":null,"topics":["auth","php","user-management"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dimo414.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-01-17T09:01:20.000Z","updated_at":"2022-04-04T03:13:44.000Z","dependencies_parsed_at":"2024-05-21T04:00:38.813Z","dependency_job_id":null,"html_url":"https://github.com/dimo414/php-auth","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dimo414/php-auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimo414%2Fphp-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimo414%2Fphp-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimo414%2Fphp-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimo414%2Fphp-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dimo414","download_url":"https://codeload.github.com/dimo414/php-auth/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dimo414%2Fphp-auth/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267693478,"owners_count":24129133,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-29T02:00:12.549Z","response_time":2574,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","php","user-management"],"created_at":"2024-10-12T02:20:25.082Z","updated_at":"2025-10-05T13:57:08.022Z","avatar_url":"https://github.com/dimo414.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# UserManager\n\n*Version 1.5.0*\n\nThe UserManager class is a self-contained user management system, written in PHP. Include the class\nin your website, and you have with a few short lines of code a fully operational login system,\nincluding multiple user levels (default User, SuperUser, and Admin) and the ability to lock web\npages from users without appropriate permissions - similar to .htaccess and .htpassword locking,\nexcept integrated with your website rather than a series of intrusive 401 login prompts.\n\t\nThere are two versions, `XMLUserManager` and `MySQLUserManager`, both of which extend `UserManager`,\nand allow you to chose where your user information is stored.\n\n`XMLUserManager` is the original tool, providing user management in a lightweight XML file, without\nrequiring a database or any other configuration. `MySQLUserManager` is a newer variant which is\nbacked by a database and therefore supports larger numbers of users, and is ideal if your site is\nalready using a MySQL database.  Both classes implement the same interface therefore switching from\none to the other is as easy as changing which class you initialize.\n\n## Requirements\n\n`XMLUserManager` is functional with a default install of PHP5, a MySQL database is required to use `MySQLUserManager`, and the [`mysqli` database driver](http://php.net/manual/en/book.mysqli.php) is\nused to communicate with the database.\n\nPrimarily tested with [Uniform Server](http://www.uniformserver.com/).\n\n## Features\n\n* XML Backend: no database or setup required.\n* MySQL Backend: easy to setup, scales well.\n* Customizable user permission levels.\n* Customizable storage fields.\n* Integrates seamlessly with your website.\n* One function call locks a page to anyone without the proper permission.\n* Self contained user management page.\n* Add and maintain users yourself, or use the pre-built manager.\n\n### Potential Features\n\n* `ManageUsers` should be divided into separate pages in order to deal with larger user bases.\n  \n## Usage\n\nThis section describes how to use the class right out of the box.  As is, `UserManager` has four\nuser levels, Guest, User, Superuser, and Admin, and stores each user's username, password\n(encrypted), and level. In addition to this documentation the public functions in the `UserManager`\nprovide more specific implementation details.\n\n### Initialization\n\nUserManager uses PHP Sessions to store the current visitor's information.  So before anything else,\nyou must call `session_start()`.  Then create an instance of either the `XMLUserManager` class by\npassing the constructor the location of the XML file, or the `MySQLUserManager` class by passing a\n`mysqli` database connection, and the name of a table the class should work with.  If using the\n`XMLUserManager` be sure to specify a location outside the web root or hidden from public view. Even\nthough passwords are encrypted the XML file should not be world-readable.\n\t\n```\ninclude 'XMLUserManager.class.php';\nsession_start();\n$user = new XMLUserManager('users.xml');\n```\n\n```\ninclude 'MySQLUserManager.class.php';\nsession_start();\n$db = new mysqli(HOST,USER,PASS,DB);\n$user = new MySQLUserManager($db);\n```\n\t\nThat's all it takes to initialize the UserManager.  You should generally place these setup\ncommands in a common include file. For the remainder of this document, it will be assumed that\ncalling `include 'common.inc.php';` will call the lines of code above.\n\n#### Database Setup\n\nUsing `MySQLUserManager` requires slightly more setup than `XMLUserManager`, but it is still quite\nstraightforward.  The first time you construct the `UserManager` you will need to create the\nuser table. `MySQLUserManager` can generate the necessary `CREATE TABLE` query, which you can either\nprint and run manually, or have it invoke directly if the database connection has the appropriate\npermissions.\n\t\nIf the user on the connection passed to `MySQLUserManager` has `CREATE` permission you can call\n`createTable()`, this will execute the create command and construct the necessary table. Otherwise\nyou can call `echo createTableString();` to get the schema and invoke it yourself.\n\t\n`MySQLUserManager` cannot predict what data you may want to search by. Looking up by username and id\nare fast with the default command, but if you extend the class (more below) be aware that\n`lookupAttribute()` is only efficient when run against properly indexed data. Therefore you should\nmodify the table or the `CREATE` instruction as necessary - a decent rule of thumb would be to index\nany column you intend to search by, but `MySQLUserManager` does not eliminate the need for good\ndatabase layout.\n  \n### Creating Users\n\nThere are two different ways to create and manage your website's users. The first is through the\nbuilt-in `manageUsers()` UI and the second is manually, with `addUser()`, `modifyUser()`, and\n`deleteUser()`.\n  \nThe easiest way is to use the `manageUsers()` function, which generates a user-management page.\nPlace the following in a file (`admin.php` or something similar):\n\n```\n\u003c?php\ninclude 'common.inc.php';\n// IMPORTANT - set this to false once you've created an administrator account\n// so that only admins can manage users. When true the manageUsers UI is\n// accessible to all visitors.\n$user-\u003emanageUsers(true);\n?\u003e\n```\n  \nThis will generate a form to modify existing users and add additional users. If you don't have any\nusers created already you will just see three empty slots to create new users. The `true` parameter\npassed to `manageUsers()` above overrides the protection built into the function - normally if you\nare not logged in as an Administrator, you will not be able to access the user management page.\nSince you haven't created any administrator accounts yet you need to override this lock.\n\nIMPORTANT: make sure to remove the parameter to `manageUsers()` before a live launch of your site.\nIf override is not set, `manageUsers()` is safe from unauthorized access.\n  \nThe second way to work with users is manually.  This would primarily be used if you have your own\nregister page for users to register themselves.\n  \nBy calling `addUser(\"USERNAME\", \"PASSWORD\", UserManager::ADMIN, array());` where USERNAME and\nPASSWORD are your desired username and password, you will create a new user with ADMIN level\npermissions.  (the other default user levels are `UserManager::USER` and `UserManager::SUPERUSER`.  `UserManager::GUEST` also exists, but should not be used to create a user).  `addUser()` can be\nintegrated with your own registration page by doing any error checks you want to make and then\npassing the registration information straight to `addUser()`.  addUser() will return false if the\nusername already exists, and will otherwise register the user.\n\nFor `XMLUserManager`, if you plan on calling `addUser()` more than once per execution add an\nadditional parameter, `false`, to the function call.  This disables writing the values to the file\nuntil you call `commitDOMChanges()`, which will write all changes back to the file, which is much\nfaster than writing and rebuilding the DOM model with every addition.\n\n### Login and Checking Permissions\n\nThe `require_login()` function can be invoked the top of any page, and only users logged in (with a\ncertain permission level, if you pass one to the function) will be able to view the contents of the\npage. If the visitor is already logged in they will notice no interruption of service, and will not\nneed to login again.\n  \nThe default UserManager class has a `header()` and a `footer()` function which are called\nby `require_login()` (and for that matter `manageUsers()`) which will be used to generate an HTML\nlogin page. The default behavior of these methods is a bare-bones page with no styling. See the\n\"Extending Header and Footer\" section below to change this behavior to match your site's look and\nfeel, or avoid `require_login()` and create your own login behavior instead.\n\nThe `login()` function takes a username and password and returns a boolean. If true, the credentials\nwere correct and the user is now logged in, if false one of the given credentials was incorrect.\nNote that it is a security feature, and not a bug, that *which* credential was incorrect is not\nspecified. You can create your own login page or form and pass the result to the `login()` method.\n  \nYou may want to output certain content only to logged in users (for instance, perhaps only logged in\nusers should see a link to post a new topic). For this functionality, use `hasPerm()`. The default\nparameter is `UserManager::USER`, but if you want to be more restrictive, for instance displaying a\nlink to the admin panel only to administrators, simply pass a different user level to the function.\nThe function returns a boolean if the user has permission or not.  Example:\n\n```\nif($_user-\u003ehasPerm(UserManager::ADMIN)) {\n  echo '\u003ca href=\"admin.php\"\u003eManage Users\u003c/a\u003e';\n}\n```\n  \n### Get Information About the Current User\n\nThe current user's ID, username, and level are stored in the session and are immediately available\nto every webpage. This information is stored in the `$user` array. If you need additional\ninformation about the current user, you must call `loadCurUser()`. This will populate the array with\nall other information on the current user.\n  \n### Method Overview\n\n* `logout()`\n\n    Call logout() and the current user will be logged out and reduced to GUEST permission level.\n\n* `loadCurUser()`\n\n    To save reads the current user's extended data is not loaded unless requested. The ID,\n\tUsername, and Level are available in the `$user-\u003euser` array immediately. If you need the\n\textended data, such as any custom attributes being stored, call `loadCurUser()` to populate the\n\t`$user-\u003euser` array with all the current user's information.\n\n* `getUser()`\n\n    To get information on a user given an ID, you can call `$user-\u003egetUser($id)`. This will return\n\tan associative array of all the details of that user.\n\n* `lookupAttribute()`\n\n    To lookup users by anything other than their ID you can use lookupAttribute. It takes two\n\tparameters, the attribute to lookup by and a value to match. It will return an array of users\n\t(which are themselves associative arrays of all the user's attributes).\n\n* `userLevel()`\n\n    Returns the string version of a permission level, pass it the result of `$user-user['level']`,\n\tfor instance.\n\n* `modifyUser()`\n\n    This method takes an associative array of parameters to new values. You can even change the\n\tusername. You must specify the user id (obviously) but all other parameters are optional. What\n\tyou don't specify stays the same.\n\n* `deleteUser()`\n\n    Takes a user id to delete.\n\n* `commitChanges()`\n\n    If you call any of the modifying methods (`addUser`, `modifyUser`, `deleteUser`) and have set \n\t`autoCommit` to `false` you need to call `commitChanges()` to process all the buffered commits\n\tat once.  Note that internally when `autoCommit` is `true` modifications call `commitChanges()`,\n\tso if at any point you call a modifying method with `autoCommit` set to true all earlier\n\tuncommitted modifications will also be submitted.\n\n## Advanced Usage\n\nYou can extend the `UserManager` subclasses to enable more custom behavior, including new user\nlevels, custom header and footer behavior, and more. It is also possible to extend `UserManager`\nitself to integrate with a new backend. How to do this is not presently documented, but replicating\nthe contents of either `XMLUserManager` or `MySQLUserManager` with your backend of choice\n(`JSONUserManager`, for instance) will get you most of the way there.\n\n### New Permission Levels and Additional Fields\n\nIf you wish to create additional user levels, you must introduce a new constant, such as\n`const SUBSCRIBER = 3;` make the name descriptive, and make the value some integer to represent its\nrank. Larger numbers have higher permissions. Note that 0 is a guest, a normal user is 2, a super\nuser is 4, and an administrator is 10. In addition to creating a new constant, you will need to add\nthis value to the levels array in your constructor:\n  \n```\n$this-\u003elevels['SUBSCRIBER'] = self::SUBSCRIBER;\n```\n  \nYou can also define permission groups, which do not have a logical hierarchy, but also are not\nmutually exclusive. A user can only be one level, and automatically inherits the privileges of any\nlower level, but can be a member of any number of groups. This is done by constructing a bitmasker\nobject (see `bitmasker.class.php` for more) with the names of the groups you would like to exist,\nlike so:\n  \n```\n$this-\u003egroups = new bitmasker('author','editor','publisher');\n```\n\nNow you can specify a user's groups directly in `addUser()`, update them with `modifyUser()` (though\nyou have to directly use the bitmasker object in this case), and most importantly handle permission\nchecks with `hasPerm()` and `require_login()`.  For instance, to confirm a user is either an author\nor a publisher, you can do the following:\n  \n```\n$_user-\u003ehasPerm(UserManager::USER,array('author','publisher'));\n```\n\nGroups are stored as a bitmask, and as such you'll want to use the bitmask class to modify them or\ndo more advanced handling of user groups:\n  \n```\n$_user-\u003egroups-\u003egetValue($_user-\u003euser['groups'],'author'); // returns true if user is an author\n// sets editor field to true and returns modified mask.  Saving the modified mask is a second step.\n$newGroup = $_user-\u003egroups-\u003esetValue($_user-\u003euser['groups'], 'editor', true);\n// returns an array of the groups a user is in\n$groups = $_user-\u003egroups-\u003emaskToArray($_user-\u003euser['groups']);\n```\n\nAnother way to extend UserManager is to introduce new attributes for the XML document / DB to store.\nDo this by appending an array of the attributes you want to add to the userFields array, for\ninstance:\n\n```\n$this-\u003euserFields = array('name', 'email', 'gender', 'ip');\n```\n\n**Make sure** you call the parent constructor and pass it the file you want to reference, even if\nyou don't want to extend either the user levels or the user attributes.\n  \n### Extending Header and Footer\n\nExtending the `header()` and `footer()` methods will allow you to display your own template when\nusing the `require_login()` and `manageUsers()` functions. Simply insert your own template header\nand footer code into the respective methods. For instance, to work with the template system I\nnormally use, I do the following:\n\n```\nfunction header($title) {\n  global $template;\n  $template-\u003eheader($title);\n}\n\nfunction footer() {\n  global $template;\n  $template-\u003efooter();\n}\n```\n\n## File Overview\n\n* `UserManager.class.php` - The abstract parent class of both UserManager objects, handles all\n  backend-abstract behavior.\n* `XMLUserManager.class.php` - The XML-backed UserManager, include this file in your code and create\n  an instance of it to use XML.\n* `MySQLUserManager.class.php` - The MySQL-backed UserManager, include this file in your code and\n  create an instance of it to use XML.\n* `bitmasker.class.php` - A bitmap handling utility for storing and working with groups.\n* `UserManager.Extended.class.php` - This is an example demonstrating one possible way to extend the\n  `UserManager` to draw more out of the application.\n\n## Version History\n\n* 1.5 - `MySQLUserManager` released\n  * 1.5.0 - Major robustness improvements, `UserManager` compartmentalized and `MySQLUserManager`\n    created\n* 1.0 - Initial `UserManager`\n  * 1.0.2 - Minor Feature Improvements\n  * 1.0.1 - Bug Fixes\n  * 1.0.0 - Initial Release\n\n## Copyright and License\n\n©2010-2012 Michael Diamond\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see \u003chttp://www.gnu.org/licenses/\u003e.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdimo414%2Fphp-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdimo414%2Fphp-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdimo414%2Fphp-auth/lists"}