php how to test if file has been uploaded completely

后端 未结 11 1530
耶瑟儿~
耶瑟儿~ 2021-02-01 15:24

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

11条回答
  •  清酒与你
    2021-02-01 16:08

    There are many different ways to solve this. Just to name a few:

    1. Use a signal file that is created before the upload and removed when it's completed.
    2. Find out if your 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).
    3. Get a list of all currently opened files in that directory by parsing the output of the UNIX/Linux 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).
    4. Check if the 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?

提交回复
热议问题