Let’s try to add a loop that checks the file size every few seconds and proceed only if the size hasn’t changed within the loop. This is not a foolproof method, as it assumes that the file size will change when it’s being written, and it may introduce a delay in processing, but it could solve your problem in most cases.
Here’s a modified version of your code that checks the file size in a loop:
<?php
header('Content-Type: text/plain');
if (preg_match('/(GRLevel2|GRLevel3|GR2Analyst)/', $_SERVER['HTTP_USER_AGENT'])) {
$filePath = "Strikes(US).txt";
$tries = 5; // Number of tries
$waitSeconds = 2; // Time to wait between each try
for ($i = 0; $i < $tries; $i++) {
clearstatcache(); // Clear the file status cache
$sizeBefore = filesize($filePath);
sleep($waitSeconds);
clearstatcache(); // Clear the file status cache again
$sizeAfter = filesize($filePath);
if ($sizeBefore == $sizeAfter) {
echo file_get_contents($filePath);
break;
}
// If this is the last loop iteration and the file is still changing, handle the error as needed
if ($i == $tries - 1) {
echo "File is being updated. Please try again later.";
}
}
} else {
echo 'Please Copy & Paste the URL directly into your GRLevelX Placefile Manager!';
exit;
}
?>
This code will attempt to read the file up to 5 times (as defined by $tries
), waiting 2 seconds between each attempt (as defined by $waitSeconds
). If the file size hasn’t changed within that time, the file contents will be echoed out. If the loop finishes and the file size is still changing, an error message will be echoed.
Please note that the clearstatcache()
function is used to clear PHP’s internal cache of information about the file. Without this, PHP might return cached information about the file size, which could cause this loop to exit prematurely.
Also, note that this method does not actually check if the file is being written to; it only checks if the size has changed. If the file is being written in a way that doesn’t change the size, or if the writes are happening faster than the loop’s delay, this method might not work. It’s a workaround that might work for your specific use case, but it’s worth testing thoroughly to make sure it meets your needs. Good luck, if you have not yet got the solution, use this