Web Niraj
  • Facebook
  • Flickr
  • Github
  • Linkedin
  • Twitter
  • YouTube
Online portfolio, code examples and developer blog
  • About
  • Contact
  • Portfolio
  • WordPress
Search the site...
  • Home
  • Blog
  • Memcached with PHP

Memcached with PHP

0

On a recent project I worked on, the sheer amount of users using the application caused the web server to fail due to the load on the database. Memcache with PHP was just one of the methods I used to reduce the load on the database and away from constant disk read/writes.

On a Unix server, Memcache is easy to setup when using PHP and Apache/httpd. Once Memcache was running, a simple modification to the script accessing the database made a whole lot of difference. Here is a bit of sample code you can use to cache your own data:

 

// Init memcache
$memcache = new Memcache;
// Connect to memcache server
$memcache->connect( 'localhost', 11211 ) or die ( "Could not connect" );

// get data from cache
$cached_data = $memcache->get( 'my_data' );

if ( $cached_data ) {
    $data = $cached_data;
} else {
    // function to get data
    $data = getData();
    // store data in cache for 60 seconds
    $memcache->set( 'my_data', $data, false, 60 )
         or die ("Failed to save data at the server")
}

// do something with $data

 

Unfortunately, for this particular project, memcache wasn’t enough to reduce the load and the server crashed several times during one particular period of high traffic. Needless to say, the second time around we made sure we had enough server resources to cope with a massive load of traffic.

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

StackExchange / StackOverflow

profile for Niraj Shah on Stack Exchange, a network of free, community-driven Q&A sites

Support Me

Buy Me a Coffee

PSN Profile

Tags

ACL Amazon Amazon Web Services Android Android 4.4 KitKat Android 5.0 Lollipop Apache Backup Bug Command Line Cordova cPanel / WHM Facebook Facebook Graph API Facebook PHP SDK 4.0 Facebook Social Plugins Fan Page Firewall Flash Gadget Geolocation Google Nexus 5 Hacking HTML5 iOS JavaScript jQuery Laravel 5 Linux NodeJS Parse PDF PHP Plugin Portfolio PS4 Review Security Server SSH SSL Sysadmin Tutorial WordPress WordPress Plugins
© 2011-2025 Niraj Shah
  • Blog
  • Portfolio
  • WordPress
  • About Me
  • Contact Me
  • Privacy Policy
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here: Privacy Policy