プロセスを繰り返さないように、結果がセッションに保持されていることを確認したら、jQuery を使用して結果をサーバーにポーリングできます。それが役に立てば幸い:
<?php
/*Start a session to hold the results this will stop
multiple online checks from the same user.
*/
session_start();
//The urls you want to check
$urls = array('example'=>'http://example.com',
'stackoverflow'=>'http://stackoverflow.com',
'test'=>'http://test.com',
'google'=>'http://google.com');
//Is it an ajax request from jQuery
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
//Set the return content type
header('Content-Type: application/json');
//Cache the online checks in user session and for 1 hour on filesystem
if(!isset($_SESSION['status'])){
if(file_exists('cache.txt') && (time() - 3600 < filemtime('cache.txt'))){
$_SESSION['status'] = json_decode(file_get_contents('cache.txt'),true);
}else{
$_SESSION['status'] = array();
//Loop through the $urls array and ping the site using the curl function below
foreach($urls as $key=>$url){
$_SESSION['status'][$key]=get_site($url);
}
//Update cache
file_put_contents('cache.txt',json_encode($_SESSION['status']));
}
}
//Echo the json string back to jQuery
echo json_encode($_SESSION['status']);
die;
}
//The curl function to check if the site is online
function get_site($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT,2);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200){
return 'Online';
}else{
return 'Offline';
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Online Check</title>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
function pollresults(){
setTimeout(function(){
$.ajax({ url: "./test_server.online.php", cache: false,
success: function(data){
<?php
//Loop through the $urls array and build a simple replaceWith
foreach($urls as $key=>$value){
echo '$("#'.$key.'").replaceWith("<p id=\"'.$key.'\">"+data.'.$key.'+"</p>");'.PHP_EOL;
}
?>
pollresults();
}, dataType: "json"});
}, 1000);
}
$(document).ready(function(){
pollresults();
});
</script>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="50%">
<tr>
<td width="50%">Site:</td>
<td width="50%">Status:</td>
</tr>
<?php foreach($urls as $key=>$value):?>
<tr>
<td width="50%"><a href="<?php echo $value;?>"><?php echo $value;?></a></td>
<td width="50%"><p id="<?php echo $key;?>">Checking</p></td>
</tr>
<?php endforeach;?>
</table>
</body>
</html>
スクリプトをコピーしてtest_server.online.phpというファイルに貼り付けてテストするだけです。