Simple PHP Persistent Storage

13 Jul

For a project I am working on, I had to put together a demo using PHP. One of the aspects of this demo is that it needed a simple persistent storage: it has to keep a count of the number of times a particular URL is passed as an argument, and do something relevant.

Instead of using a MySQL database, I simply used an associative array and serialize() and unserialize().

So my code basically looked something like this:

if (numberOfUrl ($url) == 0)
  do_something_for_first_request();
else
  do_something_for_subsequent_requests();

But the function numberOfUrl($url) needs persistent storage – and MySQL would have been overkill.

So I used a simple associative array and serialize() and unserialize() to a file.

/**
* Returns the number of times this URL has been requested
*/
function numberOfUrl ($url) {
  // The file name
  $arrayFile = "urls.db";

  // Read the file, unserialize it to an array
  $urlArray = unserialize (file_get_contents($arrayFile));

  // If this URL exists in the array, just increment it
  if (isset ($urlArray[$url]))
    $urlArray[$url]++;
  // Otherwise add a new entry and set it to 1
  else
    $urlArray[$url] = 1;

  // Write out the serialized array back to disk
  file_put_contents ($arrayFile, serialize($urlArray));

  // Return the number of accesses
  return $urlArray[$url] - 1;
}

Of course, you will have to implement some form of mutual exclusion or locks to ensure that the whole thing happens as a transaction, especially if this PHP code can be accessed by multiple clients at the same time.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: