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
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?
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 columnid
. Multiple clicking on the button would still only lead to one new inserted row.