Use an array in PHP as a “database”

First a small warning: The solution presented in this post is not very secure and is prone to errors. It’s a quick and dirty solution to a simple problem. But since we all like to get dirty sometimes I’ll present it to you anyway.

Naveed at work is making a small chat application and wanted to store some information about which users were banned from the chat. This feature needed to be done relatively fast and since the chat does not use a database (apc only) we did not want to use a database to store this information either. I figured we could implement it fast by storing it in a regular php array.

The “database” might look like this:

return array(123 => true, 456 => true, 789 => true);

As you can see we have three banned users. The keys in the array represent the IDs of these users. In the chat application we fetch the database by doing:

This entry was posted in PHP, Technology, Work related and tagged , , . Bookmark the permalink.

6 Responses to Use an array in PHP as a “database”

  1. Rexxars says:

    I assume the reasoning behind writing to a file is making it persistant?

    Shouldn’t you be using LOCK_EX on the file_put_contents to make sure that two people does not write to the file at the same time?

    It’s dirty, but I like it.

  2. that code is a simple and easy

  3. christer says:

    @Rexxars: Yes, we should. :) Thanks for the input.

  4. Shahar Evron says:

    BTW I don’t think it’s that dirty – to me it makes a lot of sense, for small amounts of relatively static data that do not require any of the advanced features of a real database and do not need to be constantly synced across the cluster – things like configuration data or lists of countries / regions.

    Remember that if you have opcode cache (APC et al) it will be *super* fast – probably faster than anything else (my guess is that it will even be faster than storing it in shared memory cache because of the time it takes to serialize / unserialize cached arrays).

    The only thing you need to be concerned about is security – this is after all executable code so make sure nobody can inject anything in there (best make it read only).

  5. christer says:

    @shahar: Thanks for the comment. We have APC in front of it so yes, it will probably be very fast.

  6. rateitstar says:

    youll still get bottlenecks from *file_lock errors if they are writing to the same file no matter what you do with that.

    other than a redesign..

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s