I am writing a script for a client so hey can check the status of their servers.
The script performs ajax requests to get the data as json then poulates the table with the returned json results.
is there anyway i can streamline this better.
I also sometimes get timeout errors on the get_meta_data calls, whats the best way to handle/supress these warnings so the json does not break
The live script is here heres the script
<?php
// set up db connection
$hostname = "localhost";
$database = "*********";
$username = "*********";
$password = "**********";
$username = "root";
$password = "dioohag";
$db_conn = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database, $db_conn);
$query = "SELECT * FROM sitestocheck ORDER BY url ASC";
$servers = mysql_query($query, $db_conn) or die(mysql_error());
$totalRows_servers = mysql_num_rows($servers);
$title = "Server Check";
$responseCodes = array(
100 => '100 Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'Im a teapot',
421 => 'Misdirected Request',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
444 => 'Connection Closed Without Response',
451 => 'Unavailable For Legal Reasons',
499 => 'Client Closed Request',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required',
599 => 'Network Connect Timeout Error'
);
// if a host has been passed (this is an ajax request)
if (isset($_GET['host'])) {
$host = $_GET['host'];
//if command has been passed this is an insert or delete operation
if(isset($_GET['command'])){
try {
$conn = new PDO("mysql:host=$hostname; dbname=$database;", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//insert
if($_GET['command'] == 'insert'){
$stmt = $conn->prepare("INSERT INTO sitestocheck (url) VALUES (:host)");
$stmt->bindParam(':host', $host);
$stmt->execute();
$return = array(
'status'=> 'success',
'message'=> $host.' added'
);
}
//Delete
if($_GET['command'] == 'delete'){
$stmt = $conn->prepare("DELETE FROM sitestocheck WHERE url=:host");
$stmt->bindParam(':host', $host);
$stmt->execute();
if($stmt->rowCount()) {
$return = array(
'status'=> 'success',
'message'=> $host.' deleted'
);
} else {
$return = array(
'status'=> 'danger',
'message'=> $host.' not found in database'
);
}
}
//return response
header('Content-Type: application/json');
echo json_encode($return);
$conn = null;
exit;
}
//if there was an error
catch(PDOException $e){
$return = array(
'status' => 'danger',
'message'=> $e->getMessage()
);
header('Content-Type: application/json');
echo json_encode($return);
exit;
}
};
//return results of tests
header('Content-Type: application/json');
$return = array(
'status' => pingTest($host),
'author' => checkAuthor($host),
'http' => httpCheck($host, $responseCodes)
);
echo json_encode($return);
exit;
} else {
//not an ajax request so display the page
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="ROBOTS" content="NOINDEX, NOFOLLOW">
<title><?php echo $title; ?></title>
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<h1><?php echo $title; ?></h1>
<form class="form-horizontal">
<fieldset>
<!-- Form Name -->
<legend>Add / Remove Servers</legend>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="Domain">Domain</label>
<div class="col-md-4">
<input id="domain" name="domain" type="text" placeholder="mysite.com" class="form-control input-md" required="">
<span class="help-block">The domain you wish to add/remove</span>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-4 control-label" for="insert">Action</label>
<div class="col-md-8">
<button id="domainInsert" name="insert" class="btn btn-success">Add</button>
<button id="domainDelete" name="delete" class="btn btn-danger">Remove</button>
</div>
</div>
<div class="form-group">
<div id="formResponse"> </div>
</div>
</fieldset>
</form>
<table id="results" class="table table-striped">
<thead>
<tr>
<th></th>
<th>Domain</th>
<th>Site Status</th>
<th>Server Ping</th>
<th>Http Status</th>
<th>
<div class="recheckAll btn btn-default btn-xs" data-host="<?php echo $row['url']; ?>" data-hash="<?php echo $urlHash; ?>">Recheck ALL</div>
<div class="recheckFailed btn btn-default btn-xs" data-host="<?php echo $row['url']; ?>" data-hash="<?php echo $urlHash; ?>">Recheck Failed</div>
</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysql_fetch_assoc( $servers )) {
$url = $row['url'];
$urlHash = md5( $url );
?>
<tr class="hostresult" id="<?php echo $urlHash; ?>" data-url="<?php echo $row['url']; ?>"
data-hash="<?php echo $urlHash; ?>">
<td><i id="spinner-<?php echo $urlHash; ?>" class="fa fa-spinner" style="font-size:24px;color:green"></i></i></td>
<td class="name"><a href="http://<?php echo $row['url']; ?>" target="_blank"><?php echo $row['url']; ?></a></td>
<td id="<?php echo $urlHash; ?>-author"> </td>
<td id="<?php echo $urlHash; ?>-ping"> </td>
<td id="<?php echo $urlHash; ?>-http"> </td>
<td>
<div class="recheck btn btn-default btn-xs" data-host="<?php echo $row['url']; ?>" data-hash="<?php echo $urlHash; ?>">Recheck</div>
</td>
</tr>
<?php }; ?>
</tbody>
</table>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#domainInsert').click(function(e){
// Fork it
e.preventDefault();
var request;
host = $('#domain').val();
console.log('add: '+host);
request = $.ajax({
url: "<?php echo basename(__FILE__); ?>",
type: "get",
data: {
host: host,
command: 'insert'
}
});
request.done(function (response) {
var status = response.status;
var msg = response.message;
$('#formResponse').removeClass('label-danger label-success').html(msg).addClass('label-'+status);
});
});
$('#domainDelete').click(function(e) {
// Fork it
e.preventDefault();
var request;
host = $('#domain').val();
console.log('delete: '+host);
request = $.ajax({
url: "<?php echo basename(__FILE__); ?>",
type: "get",
data: {
host: host,
command: 'delete'
}
});
request.done(function (response) {
var status = response.status;
var msg = response.message;
$('#formResponse').removeClass('label-danger label-success').html(msg).addClass('label-'+status);
});
});
function test(host, hash) {
// Fork it
var request;
// fire off the request to /form.php
request = $.ajax({
url: "<?php echo basename(__FILE__); ?>",
type: "get",
data: {
host: host
},
beforeSend: function () {
$('#spinner-'+hash).addClass('fa-spin').show();
}
});
// callback handler that will be called on success
request.done(function (response) {
//console.log(response);
var status = response.status;
var author = response.author;
var http = response.http;
var pingMsg, authorMsg, httpMsg;
//console.log(response);
var statusClass = 'error';
//process ping
if (status) {
statusClass = 'success';
pingMsg = '<span class="label label-success">OK</span>';
} else {
pingMsg = '<span class="label label-danger">Fail</span>';
}
//process author meta tag
$('#'+hash).removeClass('checkFailed');
if (author['match'] == true) {
authorMsg = '<span class="label label-success">OK</span>';
} else {
authorMsg = '<span class="label label-danger">NO</span>';
$('#'+hash).addClass('checkFailed');
}
// process http response
if (http.httpCode >= 100 && http.httpCode <= 199){
httpMsg ='<span class="label label-info">'+http.httpCode+'</span> '+http.httpDesc;
}
if (http.httpCode >= 200 && http.httpCode <= 299){
httpMsg ='<span class="label label-info">'+http.httpCode+'</span> '+http.httpDesc;
}
if(http.httpCode >= 300 && http.httpCode <= 399){
httpMsg ='<span class="label label-warning">'+http.httpCode+'</span> '+http.httpDesc;
}
if(http.httpCode >= 400 && http.httpCode <= 499){
httpMsg ='<span class="label label-danger">'+http.httpCode+'</span> '+http.httpDesc;
}
if(http.httpCode >= 500 && http.httpCode <= 599){
statusClass ='error';
httpMsg ='<span class="label label-danger">'+http.httpCode+'</span> '+http.httpDesc+'<br>'+http.response;
}
$('#' + hash + '-ping').html(pingMsg);
$('#' + hash + '-author').html(authorMsg);
$('#' + hash + '-http').html(httpMsg);
$('#spinner-' + hash).removeClass('fa-spin').hide();
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.error(
"An error occurred: "
);
console.log('jqXHR: '+jqXHR+' textStatus:'+textStatus+' errorThrown: '+errorThrown);
console.log(jqXHR);
$('#'+hash).addClass('checkFailed');
$('#spinner-' + hash).removeClass('fa-spin').hide();
$('#' + hash + '-ping').html('<span class="label label-danger">An Error Occured: '+errorThrown+'</span>');
});
}
$('.recheck').click(function () {
var host, hash;
host = $(this).closest('tr').data('url');
hash = $(this).closest('tr').data('hash');
test(host, hash);
});
$('.recheckAll').click(function () {
$('.hostresult').each(function () {
var host, hash;
//console.log($(this));
host = $(this).data('url');
hash = $(this).data('hash');
//console.log('url: '+ host + 'hash: '+hash);
test(host, hash);
});
});
$('.recheckFailed').click(function () {
$('.checkFailed').each(function () {
var host, hash;
host = $(this).data('url');
hash = $(this).data('hash');
//console.log('url: '+ host + 'hash: '+hash);
test(host, hash);
});
});
$('.hostresult').each(function () {
var host, hash;
//console.log($(this));
host = $(this).data('url');
hash = $(this).data('hash');
//console.log('url: '+ host + 'hash: '+hash);
test(host, hash);
/*(function loop(host, hash) {
setTimeout(function () {
test(host, hash);
loop(host, hash);
}, 24000);
})(host, hash);*/
});
});
</script>
</body>
</html>
<?php
}
/* Misc at the bottom */
function pingTest($server) {
$socket = @fsockopen($server['ip'], 80, $errorNo, $errorStr, 3);
if ($errorNo == 0) {
return true;
}
return false;
}
/**
* Checks is the author tag matches the url encoded in md5
* @param String $host
*
* @return array
*/
function checkAuthor($host){
$tags = get_meta_tags('http://'.$host);
// all keys are lowercase now, and . is replaced by _ in the key.
$author = $tags['author']; // author
$authorCheck = array(
'tags' => $tags,
'host' => $host,
'meta' => $author,
'match' => $host == $author
);
return $authorCheck;
}
function httpCheck($host, $responseCodes) {
$fullUrl ='http://'.$host;
$ch = curl_init($fullUrl);
$options = array(
CURLOPT_URL => $fullUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$result = array(
'httpCode' => $http_code,
'httpDesc' => $responseCodes[$http_code],
'response' => $response
);
curl_close($ch);
return $result;
}
/**
* @param String $host
*
* @return array
*/
function processDNS($host){
$dns = array(
'NS'=> dns_get_record($host , DNS_NS),
'A'=> dns_get_record($host , DNS_A)
);
$dnsAString ='';
$dnsNSString ='';
foreach($dns['A'] as $obj){
foreach($obj as $key => $val){
$dnsAString = $dnsAString.$key.': '.$val.'<br>';
}
$dnsAString = $dnsAString.'<br>';
}
foreach($dns['NS'] as $obj){
foreach($obj as $key => $val){
$dnsNSString = $dnsAString.$key.': '.$val.'<br>';
}
$dnsNSString = $dnsNSString.'<br>';
}
return array(
'NS'=> $dnsNSString,
'A'=> $dnsAString
);
}
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
?>