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.


<?php
function ping($url) {
	//don't wait for too long - there'll be a next ping
	set_time_limit(5);
	$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;
}
date_default_timezone_set("Europe/Paris");
$dateForLog = (date("ymd_His"));
$dateForFilename = (date("ym"));//one log file covers one month
file_put_contents("yourpathhere/pingresult" . $dateForFilename .  ".txt",  $dateForLog  . ' ' . ping("http://yoururlhere.com"). "|\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 *