Determining successful download using php readfile

后端 未结 3 1541
甜味超标
甜味超标 2020-12-10 09:30

I need to know if a user selected download then clicked the cancel button, which is not the same as readfile having an error. I have inspected the count returned by the rea

相关标签:
3条回答
  • 2020-12-10 10:04

    You would first need ignore_user_abort().

    This would allow your script to continue on after the user has hit cancel, or escape.

    You would then have to print out the file and continuously check with connection_aborted().

    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header("Content-Disposition: attachment; filename=$download_name");
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize("sub/$doc_file"));
    ob_clean();
    flush();
    
    $fp=fopen("sub/$doc_file","rb");
    
    while(!feof($fp))
    {
        print(fread($fp,1024*8));
    
        flush();
        ob_flush();
        if( connection_aborted() )
        {
            //do code for handling aborts
        }
    }
    
    0 讨论(0)
  • 2020-12-10 10:13

    I fear the correct answer is "Impossible" - let me explain: You might be able to correctly figure out, when the file has crossed the wire, but you can't figure out reliably, whether the client threw it away or not.

    Example (chronological sequence):

    • A user on MSIE clicks download and is presented with the "Save where" Dialog.
    • While this dialog is open, the download is started in the background.
    • The user navigates around in the dialog or simply does nothing (phone rang, he talks)
    • The background download is finished, your script sees the download as complete
    • The user clicks on "cancel"
    • MSIE deletes the tempfile, the download is never stored in a user-accessible form

    Result:

    • The user sees the file as "not downloaded" - and he is correct
    • Your app sees the file as "correctly downloaded" - and it is correct
    0 讨论(0)
  • 2020-12-10 10:14

    Use this comment on php.net : http://www.php.net/manual/en/function.fread.php#72716 On fclose you would be able to determine if file has been downloaded successful, because your are checking if user aborted connection with connection_status()

    0 讨论(0)
提交回复
热议问题