【发布时间】:2020-09-20 22:27:25
【问题描述】:
我有一个 html 表单,我想在其中使用 php 将所有字段的所有条目保存到一个文件中。
- 如果我能够成功保存条目,那么我想弹出消息说
{bytes} bytes written to file。 - 如果我无法成功写入,那么我想弹出消息说
There was an error writing this file。 - 如果用户没有写权限,那么它应该给出弹出消息 -
Write access revoked。
我从表单操作中调用save.php 文件以将所有条目保存在文件中并添加一些验证。
下面是我的index.php 文件,里面有表格-
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (! check_auth()) {
redirect('login.php');
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1>
<a href="logout.php">Logout</a>
</div>
<div>
<p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
</div>
<form action="save.php" method="POST">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
下面是我的save.php 文件-
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (!check_auth())
{
redirect('login.php');
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (!isWriteAccess())
{
echo json_encode(['success' => false, 'message' => 'Write access revoked', ]);
return;
}
// Your code here...
if (isset($_POST['field1']) && isset($_POST['field2']))
{
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('mydata.txt', $data, LOCK_EX);
if ($ret === false)
{
die('There was an error writing this file');
}
else
{
echo "$ret bytes written to file";
}
}
else
{
die('no post data to process');
}
}
问题陈述
到目前为止,每当我单击index.php 中的表单上的保存按钮时,它只会在我的浏览器上打印所有内容作为响应,并且还会重定向到save.php,但我不希望那样。我想在弹出窗口上显示所有消息,但它应该保留在同一个 index.php 文件中。
- 如果我能够成功写入文件,那么我应该会看到
some bytes written to the file作为弹出窗口,但它应该只保留在index.php文件中。 - 如果存在写访问问题,则应将
Write access revoked显示为弹出窗口,但应仅保留在index.php文件中。
如何确保每当我单击 index.php 中表单上的保存按钮时,它应该保持在同一页面上,但仍会进行各种验证并将条目保存在文件中?
【问题讨论】: