Kalhan.Toress
Kalhan.Toress

Reputation: 21901

check file is completely copied (with Php)

if( completely_copied ) {
        //do some stuff
} else {
        // do some stuff
}

There are several images in a directory and images are coping to this directory every 5 seconds. How to check these images are completely copied to the directory or half copied ?

Upvotes: 0

Views: 679

Answers (2)

arkascha
arkascha

Reputation: 42915

This is a typical situation and two/three strategies are at hand:

  1. You store the files using a temporary name under which it is ignored (filtered) by subsequent processes who require the file to be complete. Then, when the copying process has finished, you rename the file. Renaming is an atomic operation on the file system, thus it either has happened or not. There is no incomplete state. This usoffers ually the kind of protection required.

  2. A variant of the above strategy is to copy and move the files (instead of copy and rename). Moving a file within a file system also is an atomic operation, so you have the same benefits. This makes sense if the copy process cannot use temporary names. You then can simply copy to a temporary directory and move the files to the final location in an atomic manner as soon as the copy process has finished.

  3. if you are on a unixoid system (Linux or some Unix flavor), then this might not even be required: the typical behavior of tasks reading and processing a file that has not yet been written completely is to block until further data is available. Thus opening, reading and processing the file typically is safe regardless of how long the writing of the file takes. The processing task simply is slowed down (blocks) until the whole file is available. You might want to give this a try, since it might safe you from having to implement anything at all. For example there is no problem in playing a 4 GB video file whilst it is still being copied. If the video player is faster than the writing process, then it blocks until further data is available. Ugly, but safe.

Upvotes: 1

hsz
hsz

Reputation: 152216

You can check md5 sum of the files with md5_file function:

if ( md5_file($pathToOriginal) == md5_file($pathToCopy) ) {
  // contents are the same
}

Above solution allows you to check if file's content is complete. However Hanky 웃 Panky has pointed, that you also may check if all of the files are copied or just a few of them. If so, you can try with:

$fiSource = new FilesystemIterator($sourceDir, FilesystemIterator::SKIP_DOTS);
$fiTarget = new FilesystemIterator($targetDir, FilesystemIterator::SKIP_DOTS);

if ( iterator_count($fiSource) == iterator_count($fiTarget) ) {
  // the amount of files in both directories is equal
}

Upvotes: 3

Related Questions