Search code examples
phpmkdirtemp

php - session temp folder


Idea is this:

  1. User uploads a file(s) in some "temp" folder that exist only for current session.
  2. User registers
  3. Files form "temp" folder are moved to permanent folder aka storage.

I can do something like this:

mkdir('tempfiles/'.session_id(), 777)

And upload files:

if (move_uploaded_file($_FILES['my_files']['tmp_name'], 'tempfiles/'.session_id().'/')) {
  // echo "success";
}

When user register, files are moved to some other folder, temp folder is removed like this:

/* some function to empty dir */
rmdir('tempfiles/'.session_id())

Problem is: What if user after uploading does not register? How to remove temp folder?

With tempnam function I can create a folder that "will remove it self".. but in Windows server I can't create for example tempnam('/tmp/test', '');, just set 3 character prefix: C:\Windows\Temp\pre569E.tmp

My only idea is to write to database path of temp folders.

Any help would be most welcome.


Solution

  • If the user doesn't register, you'll have to manually go in and clean up those files. PHP will only auto-clean an upload if you've left the original temp file alone. Since you've explicitly moved it out of the upload temp directory, that means it's entirely up to you to clean up.

    You can't rmdir a non-empty directory. You must remove all the files in that directory first. Simplest method would be to do

    $files = glob('tempfiles/' . session_id());
    foreach($files as $file) {
       unlink($file);
    }
    

    Even easier is to NOT create a subdirectory for each user. Move the file out of the upload temp directory (so PHP won't auto-clean it) and store it in ANOTHER single intermediate directory with the session_id() as its filename. This limits each unregistered user to a single file held in abbeyance, but that's probably a good thing. All the users' files will be intermingled, but since each one has a unique session-based name, there's no conflict.

    You'd still have to clean up orphaned files from users who opted to not register, but that'd be a simple matter of checking if, for every one of these temporary files, there's no matching session file - if there's no session file, then the user's abandoned the session and PHP has removed the stale session file. So you can have a timed job do this cross-check and remove any of the files which have no matching session.