0

Whenever I reload my website, the PHP will add a new user to my JSON file, I only want it to add a new person if they push the submit button, and that person doesn't exist in the file. Here is my PHP/HTML:

<html class="backgroundColor">
 
   <head>     <meta charset="utf-8">      <meta name="viewport"
 content="width=device-width,  initial-scale=1.0">   
 <title>repl.it</title>       <link href="style.css" rel="stylesheet"
 type="text/css" />       <link rel="stylesheet"
 href="https://fonts.googleapis.com/css?family=Quicksand"/>       <link
 rel="icon" href="Images/avatar.jpg" />   </head>
 
   <body style="font-family: 'Quicksand'">
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     <script src="script.js"></script>
 
     <div class="block">
       <h2>Users:</h2>
       <?php
       if($_SERVER['REQUEST_METHOD'] === 'POST')
       {
         if(isset($_POST["btnSubmit"]))
         {
           $file = "Users/users.json";
 
           $users->FirstName = htmlspecialchars($_POST["firstName"]);
           $users->LastName = htmlspecialchars($_POST["lastName"]);
           $users->Age = htmlspecialchars($_POST["userAge"]);
           $users->School = htmlspecialchars($_POST["school"]);
           $users->Sin = htmlspecialchars($_POST["sin"]);
           $users->Gender = htmlspecialchars($_POST["gender"]);
 
           $myJSON = json_encode($users, JSON_PRETTY_PRINT);
 
           file_put_contents($file, $myJSON, FILE_APPEND | LOCK_EX);
         }
       }
     </div>
 
     <div class="block">
       <h2>User Registration</h2>
       <form method="post" name="regForm">
         <p>First Name:</p><br><input type="text" name="firstName" value="First Name"><br>
         <p>Last Name:</p><br><input type="text" name="lastName" value="Last Name"><br>
         <p>Age:</p><br><input type="text" name="userAge" style="width: 10vw;" value="Age"><br>
         <p>School:   </p><br><input type="text" name="school" value="School"><br>
         <p>Social Insurance Number:</p><br><input type="text" name="sin" value="SIN"><br>
         <p>Male</p><input type="radio" name="gender" id="male" value="male"><p>Female</p><input type="radio" name="gender"
 id="female" value="female"><br>
         <input type="submit" name="btnSubmit" onclick="submitForm();">
       </form>
     </div>
        </body> </html>

What can I do to the code, so that it won't add a new user every time I reload?

aynber
  • 22,380
  • 8
  • 50
  • 63

1 Answers1

0

Simply add this script to your html:

<script>
  window.addEventListener("load",function(){
    if(window.history.replaceState) {
      window.history.replaceState(null, null, window.location.href);
    }
  });
</script>

Also, please end your if statment and PHP block } ?>

Source: How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Seth B
  • 1,014
  • 7
  • 21