Using PHP to check response time of HTTP-server

I must start off with admiting that my PHP skills are very limited, however being a very experienced Perl hacker this is very similar to me. Edit 2013-01-30: This is no longer true 🙂

I needed a script that checked for a normal HTTP response from another server, a status script to see if the other server(s) where behaving as they should.

The resources on-line for PHP are great and I quickly found the code needed to retrieve a remote page and read the contents. I also found some tutorials describing how to use this code. My version ended up looking like this (thanks phptoys.com for the tutorial!):

<?php
// check responsetime for a webbserver
function pingDomain($domain){
    $starttime = microtime(true);
    // supress error messages with @
    $file      = @fsockopen($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file){
        $status = -1;  // Site is down
    }
    else{
        fclose($file);
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    }
    return $status;
}
?>

What this code does is to measure, using the microtime function, the time difference between initiating a connection using fsockopen and when that functions has completed executing. If a connection was established the time difference is returned. If fsockopen failed to open a connection -1 is returned.

The time difference is multiplied by 1000 to get the number of milliseconds it took, floor() is then used to round down to the nearest integer value.

To call this function simply add the domain or IP you want to check the response time of:

Fireflake: <?php echo pingDomain('tech.fireflake.com'); ?> ms<br>
Example: <?php echo pingDomain('www.example.com'); ?> ms<br>
Internal IP: <?php echo pingDomain('192.168.0.2'); ?> ms<br>
Fail: <?php echo pingDomain('fail.fireflake.com'); ?> ms<br>

Sample output from the above statements are:

Fireflake: 111 ms
Example: 139 ms
Internal IP: 0 ms
Fail: -1 ms

Also, sometimes DNS servers return a “search engine” response if the domain is unknown or unreachable. To be sure you reach the server you want try calling it by IP-number instead to make sure your DNS isn’t fooling you.

EDIT:  Thx for adding the tip to use @ to supress error messages. Just use @fsockopen to supress the inevitable error message.

EDIT 2013-01-30: Fixed the old code and added some more examples.

EDIT 2013-03-07: Added clarification about unit used in $status.

Using AJAX to asynchronously load slow XML files

More and more I’ve come across situations where I want to use AJAX to download a XML file to use in the interface but know beforhand that the file will take a long time to load. With asyncroneous download of XML files by JavaScript, which is kind of what the buzz word AJAX is all about, you must be carefull not to leave the client in limbo between a useable interface and a locked up screen.

Unfortunately this script only works in Internet Explorer, useful tips of how to port it properly (with the asynchronous property intact) would be highly appreciated.

Here is a simple description of the basic functions needed to perfom a asynchronous download where the user will have the option to abort.

First we need a simple function that download the XML, this is pretty standard and the code is lovingly ripped off from w3school.com.

function loadXml(sUrl){
	try{
		//Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	}
	catch(e){
		try{
			//Firefox, Mozilla, Opera, etc.
			xmlDoc = document.implementation.createDocument("","",null);
		}
		catch(e) {
			alert(e.message)
		}
	}
	try{
		xmlDoc.async = 'true';
		xmlDoc.load(sUrl);
	}
	catch(e) {
		alert(e.message)
	}
}

This code is pretty straight forward and I assume you allready know of it, if not read the guide over at W3Schools. The only difference in the above code compared to that from the tutorial over at W3Schools is the flag “xmlDoc.async = ‘true'”. This means that the code will continue executing after the load is called without waiting for the load to finish. This will place the status of the xmlDoc variable in a limbo which can be checked with the “readyState” flag.

To check if our file is ready to use we have a test-loop that will check if readyState changes:

function testReadyLoop(){
	i++;
	if (xmlDoc.readyState == 4){
		// the file has completed the download
		alert('xmlDoc ready to use! Contents:n' + xmlDoc.xml);
		// TODO: add code here of what to do with the file
	}
	else{
		if (!abortXmlLoad){
			// try again in 1 second
			setTimeout("testReadyLoop();",1000);
		}
		else{
			// stop loading the xml file
			xmlDoc.abort();
			alert('Loading of the XML file aborted!');
		}
	}
}

The incrementation of the variable “i” is just a counter that will be used later and the “abortXmlLoad” is a boolean if the loop should continue or not, these will be explained later. What happens in this function is that it first tests if readyState is 4 which indicates that the file is ready to be used, if this is the case we simple show an alert with the contents of the file, here more intelligent code would be placed. If it’s not ready it checks if it should continue waiting for the file or not, if it should it calls itself in 1 second (1000 ms) otherwise it aborts the loading and simply stops.

To abort a download we need to set the “abortXmlLoad” flag to true, a short function is needed for this:

function abortAsyncXML(){
	// set the abort flag to true
	abortXmlLoad = true;
}

Now we have all the functions needed for the asynchronous download, a last function is added to tie them all togheter:

function loadAsyncXML(sUrl){
	// set abort to false and start download
	abortXmlLoad = false;
	i = 0;
	loadXml(sUrl);
	// start loop to check when ready
	testReadyLoop();
}

This function first resets the values of “i” and “abortXmlLoad” and then it calls the download and after that starts the loop to test if the download is ready. The file will now download silently in the background and pop an alert when ready unless someone calls “abortAsyncXml” before that happens.

As you may have noticed there are a few global variables I use across the functions that also need to be added to the top of the script:

var xmlDoc;
var abortXmlLoad;
var i;

To use this script a small form need to be added to the page:

<form>
<input type="button" value="load" onclick="loadAsyncXML('sample.xml');">
<input type="button" value="abort" onclick="abortAsyncXML();">
</form>

This will load the file “sample.xml” and abort if the abort button is pushed. In order to test that the abort button is working you would have to build a slow loading page that simulates long loading time.

I will post a link to the full code and sample later. Hope you found this helpful.

Are you not (yet) against software patents?

Are software patents protecting the inventors and is something needed to protect intelectual property?

Read this: http://news.zdnet.com/2424-9595_22-218626.html

If it designed to be used to protect intelectual property then it is now abused by large companies for making absurd claims, in this case Microsoft.

Makes me want to patent the “O”-button… peple cant write blgs withut it.