Having trouble getting PHP locking to function properly. Struggling to pinpoint the issue

Hello everyone, I am reaching out regarding my ongoing issue with the functionality of Acquire_lock() in PHP and AJAX that has not been resolved yet.

To simplify things, I have three files:

  • abc.txt
  • file1.php
  • file2.php

All these files are located in the same directory, and the content of both PHP files is identical:

<?php 
$x = fopen("/var/www/abc.txt", "w"); 
if (flock($x, LOCK_EX|LOCK_NB)) { 
print "No issues, lock acquired successfully. Ready to wait."; 
while (true) 
    sleep(5); 
} else { 
print "Failed to acquire the lock. Exiting now. Good night."; 
} 
fclose($x); 
?>

However, when I try to load either file1.php or file2.php, I always receive the second print message: "Failed to acquire the lock. Exiting now. Good night."

If anyone has any insights or solutions to this problem, or even to my previous question, I would greatly appreciate it as I am truly stuck at this point.

Thank you for your assistance.

Answer №1

To prevent the PHP script from exiting, you can implement a blocking lock.

The flock documentation suggests that you can achieve this by specifying a third parameter and removing the LOCK_NB flag.

<?php 
$x = fopen("/var/www/abc.txt", "w"); 
if (flock($x, LOCK_EX, 1)) { 
    print "I have successfully obtained the lock and will maintain it."; 
    // waiting for 5 seconds
    sleep(5);
    // Release the lock to allow the next script to run
    flock($x , LOCK_UN);
} else { 
    print "Failed to obtain the lock. Exiting now. Goodbye."; 
} 
fclose($x); 
?>

Answer №2

Here's a breakdown of what's happening in your script:

1) Your code is stuck in an infinite loop with while(true), preventing it from reaching the fclose() statement.

2) I ran tests with both File1.php and file2.php on my local server. While File1.php kept looping, file2.php immediately showed a "file is locked" message (indicating correct locking). Both files failed the lock test when refreshed afterward.

If you're using PHP > 5.3.2, remember that manual unlocking is required now:

The automatic unlocking upon closing a file handle was removed. Unlocking must now be done manually. Source

For older PHP versions, the file will unlock once the script finishes executing. Since your script endlessly loops, it never truly finishes, hence keeping the file locked.

Even if you stop the script in your browser, the php-cgi.exe process linked to that script remains active until manually terminated via task manager (I confirmed this).

Solution:

1) To resolve this issue and ensure proper file locking, remove the infinite loop to allow the script to gracefully end:

Use this revised script to lock the file for 30 seconds (loop removed):

<?php 
$x = fopen("/var/www/abc.txt", "w"); 
if (flock($x, LOCK_EX|LOCK_NB)) { 
print "No issues, I've acquired the lock, now waiting."; 
sleep(30);
fclose($x); // Always close even pre-PHP 5.3.2
} 
else { 
print "Lock couldn't be obtained. Exiting. Good night."; 
} 

?>

2) On Linux machines, utilize LOCK_NB flag to verify file locking status. Add LOCK_NB for checking file lock like so:

while ( ! flock($f, LOCK_NB) ) 
{
    sleep(1);
}

This forces the script to check for the lock every second, waiting for the other script to complete.

3) Utilize flock($fp, LOCK_UN) to explicitly release the lock instead of fclose(); In essence, your code should resemble this:

<?php 
$x = fopen("/var/www/abc.txt", "w");
while(!flock($x,LOCK_NB)
    sleep(1);

if (flock($x, LOCK_EX,true)) { 
print "No problems, I got the lock, now I'm going to sit on it."; 
sleep(30);
fflush($fp);            // flush output before releasing the lock
flock($fp, LOCK_UN);    // release the lock
} else { 
print "Didn't quite get the lock. Quitting now. Good night."; 
} 
fclose($x); 
?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transfer information from python-cgi to AJAX

Currently, I am in the process of creating a UI version of the find command found in Linux. In this implementation, I receive the location and filename parameters for the find command through a CGI form that has been built using Python. When the user submi ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

Issue with javascript code not functioning post axios request

When working on my project, I utilize axios for handling Ajax requests. I crafted a script that attaches a listener to all links and then leverages Axios to make the Ajax request. Following the Ajax request, I aim to execute some post-processing steps. Aft ...

Intrigued by the asynchronous nature of AJAX and the concept of scheduled or timed events

I have a question regarding AJAX and its asynchronous nature... When JavaScript is run while a page loads and triggers an AJAX call, the page continues to load while the server processes the AJAX request. Can this be likened to pseudo-parallelism? What h ...

Transferring information between pages in PHP

Currently, I am exploring the most effective way to pass data between two pages (Page A to Page B) using PHP for a specific scenario: Page A: This page displays a gallery of images with titles. The PHP file makes a database call to an images table, which ...

Transferring Anchor Value to the Controller

Currently, I am struggling to figure out how to pass an id to my controller using the code I have written. Below is a snippet from my cshtml file: <script> $(document).on("click", "#getDetails", function (e) { $.ajax({ u ...

Sweet alert is taking precedence over the standard alert function when used in a loop

When I call the sweet alert function inside a loop, it only shows up once. It seems like it's overriding the previous sweet alert because when I use a simple alert, it pops up twice. What I want is for the sweet alert to show the second or third alert ...

Guide to identifying a particular keyword within a vast database of text

I've been grappling with this problem for a day now, focusing on the PHP + MYSQL aspect. However, due to the large amount of data, most of the scripts I've attempted have timed out. Our database consists of two tables: People with approximatel ...

Transfer information to the form through a hyperlink

I need help with a script that sends data to a form when a link is clicked. What I'm trying to achieve is to have the data appear in the form when the user clicks the link below, which is generated from a database. <div id="menu_bar" region="west ...

Utilize AJAX to submit a form in CodeIgniter efficiently

Is there a problem with submitting a form via Ajax? The form is not being submitted as expected and the Ajax function does not seem to be picking up the submit id. It is currently submitting in the usual way, but I need it to work through Ajax. Can anyon ...

"Unique AJAX feature for manual, customized one-time payment subscriptions for adding items to cart

Hello, I am currently working on manually ajaxing this process: <a href="/cbg-gummies?add-to-cart=55337&convert_to_sub_55337=0" class="testing"> Add to cart </a> The purpose of this is to add a one-time purchase option ...

Steps for Hosting a PHP Website on Windows Server 2008

Currently, I have a PHP website up and running successfully on my local system using XAMPP. However, I now have a Windows Server 2008 and would like to host the site on this server. Unfortunately, I am unsure of how to do this and would greatly appreciat ...

Loading partial views asynchronously in Ember

Recently, I developed an Ember helper that enables the loading of a dynamically created partial view from a URL on the server. Here's how it works: Ember.Handlebars.helper('serverPartial', function(url, options) { var template; $.a ...

Track the amount of time visitors spend on my website with the help of AJAX

Looking for assistance with my Ajax script. I'm trying to track and record the amount of time a visitor spends on my website, then send that data to a PHP page: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">< ...

PHP script for conducting sensitivity analysis

I am working with a PHP application that calculates a final result based on user input in multiple forms. Imagine a scenario where a user enters a value of 5 on the first page, which is passed through _POST to the next page. Then, they enter a value of 2 ...

Employing data retrieved from an ajax response as a json object

As a newcomer to ajax and Jquery, I am attempting to display my database graphically using c3.js. However, I am facing challenges with utilizing my ajax response in a JavaScript variable. Below is the JSON response from response.php: [{"time":"2014-05-20 ...

Establish a connection to an HTTPS server using PHP

I am trying to retrieve data from a webpage hosted on a server that uses the https protocol, such as . Below is the PHP code I have been utilizing: $POSTData = array(''); $context = stream_context_create(array( 'http' => array( ...

The function echo json_encode($row) is outputting repetitive values

Here is my PHP code: $result = mysql_query("SELECT * FROM backup WHERE owner='$email'") or die(mysql_error()); $dataCount = mysql_num_rows($result); $row = mysql_fetch_array($result); echo json_encode($row); And this is the result it returns: ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

Utilizing AJAX and jQuery to dynamically load a div instantly, followed by automatic refreshing at set intervals

I am utilizing jQuery and AJAX to refresh a few divs every X seconds. I am interested in finding out how to load these divs immediately upon the page loading for the first time, and then waiting (for example, 30 seconds) before each subsequent refresh. I h ...