Is there any way to check if file has been uploaded completely on the server? My scenario: User uploads file over ftp and my other PHP task is running in cronjob. Now I would li
There are many different ways to solve this. Just to name a few:
signal file
that is created before the upload and removed when it's completed.FTP server
has a configuration option
that for example gives uncompleted files the extension ".part" or locks the file on the file system level (like vsftp).lsof
command and check if the file you're checking is in that list (take Nasir's comment from above into account if you encounter permission problems).last modification
of that file is longer ago than a specific threshold.As it seems your users can use any FTP client they want, the first method (signal file) can't be used. The second and third answers need a deeper understanding of UNIX/Linux and are system dependend.
So I think that method #4
is the way to go in PHP
as long as processing latency (depending on the configured threshold) is no problem. It is straightforward and doesn't depend on any external commands:
// Threshold in seconds at which uploads are considered to be done.
$threshold = 300;
// Using the recursive iterator lets us check subdirectories too
// (as this is FTP anything is possible). Its also quite fast even for
// big directories.
$it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($uploadDir);
while($it->valid()) {
// Ignore ".", ".." and other directories. Just recursively check all files.
if (!$it->isDot() && !$it->isDir()) {
// $it->key() is the current file name we are checking.
// Just check if it's last modification was more than $threshold seconds ago.
if (time() - filemtime($it->key() > $threshold)) {
printf("Upload of file \"%s\" finished\n", $it->key());
// Your processing goes here...
// Don't forget to move the file out so that it's not identified as
// just being completed everytime this script runs. You might also mark
// it in any way you like as being complete if you don't want to move it.
}
}
$it->next();
}
I hope this helps anyone having this problem.
Similar questions:
Verify whether ftp is complete or not?
PHP: How do I avoid reading partial files that are pushed to me with FTP?