PHP – ping server and log the result

Here’s a small usefull PHP script that gets data from an url, checks if it’s what you expect it to be, and logs the result (the current time, and the retrieved content if there’s an error). Best used with a cron job.

function ping($url) {
	//don't wait for too long - there'll be a next ping
	$tstart = microtime(true);
	$data = file_get_contents($url);
	$tend = microtime(true);
	//compare the retrieved contents with what we expect
	if ($data == '{"result":"SUCCESS"}') {
		$resultInfo = " ok";
	} else {
		$resultInfo = " error " . $data . " ";
	return (round((($tend - $tstart) * 1000), 0)." ms") . $resultInfo;
$dateForLog = (date("ymd_His"));
$dateForFilename = (date("ym"));//one log file covers one month
file_put_contents("yourpathhere/pingresult" . $dateForFilename .  ".txt",  $dateForLog  . ' ' . ping(""). "|\r\n", FILE_APPEND);

This entry was posted in Software. Bookmark the permalink.

2 Responses to PHP – ping server and log the result

  1. Xleeuwx says:

    First of all there are a few bugs, do you have test your code ?? seems like you forget some $ in the last row. and Second there are 2 times tstart i suggest you change that to tend 🙂

Leave a Reply

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

Please solve this little equation for verifying that you\'re human *