I have a file on a server path and would like to be able to send it to the browser.
I have tried something like this:
<?php
$filepath = '/var/tmp/apiRest/download/'.$rst;
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
flush(); // Flush system output buffer
readfile($filepath);
exit();
}
If the variable $filepath
contains the name of the file in the form of a variable $rst
, it does not download the file, but if I put the full path by hand it does.
$filepath = '/var/tmp/apiRest/download/prueba.txt';
Doing a echo
of the variable $rst
, it gives me the name of the file but something fails when concatenating.
The call to PHP from the browser, using javascript, is done as follows:
function loadDoc(id){ //funcion que me carga un documento y lo guarda en download
var parametros = {
"id": id,
}
$.ajax({
data: parametros,
url: "php/PlnDir/load_doc.php",
type: "POST",
success: function (data) {
window.open("php/PlnDir/load_doc.php");
}
});
}
XHR
The problem you have is that you areXMLHttpRequest
requesting the file using the methodPOST
and sending the file identifier through the variableid
:So far everything is fine, but you can't trigger the download of a file through a request
XHR
if you don't add additional code (I'll show how to do it in a future edition).To solve this problem you have tried to open the PHP in a new window:
The problem is that the opened window will load the PHP file using the
GET
normal method, without sending any data in the variableid
(and it doesn't do itPOST
as expected either), so this new request will fail and it won't find any file to download if you try do the SQL lookup with$_POST['id']
.To detect a failed delivery of the parameter
id
you could have done the following check in the PHP file:There are two solutions to the problem. The simplest is to correctly send the parameter by
POST
to the new window. For this we can create a form whose fieldid
is not visible and that it is loaded in_blank
(new window):The most complex involves creating a
Blob
from the data received byXHR
, loading it into a label<a>
and forcing it to click. In this other answer I have created an example of how to do it.you could include the file using the include function