Question

Given a simple code like :

$file = 'hugefile.jpg';
$bckp_file = 'hugeimage-backup.jpg';
// here comes some manipulation on $bckp_file.

The assumed problem is that if the file is big or huge - let´s say a jpg - One would think that it will take the server some time to copy it (by time I mean even a few milliseconds) - but one would also assume that the execution of the next line would be much faster .. So in theory - I could end up with "no such file or directory" error when trying to manipulate file that has not yet created - or worse - start to manipulate a TRUNCATED file.

My question is how can I assure that $bckp_file was created (or in this case -copied) successfully before the NEXT line which manipulates it .

What are my options to "pause" , "delay" the next line execution until the file creation / copy was completed ?

right now I can only think of something like

if (!copy($file, $bckp_file)) {
    echo "failed to copy $file...\n";
}

which will only alert me but will not resolve anything (same like having the php error)

or

if (copy($file, $bckp_file)) {
  // move the manipulation to here ..
}

But this is also not so valid - because let´s say the copy was not executed - I will just go out of the loop without achieving my goal and without errors.

Is that even a problem or am I over-thinking it ? Or is PHP has a bulit-in mechanism to ensure that ? Any recommended practices ? any thoughts on the issue ? ??

Was it helpful?

Solution

What are my options to "pause" , "delay" the next line execution until the file is creation / copy was completes

copy() is a synchronous function meaning that code will not continue after the call to copy() until copy() either completely finishes or fails.

In other words, there's no magic involved.

if (copy(...)) { echo 'success!'; } else { echo 'failure!'; }

Along with synchronous IO, there is also asynchronous IO. It's a bit complicated to explain in technical detail, but the general idea of it is that it runs in the background and your code hooks into it. Then, whenever a significant event happens, the background execution alerts your code. For example, if you were going to async copy a file, you would register a listener to the copying that would be notified when progress was made. That way, your code could do other things in the mean time, but you could also know what progress was being made on the file.

OTHER TIPS

PHP handles file uploads by saving the whole file in a temporary directory on the server before executing any of script (so you can use $_FILES from the beginning), and it's safe to assume all functions are synchronous -- that is, PHP will wait for each line to execute before moving to the next line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top