How to keep checking for a file until it exists, then provide a link to it

Nick Brunt picture Nick Brunt · May 3, 2011 · Viewed 13.2k times · Source

I'm calling a Java program with a PHP system call. The Java program takes a while to run but will eventually produce a PDF file with a known filename.

I need to keep checking for this file until it exists and then serve up a link to it. I assume a while loop will be involved but I don't want it to be too resource intensive. What's a good way of doing this?

Answer

CSᵠ picture CSᵠ · May 3, 2011

Basically you got it right

while (!file_exists($filename)) sleep(1);
print '<a href="'.$filename.'">download PDF</a>';

the sleep gives 1 second between checks so it won't stress your CPU for nothing