PHP Membership Provider

I came across a post made a little while ago by Steven Benner on PHP’s notable lack of a consistent Membership Provider as in ASP.Net. All good points, but I think the hard bit isn’t so much session management since there are a million examples out there on how to provide a login interface.

The tough part seems to be a consistent method of accessing, creating and maintaining users in a database. Also a lot of those examples tend to be MySQL specific so if you need something easily customized for something else, like say PostgreSQL, you’re pretty much stuck customizing to no end, at which point you might as well write your own.

And that seems to be what an overwhelming majority of people are doing if they’re not getting an off-the-shelf CMS to start with. Of the few frameworks for membership management that are available out there, most are a bit over complicated and have licenses, fees and other strings attached.

So most people are stuck writing a user management system from scratch or getting a CMS off the shelf with its own unique (and usually incompatible) user management system.

I got home from work early on Friday and have this weekend off for a pretty good rest, so early this morning, I thought I’d write up a Membership Provider for PHP that anyone can use with no strings attached (and hopefully doesn’t suck too much). The idea is to have a simple drop-in user management interface.

Keep in mind that I haven’t actually tested any of this and it all may in fact blow up spectacularly (since I didn’t do any testing, everything is as-is and I’m not a professional PHP programmer). It’s a bit late for Steven’s post, but better late than never eh? ;)


I didn’t want to mimic everything in the Membership Provider for ASP.Net in that there are a lot of things that I don’t like, some features that could be improved and others that are completely missing.

Notably, I don’t see the need for password questions and answers since resetting by email is often a better solution than lowering the security barrier by introducing (essentially) a weaker password in the form of an answer to a known question. Also, people often forget the answers to questions too or repeat the same questions and answers on different sites, which defeats the purpose of a strong password anyway.

I’d also like to have a way to find and delete users by either Id, Name or Email and easily lock/unlock, approve/unapprove users and provide strong passwords with Blowfish. For this last option, I downloaded the Portable PHP password hashing framework, which I think is the best implementation for PHP I’ve found so far.

Now I need a table…

Although this example table is in MySQL, you could modify this for any other database. In the queries, I avoided any MySQL specific commands like sql_calc_found_rows and the like and because I’m using PDO the code itself should work with no modifications on PostgreSQL and SQLite provided it’s the same table structure.

CREATE TABLE `users` (
  `userId` int(20) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL,
  `hash` varchar(10) NOT NULL,
  `password` varchar(200) NOT NULL,
  `passwordSalt` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `avatar` varchar(200) DEFAULT NULL,
  `createdDate` datetime NOT NULL,
  `modifiedDate` datetime NOT NULL,
  `lastActivity` datetime NOT NULL,
  `bio` text DEFAULT NULL,
  `isApproved` tinyint(1) NOT NULL DEFAULT '1',
  `isLocked` tinyint(1) NOT NULL DEFAULT '0',

  PRIMARY KEY (`userId`)

Pretty typical for most websites. The “hash” there is just a unique key made by combining the username and email in a hash that will set apart users even with similar looking usernames. Think of it as a very primitive Tripcode shown alongside a username.


If there’s one thing that makes configuring an ASP.Net web page consistent is the web.config file. It’s only appropriate then to put all the configuation stuff into one file, say a .ini, like so :

;*** Website configuration file ***
; All comments start with a semicolon (;), and this file can be something other than config.ini
; as long as the new file name is specified in index.php .

;*** Globally accessible settings ***

dsn = "mysql:host=localhost;dbname=testdb"
username = "testuser"
password = "BKjSheQubKEufqHC"

usersTable = "users"
rolesTable = "roles"
tablePrefix = ""

;*** Membership specific settings ***

minRequiredPasswordLength = 5
maxInvalidPasswordAttempts = 3
passwordAttemptWindow = 10
userIsOnlineTimeWindow = 20
autoApproveUsers = "true"

Of course, for this example, we won’t be using all of that, but I just created a file called config.ini and put all that in there. Now how do we load all of this? First we need an index.php file.


ini_set( "display_errors", true );

// Set the application configuration file. You may store this outside the web root
// if your web host allows it.
define('INI', 'config.ini');


	End editing


define('BASE_PATH', dirname(__FILE__));

// Platform specific include path separator
if ( strtolower(substr(PHP_OS, 0, 3)) === 'win') 
	define('SEP', ';');
	define('SEP', ':');

// There must be an /app folder in root with all the class files

// Optionally there should also be a /mod folder in root where you can include modules/plugins in the future

// Modify include path
set_include_path( CLASS_DIR  . SEP . MODULE_DIR );



The down side to this approach is that all your file names must be lowercase, but it should be slightly faster than any other autoload implementation and I’m reasonably confident it should run on a *nix platform with no hiccups as well as on Windows.

For now, that autoload would force the application to look in the /app folder where all the magic happens and optionally in /mod for any future modules. And for that magic we’ll create a base class that all “action” classes would inherit from. This is basically to provide dynamic class properties.


 * Base class provides dynamic class property functionality
 * @package Base
class Base {
	 * @var array Config properties storage
	protected $props = array();
	 * Get class accessible settings
	protected function __get( $key ) {
		return array_key_exists( $key, $this->props ) ? 
			$this->props[$key] : null;
	 * Set class accessible settings
	protected function __set( $key, $value ) {
		$this->props[$key] = $value;
	 * Checks whether accessible setting is available
	protected function __isset( $key ) {
		return isset( $this->props[$key] );

Now we need a configuration class that will load the settings from the defined .ini file into itself and make the settings accessible to all classes calling it.


 * Application configuration file.
 * All settings are imported from the .ini file defined in index.php
 * @package Config

class Config extends Base {
	 * Class instance
	private static $instance;
	private function __construct() {
		$this->props = parse_ini_file(INI, true);
	public static function getInstance() {
			self::$instance = new Config();
		return self::$instance;

This is starting to get a bit long so onward to the next page

6 thoughts on “PHP Membership Provider

  1. Although I took a short introductory class for php I consider it, and all coding really, something akin to electricity – i.e. it’s not a hobby – only hire a licensed electrician! I love the idea of myself dabbling in code, but I would never think for myself to go whole hog and live with anything as the risks are too daunting. Nonetheless, I sometimes dream of buckling down and learning to code and creating some useful apps for my job or a cool site for my friends or self etc… Maybe someday.

    • Haha! That’s a great analogy :D

      But see there are people who do electrical work as a hobby too. Some people even build Tesla Coils, which can not only kill instantly, but also blow up spectacularly if everything isn’t perfect… but they’re oh-so-much-fun!

      If you’re considering diving in again, all I can say is stay away from w3schools. It’s really, really, bad!

      I think a lot of tutorials out there are just not intro-friendly. And a lot of people are taught with some really ugly, ugly code (in all languages) with no consideration of human nature. I.E. They jump right into programming techniques — some questionable — without covering basics first and that turns off a lot of people.

      We’re not robots… We use robots to work like robots.

      • Interesting as I’ve always heard of the usefulness of w3schools… But then again, maybe they are a reason I don’t bother progressing with coding. Homemade Tesla coils huh…? Now that’s interesting!

  2. I love this idea. I can’t tell you how many times I’ve written my own user authentication scheme, and typically it’s no more than a hard-coded hack (with the necessary input sanitation, of course!) with some super slap-dash session management thrown in. I would absolutely love a standardized, built-in package so I don’t have to rely on super complicated CMS implementations like Drupal / WordPress / CakePHP just to have a robust authentication and user management system.

    • Thanks!

      If you happen to find it useful I’d love to know about it. I’m also thinking of including a standard sanitization class. Probably something based on a class I’ve written before rather than reinventing the wheel.

      It’s pretty silly that we have to write more when we need less!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s