Show a “We are Busy” page when your server is too busy by using PHP

If you are apache fan. You shold have many virtual host in your apache conf. But after your site getting popular, sometimes your server can not handle all request and your visitor will have to wait in front of the browser.

I could not find a nice solution for that so created one.

First, create a html page that will be shown when your server is busy.

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
  #main  { background-color: #fcc; }
</style>
<title>We are busy</title>
</head>
 
<body>
<div id="main">
<p>
Many visitors are accessing my server or I'm encoding some movies on the server.
</p>
<p>
Wait just a few second and <a ref="javascript:location.reload()">reload</a>.
</p>
</div>
</body>
</html>

Save above file as “/phpGlobal/busy.html”. The directory can be anywhere as you like.

Next, create a php that check whether my server is heavy.

<?php
checkMachineState();
function checkMachineState()
{
        $a = @file_get_contents('/proc/loadavg');
        if(!$a) {
                return;
        }
        $a = explode(' ',$a);
 
        if($a[0] <= 3)
        // if(false)
        {
                return;
        }
        header ('HTTP/1.0 503 Service Temporarily Unavailable');
        require 'busy.html';
        exit();
}
?>

Save above as “/phpGlobal/check.php”
This will show “busy.html” when the load avarage exceeds 3.

Next, add this line on apache2.conf or your conf file.

php_value auto_prepend_file /phpGlobal/check.php

NOw when you restarts apache2. “check.php” will run before any php requests.

check.php uses UTF-8 that will disturb with your character code of your environment.
In that case, try to consider adding these lines to check.php.

@ini_set ( 'default_charset' , '');
header ('Content-Type: text/html; charset=UTF-8');

At last, you can see a current load average by using “top” command. At top right corner of the command output.

Leave a comment

Your email address will not be published. Required fields are marked *