$date = date('Y-m-d_G:i:s');
$number=array();
$command = "curl -d \"<?xml version='1.0' encoding='iso-8859-1................'//xml格式文本處理
function cur_xml($result){
$xml = simplexml_load_string($result); //XML字符串載入對象
$xml = (int) $xml->params->param->value->int;//獲取狀態碼
return $xml;
}
//html格式文本處理
function cur_html($result){
$html = preg_replace("/.*<title>/is",'',$result);//將title之前內容替換
$html = preg_replace("/<\/title>.*/is",'',$html);//將/title之後的內容替換,截取出title之前的內容
return $html;
}
//調用接口返回值
function cur_url($command) {
$url = popen($command, "r");//執行curl -d
$url = fgets($url);//取得結果
$url = mb_convert_encoding($url, "GBK", "UTF-8");//字符編碼轉換
return $url;
pclose($fp);
}
//截取關鍵字,判斷
$result=cur_url($command);
$a=substr($result,0,5);
switch ($a) {
case "<html":
echo "返回結果類型:"." html格式"."\n";
$result = cur_html($result);
$status=0;
break;
case "<?xml":
echo "返回結果類型:"." xml格式"."\n";
$result = cur_xml($result);
if ($result ==1){
$status=1;
}else{
$status=0;
}
break;
default:
$result="未知錯誤,請測試4個接口IP的連通性";
$status=0;
break;
}
$num=1;
$new=1;
//判斷文件是否存在
if (!file_exists("user_door")) {
file_put_contents("user_door", "");//文件不存在則創建文件
}
//打開文件,更新返回結果的值
$fp = fopen("user_door", "r");
$all = "";
$stat = true;//設置狀態值,用於判斷返回的結果名是否存在
//用於統計出總數
$count=file("user_door");//file會將所有行存入數組
foreach ($count as $value) {
$n = explode(',', $value);//以,分隔,存入數組
$num=$n[1]+$num;//累加所有結果出現次數
}
//遍歷文件內容,用於查找結果名是否存在,存在則更新對應的值
while (!feof($fp)) {
$s = fgets($fp, 4096);//獲取文件的一行數據
$a = explode(',', $s);//將一行數據以,分隔成數組
//結果名判斷是否存在
if ($a[0] == $result) {
$new=$a[1]+1;
//echo $new;
$a[1] = "$new\n";//更新對應的值
$s = join(',', $a);//將數組以,整合成一行字符串
$stat = false;//狀態值,說明返回結果名是存在的,並已經更新對應的值
}
$all .= $s;
}
//如果返回的結果名不存在,則插入新值
if ($stat) {
$all .= "$result,$new\n";
}
fclose($fp);//關閉連接,保存數據
//打開連接,將處理過的字符串存放文件
$fp = fopen("user_door", "w");
fwrite($fp, $all);
fclose($fp);
//每週-的11:00 將發送狀態報告
if ( date ("w")==1 && date("G:i")=="11:00")
{
$status=2;
}
echo "狀態值".$status."時間".$date."\n";
//清空上週統計數據,重新計監控數據
if ( date ("w")==1 && date("G:i")=="11:03")
{
$clear = fopen("user_door", "w");
fwrite($clear, "");
fclose($clear);
exit;//添加exit是因爲一分鐘內可能會時行兩到三次清空,可能會有誤報警。
}
//if ( $status==0 or $status==2)
//{
//將數據整合成一條字符串
$str="";
$fp1 = fopen ("user_door","r");
while (!feof($fp1))
{
$s= fgets($fp1);
$a=explode(",", $s);
$q=(int)($a[1]/$num*100)."%";//計算每種結果的百分比
//添加判斷是因爲最後會有一條空值,避免將空值整合
if ($a[0]!=FALSE){
if ($a[0]=="1"){
$a[0]="1(接口正常)";
}
if ($a[0]=="-4"){
$a[0]="-4(數據庫錯誤)";
}
$str .="狀態值:".str_replace(' ','',$a[0])."出現次數:".trim($a[1])."百分比:".$q."--";//將所有結果整合成相應格式
}
}
fclose($fp1);
$number="訪問接口總數:".$num."-"."結果分析:".$str;
echo $number;
file_get_contents()調用報警接口