Tim Igoe's Web Design, Development and Hosting Blog

PHP – Stop Site using too much CPU

Posted on by Tim Igoe

Got a popular site that sometimes gets out of control with CPU usage? Need to curb it so it doesn’t spiral. With this little snippet of code in your page (near the top), it makes a quick check to see if the server is too heavily loaded. If it is, the request is cancelled and you can return an error message to the user to tell them to try again in a few minutes.


// Change this to suit your server
$highLoad = 3; // 3 is suitable for a single core, 8 for a dual core
// This is something you will want to tweak to suit your server as you might find a point where it works better

$cpuLoad = file_get_contents(‘/proc/loadavg’);
$cpuLoads = explode(‘ ‘, $cpuLoad);
// We care about the first value from teh cpuLoads array
// $cpuLoads[0] is 1 minute load average
// $cpuLoads[1] is 5 minute load average
// $cpuLoads[2] is 15 minute load average
if ((int)$cpuLoads[0] >= $highLoad)
{ // We’re loaded too high – give the user a nice error
die(‘The server is currently under too much load, please try again in a few minutes’);
}
// If we get here, we must be ok to carry on

Save this file to disk, then include it within your site to protect it from high loads.

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

Leave a Reply