Search code examples
phpwordpressdownloadfopenreadfile

Attempting to force download via PHP


I have a PDF file stored in the uploads directory of a Wordpress stack. I am attempting to force the browser to download the PDF via AJAX.

    function get_pdf(){
    
      $file_path = realpath(WP_CONTENT_DIR).'/uploads/pdfs/12345.pdf';
    
        if (file_exists($file_path)) {
      
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            readfile($file_path, true);
                    
            exit;
           
        }
    
    }

When I run this function nothing happens. I have also attempted this approach for triggering the download:

    if (file_exists($file_path)) {


      $handle = fopen($file_path, 'rb');
      $buffer = '';

      while (!feof($handle)) {
        $buffer = fread($handle, 4096);
        echo $buffer;
        ob_flush();
        flush();
      }

      fclose($handle);
        

    }

Any suggestions on how I can debug this to get it to work?


Solution

  • When a browser navigates to a URL the response will either be displayed inline (i.e. in the browser window) or saved. Which of these happens is determined by a combination of the file type and the Content-Disposition header.

    When a browser requests data using Ajax the response will be handled by the JavaScript that made the request.

    There is no way for a response header (or anything else about the response) to make that JavaScript save the file instead of passing it to JavaScript for handling.

    The JavaScript could be written to pay attention to the Content-Disposition header but, generally speaking, the author of the JS won't need to use a header like that to decide what to do with the file.