0

I have this form:

<form action="/test.php" method="POST">
  <input type="submit" value="Add">
</form>

which submits to test.php:

<?php

echo "Hi";

$file = 'file.txt';
$fp = fopen($file, 'r');

if (flock($fp, LOCK_EX)) { 
  $current = file_get_contents($file);
  $current .= "+\n";
  file_put_contents($file, $current);
  flock($fp, LOCK_UN); 
}

sleep(2);

I am using flock to prevent content to be overwritten by mistake.

Because of the sleep part, I can click on the Add button multiple times in a row. However, no matter how often I click the Add button while loading, in the file.txt I only find a single line:

+

I would expect that if I hit the button 5 times (while loading) I should get

+++++

Why is this not happening?


Remarks

  1. I know that there are topics out here how to prevent double submit with CSRF or with disabling the button on submit with JS (see How to prevent multiple form submission on multiple clicks in PHP). Why is there no double submit happening in my scenario?

  2. Instead of writing to a file in test.php, one could also insert a row in a database

    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "INSERT INTO user (name) VALUES ('John')";
    $conn->query($sql)
    

    where the table user has a primary auto-increment column id. Multiple clicking on the button would still only lead to one new inserted row.

Adam
  • 25,960
  • 22
  • 158
  • 247
  • Duplicate: https://stackoverflow.com/questions/51347585/how-to-submit-a-form-twice?noredirect=1#comment89899676_51347585 – Adam Jul 23 '18 at 08:45

1 Answers1

0

From your code:

file_put_contents($file, $current, LOCK_EX);

Note the LOCK_EX.

You are locking the file.

While the first process is sleeping, it is holding the file locked.

When the second request triggers the attempt to write to the file again, it fails (silently because you don't test for success), so the write with the next + doesn't happen.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you for pointing that out. I have now corrected the `LOCK_EX` part. File is locked while reading and writing and then unlocked. The problem remains. – Adam Jul 22 '18 at 11:39