I have a html form in which I want to save all the entries of all the fields into a file using php.
- If I am able to save entries successfully then I want to give popup message saying
{bytes} bytes written to file
. - If I am not able to write successfully then I want to give popup message saying
There was an error writing this file
. - And if the user doesn't have write access then it should give popup message -
Write access revoked
.
I call save.php
file from the form action to save all the entries in a file and add do some sort of validations.
Below is my index.php
file which has form in it -
<?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>
And below is my save.php
file -
<?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');
}
}
Problem Statement
As of now whenever I click save button on my form which is in index.php
, it just prints everything on my browser as the response and also redirects to save.php
but I don't want that. I want to show all messages on popup window but it should stay on same index.php
file.
- If I am able to write successfully to the file, then I should see
some bytes written to the file
as a popup but it should stay onindex.php
file only. - If there is a write access issue then it should show
Write access revoked
as a popup but it should stay onindex.php
file only.
How can I make sure that whenever I click save button on my form which is in index.php it should stay on the same page but still do all sorts of validations and save entries in a file?