On a page, I have 2 different jQuery ajax calls to 2 different php scripts.
In each, a mysqli connection is established with a database on a remote server (2 different remote servers).
Sometimes, the server that the first script is trying to connect to can be offline. When this is the case, the $db->real_connect command timeout (which I set to a few seconds), which isn't an issue.
What I don't understand is that, while the $db->real_connect command is running (waiting for timeout) in the first script, and the second script is ajax-called, the second script will pause at its $db->real_connect line until the first script is done trying to connect.
I thought is might be a mysqli setting but I have max_links and max_persistents both set to no limit (-1). Any other settings relating to this? If not, what is the cause of this behavior?
Here is so abridged code that should replicate the issue :
Page:
<script>
var session_id = '<?php echo session_id();?>';
$.ajax({
type: "POST",
url: "script1.php",
beforeSend: function (xhr) {
xhr.setRequestHeader('Set-Cookie', 'PHPSESSID=' + session_id);
},
success: function(result) {
console.log("Script 1 done");
}
});
$.ajax({
type: "POST",
url: "script2.php",
beforeSend: function (xhr) {
xhr.setRequestHeader('Set-Cookie', 'PHPSESSID=' + session_id);
},
success: function(result) {
console.log("Script 2 done");
}
});
<script>
script1.php (offline mysql host) :
session_start();
$db = mysqli_init();
$db->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);
$db->real_connect($host, $username, $pass, $dbname); // This hangs for 5 seconds then fails.
script2.php (different mysql host, online) :
session_start();
$db = new mysqli($host2, $username2, $pass2, $dbname2); // This also hangs for 5 seconds then succeed.
When running the page, after a 5 seconds delay, both logs appear in the console. If I swap the order of script1 and script2 in the Javascript, "Script 2 done" appears instantly and "Script 1 done" 5 seconds later. It seems like only 1 simultaneous connect operation is allowed, any way around that? How would you solve this issue?
Thanks
Thanks to smith in the comments for the solution.
The issue was session blocking. As I ignored, the file where PHP write $_SESSION variables for an user is locked once you call session_start(), and no other script can access it until you close or the script using it ends. My second script was waiting for this file to become available.
A simple solution is to add session_write_close() immediately after session_start(), if you don't plan on writing session variables. (The variables stay loaded).
I checked this page for more information : http://konrness.com/php5/how-to-prevent-blocking-php-requests/