Rad'Val
Rad'Val

Reputation: 9231

Is there a way to check whether a file is completely uploaded using PHP?

I have a directory on a remote machine in which my clients are uploading (via different tools and protocols, from WebDav to FTP) files. I also have a PHP script that returns the directory structure. Now, the problem is, if a client uploads a large file, and I make a request during the uploading time, the PHP script will return the file even if it's not completely uploaded. Is there a way to check whether a file is completely uploaded using PHP?

Upvotes: 3

Views: 2217

Answers (3)

Alfred Godoy
Alfred Godoy

Reputation: 1043

Most UNIX/Linux/BSD-like operating systems has a command called lsof (lsof stands for "list open files") which outputs a list of all currently open files in the system. You can run that command to see if any process is still working with the file. If not, your upload has finished. In this example, awk is used to filter so only files will show that are open with write or read/write file handlers:

if (shell_exec("lsof | awk '\$4 ~ /.*[uw]/' | grep " . $uploaded_file_name) == '') {
    /* No file handles open for this file, so upload is finished. */
}

I'm not very familiar with Windows servers, but this thread might help you to do the same on a Windows machine (if that is what you have): How can I determine whether a specific file is open in Windows?

Upvotes: 1

Demonslay335
Demonslay335

Reputation: 796

I would think that some operating systems include a ".part" file when downloading a file, so there may be a way to check for the existence of such a file. Otherwise, I agree with Brian's answer. If you were using the script on the same system it is simple enough to tell using move_uploaded_file()'s return if it was being uploaded by a PHP script, but it does become a challenge pulling from a remote directory that can be added to with different protocols.

Upvotes: 0

Nahydrin
Nahydrin

Reputation: 13517

Setup your remote server to move uploaded files to another directory, and only query the directory files are moved to for files.

AFAIK, there is no way (at least cross-machine) to tell if a file is still being uploaded, without doing something like:

  1. Query the file's length
  2. Wait a few seconds
  3. Query the file's length
  4. If it's the same, its possibly completed

Upvotes: 6

Related Questions