php-test / index.php
Dooratre's picture
Update index.php
2bc2a03 verified
<?php
// Define the file path
$file = 'user.json';
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];
// Create an array with the username and password
$data = array(
'username' => $username,
'password' => $password
);
// Read the existing JSON data from the file
$jsonData = file_get_contents($file);
// Convert the JSON data to an array
$existingData = json_decode($jsonData, true);
// Add the new data to the existing array
$existingData[] = $data;
// Convert the array to JSON format
$json = json_encode($existingData);
// Save the JSON data to the file
file_put_contents($file, $json);
// Display a success message
echo 'Username and password saved successfully!';
}
// Read the JSON data from the file
$jsonData = file_get_contents($file);
// Convert the JSON data to an array
$dataArray = json_decode($jsonData, true);
?>
<!DOCTYPE html>
<html>
<head>
<title>Save User</title>
</head>
<title>User JSON Display</title>
<script>
// Fetch the user.json file
fetch('user.json')
.then(response => response.json())
.then(data => {
// Display the JSON data
document.getElementById('user-data').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('Error:', error);
});
</script>
</head>
<body>
<pre id="user-data"></pre>
<h2>Save User</h2>
<form method="POST" action="">
<label for="username">Username:</label>
<input type="text" name="username" id="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password" required><br><br>
<input type="submit" value="Save">
</form>
</body>
</html>