Skip to content

handle case where user closes browser window before file is sent #28

Closed
@jjdunn

Description

@jjdunn

problem:

  1. user requests a file to be downloaded
  2. file-download-link (or button) opens a new tab for the file-download target
  3. user closes the new tab before the file is downloaded
  4. tmp/File::send() does readfile() - but this fails since the browser connection has been closed
  5. readfile() throws an uncatchable Exception at this point - the only place it can be handled is the shutdown function. I tried various try/catch blocks around readfile(), none of which got invoked.
  6. after the shutdown function executes, tmp::__destruct() runs, and this fails because the file is locked by the web server, left over from readfile()
  7. unlink() in __destruct() throws a "permission denied" error

At first I wrote a (working) solution in my shutdown function, which checks for leftover open file resources of type "stream", and unlocks them; but this solution runs on every request so it's very high overhead to solve an edge-case error

solution I like better, in tmp/File::send():

        //readfile($this->_fileName);
        $fpointer = fopen($this->_fileName, 'r');
        $content = fread($fpointer, filesize($this->_fileName));
        fclose($fpointer);
        echo $content;

this works exactly the same as readfile() under normal conditions, but if the user closes the browser window, the temp files can be deleted since the lock has been released.

p.s. all of this on Windows/Apache httpd 2.4.62 with PHP 8.3.11. Maybe it would work differently on Linux or a different web server.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions