0

I want to send a file this lives on a path outside the web server root directory to the browser. So I will open the file from my PHP code an stream it out to the client.

On the client side this should only happen when clicking on a "open" button or on a link (-tag). In either case I will call a JS-script that should do the magic of showing the file to the client.

How would you implement that?

FernSeher
  • 177
  • 1
  • 13

1 Answers1

0

This is how i stream files from PHP outside of web access i hope this helps you understand how it works

PHP

header('Access-Control-Expose-Headers: filename');

$JSON = file_get_contents('php://input');
$data = json_decode($JSON, TRUE);
//use your json data to find the file your looking for

$file = FULL_PATH_TO_FILE;
$size = filesize($file);

    header ( 'Content-Description: File Transfer' );
    header("Content-Type: application/force-download");
    header ( 'Content-Type: application/octet-stream' );
    header ( 'Content-Disposition: attachment; filename=' . str_replace("_", " ", basename ($file)));
    header ( 'Expires: 0' );
    header ( 'Cache-Control: must-revalidate' );
    header ( 'Pragma: public' );
    header ( 'Content-Length: ' . filesize ( $file ) );
    ob_clean(); 
    flush();
    readfile ( $file );
    exit();

JS

var data = {
    ID: 1,
    FileName: “example_file_name.pdf”
}

var req = new XMLHttpRequest();
        req.open("POST", `https://api.server.com/download.php`, true);
        req.responseType = "blob";
        req.onload = (event) => {
            var blob = req.response;
            var filename = "";
            var disposition = req.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) { 
                    filename = matches[1].replace(/['"]/g, '');
                }
            }
            const href = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.download = filename;
            a.href = href;
            a.click();
        };
        req.send(JSON.stringify(data));
Anthony
  • 801
  • 10
  • 20