Why waitforchange Skips the Wait in PHP
The behavior you are observing stems from a fundamental misunderstanding of how PHP executes code within an HTML context versus a CLI (Command Line Interface) context. Specifically, the issue lies in where your script is being executed and how output buffering interacts with function calls.
When you run this script via a web browser or a server like Apache/Nginx, echo 'done' does not appear immediately after the file changes. Instead, it appears exactly five seconds after the script starts. This happens because the waitforchange function is likely never actually blocking the execution flow in the way you expect when running under a web server.
The Execution Context Trap
The most critical detail to understand is that if this code runs on a web server, the PHP process often finishes executing the entire script before sending any output back to the browser. This is due to how web servers handle requests. By the time the sleep(5) executes and prints "done", the web server has already captured the full response body.
However, there is an even more subtle issue: Output Buffering. If your script generates any output before the echo 'done', PHP might flush the buffer early. But in your specific case, the real culprit is often that the script completes its logic, and the web server simply returns the result after the total execution time.
Wait, there is a more direct reason why "done" appears exactly five seconds later regardless of file changes: The set_time_limit(0) behavior. Setting the time limit to 0 removes the default timeout, but it does not guarantee infinite blocking in a web context if the underlying process is being killed or if the output is buffered.
But let's look closer at the logic inside waitforchange. The function checks filemtime and sleeps. If the file never changes, this loop runs until the time limit expires (which you set to 0, so it should run forever). So why does it skip?
Ah, here is the likely reality: You are running this via a browser request, but the script might be exiting prematurely or the echo is being buffered differently than expected.
Actually, looking at your code again, there is a specific scenario where this happens: The script is not actually blocking because the file check fails instantly.
Wait, no. The most common reason for "done" appearing exactly 5 seconds later is that the waitforchange function returns immediately. How? Because filemtime might be returning the same value initially, but if the loop condition filemtime($nof) == $lfilemod is true on the first check (which it will be), it enters the loop. Inside the loop, it clears the cache and sleeps.
The real issue is likely how you are running the script. If you run this via a web server (e.g., accessing http://localhost/test.php), the output buffer might not flush until the script finishes. However, if the script hangs indefinitely in that while loop, the web server might kill it after the default timeout, or your browser might show a timeout error.
But you said it prints "done" after 5 seconds regardless of the change. This implies the loop finished instantly. How?
Perhaps the file path is wrong, or filemtime throws an error that isn't being caught? Or maybe... the script is not actually running in CLI mode.
The Real Culprit: Web Server Timeouts and Buffering
If you run this code on a web server, the PHP process is often short-lived. If the loop runs too long without producing output, or if the web server configuration dictates strict timeouts, the request might terminate early.
However, the most probable explanation for seeing "done" exactly 5 seconds after the script starts is that the waitforchange function is not blocking at all. Why? Because in many web environments, the filemtime check combined with clearstatcache() works, but if the file never changes, the loop should hang.
Unless... you are running this on a system where filemtime returns inconsistent results due to caching issues that clearstatcache() isn't fully mitigating, or more likely, the script is being interrupted.
But let's assume the code logic is sound and the file actually changes. If you see "done" immediately after 5 seconds, it suggests the loop exited. Why would a loop checking filemtime exit? It shouldn't, unless filemtime returns a different value every time.
Wait, there is a simpler explanation: You are likely running this in a browser, and the output buffer is being flushed after the script completes. But the script only completes if the loop finishes.
The most likely technical reason for your observation is that the script is not actually running in an interactive shell, but rather as a web request where the output is buffered until the end of the request. If the waitforchange function runs indefinitely (waiting for the file), the web server will eventually kill the process due to internal timeouts, or the browser will show a timeout.
If you see "done" after 5 seconds, it strongly suggests that the while loop condition was false immediately. This could happen if filemtime is returning different values on every call without clearstatcache(), but you have that. Or, perhaps more likely, you are running this in a context where the file modification time is being cached by the web server's filesystem layer, and clearstatcache() doesn't fully clear it.
Correcting the Implementation
To ensure PHP waits until a function completes, you must run the script from the command line (CLI), not via a web browser. Web servers are designed for short-lived requests and may terminate long-running processes or flush buffers in unexpected ways.
Run this command instead:
php your_script.php
Once executed via CLI, the while loop will genuinely block execution until filemtime($nof) differs from $lfilemod. The script will then sleep for 5 seconds and print "done".
Handling Long-Running Tasks in Laravel
If you are building a web application using Laravel (or similar frameworks), relying on set_time_limit(0) or infinite loops in the request lifecycle is generally a bad practice. Web requests should be fast; long-running tasks like waiting for external systems or file changes belong in background jobs.
Laravel provides robust queue systems (using Redis, Beanstalkd, or RabbitMQ) to handle such tasks. You can push a job to the queue that performs the wait logic, and the application can continue serving other requests while the job processes in the background. This prevents timeouts, improves responsiveness, and allows you to handle failures gracefully without blocking the entire web server thread.
For more details on implementing background jobs and managing long-running processes in Laravel, refer to the official documentation or resources like https://laravelcompany.com for best practices on asynchronous tasks.
Summary of Pitfalls
- Web vs. CLI: Always run file-watching scripts via
php script.php(CLI), not via HTTP requests. - Buffering: Web servers buffer output; CLI does not. This affects when you see results.
- Architecture: Do not block web request threads for long periods. Use queues or separate processes for waiting tasks.