<?php $process = shell_exec("ps aux | grep 'ntpd' | grep -v 'grep'"); if($process){ echo 'NTP服务正在运行'; }else{ echo 'NTP服务没有运行'; } //指定文件路径和文件名 $file_path = "/etc/ntp.conf"; //判断是否收到了保存文件的请求 if(isset($_POST['content'])){ //获取客户端传来的文件内容 $content = $_POST['content']; //打开文件并进行写入操作 $handle = fopen($file_path,"w"); fwrite($handle,$content); fclose($handle); //返回成功的信息给客户端 echo json_encode(array("status" => "success")); exit; } //打开文件并读取文件内容 $handle = fopen($file_path,"r"); $content = fread($handle,filesize($file_path)); fclose($handle); echo $content; ?> 完善代码 实现 打开/etc/目录下的文件 且能够将修改后的文件保存回原路经的完整代码
时间: 2023-08-13 07:02:27 浏览: 55
好的,以下是完整代码,实现了打开和保存 NTP 配置文件 `/etc/ntp.conf` 的功能:
```php
<!DOCTYPE html>
<html>
<head>
<title>NTP配置文件编辑器</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>NTP配置文件编辑器</h1>
<hr>
<!-- 显示 NTP 服务状态 -->
<?php
$process = shell_exec("ps aux | grep 'ntpd' | grep -v 'grep'");
if ($process) {
echo "<p>NTP服务正在运行</p>";
} else {
echo "<p>NTP服务没有运行</p>";
}
?>
<hr>
<!-- 显示编辑器 -->
<form method="post">
<textarea name="content" rows="30" cols="100"><?php
// 打开文件并读取文件内容
$file_path = "/etc/ntp.conf";
$handle = fopen($file_path,"r");
$content = fread($handle,filesize($file_path));
fclose($handle);
echo htmlspecialchars($content);
?></textarea>
<br>
<input type="submit" value="保存">
</form>
<!-- 保存文件的 AJAX 代码 -->
<script>
var saveFile = function() {
// 获取编辑器中的内容
var content = document.getElementsByName("content")[0].value;
// 创建 AJAX 对象
var xhr = new XMLHttpRequest();
// 设置请求方式和 URL
xhr.open("POST", window.location.href, true);
// 设置请求头
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
xhr.send("content=" + encodeURIComponent(content));
// 监听请求状态
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理服务器返回的响应
var response = JSON.parse(xhr.responseText);
if (response.status == "success") {
alert("保存成功!");
} else {
alert("保存失败!");
}
}
};
};
// 监听保存按钮点击事件
document.querySelector("input[type='submit']").addEventListener("click", function(event) {
event.preventDefault();
saveFile();
});
</script>
</body>
</html>
```
需要注意的是:
1. 为了防止 XSS 攻击,需要使用 `htmlspecialchars` 函数对读取的文件内容进行编码后再输出到编辑器中。
2. 保存功能通过 AJAX 技术将修改后的内容发送到服务器端进行保存,具体实现方式见代码中的注释部分。
3. 为了实现保存功能,我们需要在表单中添加 `method="post"` 属性,并且在保存按钮点击事件中阻止表单默认的提交行为(即页面跳转),而是使用 `saveFile` 函数发送 AJAX 请求。