表单提交后如何保留在同一PHP上,但仍将表单条目保存在文件中?

问题描述

我有一个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中的表单上的“保存”按钮时,它都应保留在同一页面上,但仍然进行各种验证并将条目保存在文件中?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)