index.php:
<div class="start">START</div>
<div class="content"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="script.js"></script>
update1.php:
<div class="fire">FIRE<div>
<div class="result"></div>
update2.php:
$json = array(
'unique' => uniqid(),
);
echo json_encode($json);
script.js:
$(document).off("click", ".start").on("click", ".start", function (event) {
$.ajax({
url: "update1.php",
data: {},
type: "POST",
success: function (data) {
$(".content").html(data);
}
})
});
$(document).off("click", ".fire").on("click", ".fire", function (event) {
$.ajax({
url: "update2.php",
type: "POST",
dataType: "json",
encode: true,
data: {},
success: function (data) {
$(".result").html(data.unique);
}
});
});
I load some data via Ajax and after that I load a Unique ID with json encode. It is working well. The only problem is, that on every click "FIRE" the loading of the Unique ID is getting slower and slower.
The loading time is more or less like this
...
I cannot find out, why this is happening.
The issue is with the PHP implementation of uniqid()
To avoid time-based collisions it will sleep for a given number of mircoseconds.
This can be mitigated against without losing the uniqueness that would occur in instances of time-based collision.
See detailed explaination here: Why is uniqid slow?
The key part of the solution is to set more_entropy to true to avoid time-based collisions.
By setting more_entropy to true, we choose to provide an additional source of entropy by appending data using php_combined_lcg() (a pseudo-random number generator), thus preventing time-induced collisions without having to sleep.