所以我多年来一直致力于这个托管游戏服务器的项目,这个按钮应该生成一个 ID 号并从文本框中获取值,然后将它们保存在 .json 数据库中。
最近我更新到 php 8,这个特定按钮在我的项目中停止工作。我希望有人可以帮助我修复它以与 php 8 一起使用。
编辑:我检查了日志和 PHP 致命错误:未捕获错误:未定义常量“Servers”是错误...在这一行: $idsList = array_column($data[Servers], 'serverID');
<?php if (isset($_POST['newServer'])) {
// retrieve user input
$serverName = (isset($_POST['serverName'])) ? $_POST['serverName'] : null;
$assignedPort = (isset($_POST['assignedPort'])) ? $_POST['assignedPort'] : null;
$userName = (isset($_POST['userName'])) ? $_POST['userName'] : null;
$passWord = (isset($_POST['passWord'])) ? $_POST['passWord'] : null;
$passWord = password_hash($passWord, PASSWORD_DEFAULT); // store a hash
// get .json file
$dataBase = "../../admin_files/database.json";
$data = json_decode(file_get_contents($dataBase), true);
$idsList = array_column($data[Servers], 'serverID');
$newID = max($idsList) + 1;
$formattedID = sprintf('%06d', $newID);
$data['Servers'][] = ['serverID' => $formattedID, 'gameTitle' => '7 Days To Die', 'serverName' => $_POST['serverName'], 'assignedPort' => $_POST['assignedPort'], 'commandLine' => ''];
// insert new user credentials
$data['Users'][] = ['userName' => $userName, 'passWord' => $passWord];
// write to flat file database
file_put_contents($dataBase, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | LOCK_EX));
mkdir($formattedID);
header('Location: ' . 'servers.php'); }?>
我尝试将 php 回滚到 php 7,它再次工作,但我需要它与 php 8 一起使用。
提供的代码片段似乎使用 PHP 7 的隐式类型转换,该类型在 PHP 8 中已弃用,并且可能会导致严格类型声明的问题。为了使代码与 PHP 8 兼容,您需要将变量显式转换为其各自的数据类型。这是修改后的代码:
<?php
if (isset($_POST['newServer'])) {
// Retrieve user input and explicitly cast to their respective data types
$serverName = (isset($_POST['serverName'])) ? (string) $_POST['serverName'] : null;
$assignedPort = (isset($_POST['assignedPort'])) ? (integer) $_POST['assignedPort'] : null;
$userName = (isset($_POST['userName'])) ? (string) $_POST['userName'] : null;
$passWord = (isset($_POST['passWord'])) ? (string) $_POST['passWord'] : null;
// Hash the password securely
$passWord = password_hash($passWord, PASSWORD_DEFAULT);
// Retrieve and process the JSON database
$dataBase = "../../admin_files/database.json";
$data = json_decode(file_get_contents($dataBase), true);
// Generate a new server ID
$idsList = array_column($data['Servers'], 'serverID');
$newID = max($idsList) + 1;
$formattedID = sprintf('%06d', $newID);
// Add new server and user credentials to the JSON data
$data['Servers'][] = [
'serverID' => $formattedID,
'gameTitle' => '7 Days To Die',
'serverName' => $serverName,
'assignedPort' => $assignedPort,
'commandLine' => ''
];
$data['Users'][] = [
'userName' => $userName,
'passWord' => $passWord
];
// Update the JSON file
file_put_contents($dataBase, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | LOCK_EX));
// Create a directory for the new server
mkdir($formattedID);
// Redirect to the servers page
header('Location: ' . 'servers.php');
}
通过将变量显式转换为其各自的数据类型,您将确保与 PHP 8 严格类型强制的兼容性,并防止隐式类型转换引起的任何潜在问题。