我正在尝试制作一个脚本,可以在其中检查服务器的服务器状态(在线/离线),例如:Teamspeek、Minecraft 等。
我找到了这个脚本:
<?php
function getStatus($ip,$port){
$socket = @fsockopen($ip, $port, $errorNo, $errorStr, 3);
if(!$socket) return "offline";
else return "online";
}
echo getStatus("server.com", "80");
?>
但是我不需要更改服务器名称和端口,而是从 mysql 数据库中获取它。 所以我做了这个,但我的问题是:我无法将字符串连接到脚本。 我获取字符串的代码如下所示:
<?php
// Check to see the URL variable is set and that it exists in the database
if (isset($_GET['id'])) {
// Connect to the MySQL database
include "connect_mysql.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
// Use this var to check to see if this ID exists, if yes then get the product
// details, if no then exit this script and give message why
$sql = mysql_query("SELECT * FROM servers WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
// get all the product details
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$ip = $row["ip"];
$port = $row["port"];
$getit = $row["getit"];
$name = $row["name"];
$content = $row["content"];
}
} else {
echo "That item does not exist.";
exit();
}
}
?>
所以我想我可以将 echo getStatus("server.com", "80");
更改为 echo getStatus("$ip", "$port");
但这是行不通的。
有人知道我必须做什么吗?
最佳答案
首先要做的事情。使用 mysqli_ 而不是 mysql。
其次,如果将结果限制为 1,则不需要 while 循环。
现在,当您在get方法中获取id时,您可以在数据库中检查它并获取详细信息:
从数据库中获取详细信息后,您必须触发函数 getStatus()。
if ($productCount == 1){
echo getStatus($row["ip"],$row["port"]);
} else {
echo "That item does not exist.";
}
关于php - 我在检查服务器状态时遇到一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19135761/