Download file from Server PHP
I would like to download a server image using PHP. Specifications:
- I do not want to use javascript and I do not want to pass the name by database and then retrieve it.
- The image I want to download is a QR code that I generated and saved in a "php_action / temp" directory. Within this directory there are several images, so I am trying to download only the file I have generated.
I added the phpqrcode library and created a file that calls this library to generate the QR code. This file is show_product2.php in root.
I am not able to get download the file.
//set it to writable location, a place for temp generated PNG files
session_start();
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'php_action'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "phpqrcode/qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'test.png';
//processing form input
//remember to sanitize user input in real-life solution !!!
$errorCorrectionLevel = 'L';
if (isset($_REQUEST['level']) && in_array($_REQUEST['level'],
array('L','M','Q','H')))
$errorCorrectionLevel = $_REQUEST['level'];
$matrixPointSize = 4;
if (isset($_REQUEST['size']))
$matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
if (isset($_REQUEST['data'])) {
//it's very important!
if (trim($_REQUEST['data']) == '')
die('Introduzca la Referencia del Producto en el campo "Referencia"
y haga clic en "Generar", no puede dejar en blanco los datos! <a
href="?">Regresar</a>');
$ReferenciaProducto = $_REQUEST['data'];
// user data
$filename = $PNG_TEMP_DIR.$ReferenciaProducto.''
.md5($_REQUEST['data'].'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
$filename2 = $ReferenciaProducto.'- '.md5($_REQUEST['data']
.'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
$_SESSION['filename']=$filename2;
} else {
//default data
echo 'La Imagen QR que aparece por defecto, es de prueba, hasta que no
introduzca la referncia en el campo inferior y presione "Generar" no
se visualizará la imagen definitiva"<hr/>';
QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
}
//display generated file
// echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo '<img
src="'.'php_action'.DIRECTORY_SEPARATOR.$PNG_WEB_DIR
.basename($filename).'" /><hr/>';
//.'php_action'.DIRECTORY_SEPARATOR.
//config form
echo '<form action="show_product2.php" method="post">
Ref: <input name="data" value="'.(isset($_REQUEST['data'])?
htmlspecialchars($_REQUEST['data']):'Escriba Ref.de Producto').'" />
Definición: <select name="level">
<option value="L"'.(($errorCorrectionLevel=='L')?' selected':'').'>L
- Muy Baja</option>
<option value="M"'.(($errorCorrectionLevel=='M')?'
selected':'').'>Baja</option>
<option value="Q"'.(($errorCorrectionLevel=='Q')?'
selected':'').'>Media</option>
<option value="H"'.(($errorCorrectionLevel=='H')?'
selected':'').'>Alta - La Mejor</option>
</select>
Tamaño: <select name="size">';
for($i=1;$i<=10;$i++)
echo '<option value="'.$i.'"'.(($matrixPointSize==$i)?'
selected':'').'>'.$i.'</option>';
echo '</select>
**strong text** <input type="submit" value="GENERAR"></form><hr/>';
?>
<center>
<?php echo "<form method='get' action='php_action/downloadQr.php?
Descargar='".$_SESSION['filename'].">";?>
echo' <button class="btn btn-default button3" data-toggle="submit"
name="Descargar" data-target = "Descarga"><i class="glyphicon glyphicon-
download-alt"></i> Descargar Qr en su Computadora </button>
<button class="btn btn-default button3" data-toggle="submit"
id="GuardarQRlBtn" data-target="#GuardarQRlBtn"> <i class="glyphicon
glyphicon-tasks"></i> Guardar Qr en el Servidor </button></form>';
</center>
I have created in another directory a function that is called to download the file. This function is in "includes / functions.php." Since in the previous code this function is called by: "includes / functions.php";
function descargar($fichero){
$basefichero = basename($fichero);
$filename = 'php_action/temp'.$basefichero;
if (!empty($basefichero) && file_exists($basefichero)){
header('Content-Type:
application/vnd.openxmlformats-
officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;
filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
}
}
?>
When I insert the product reference and press "Generate", the code works fine, because the QR creates a name followed by a random extension and saves it in my "temp" directory with png format. I have included a control point that forces the program to write the reference of the image on the screen that is saved inside the variable "$ filename2" in the code, this impression is generated well so the variable is passed correctly.
When once it is generated the image which is in the variable path "$filename" and in the name of the file as I said in "$ filename2" and I press the button "Download QR on your computer" the program searchs the file where are the instructions to call the download function that is the file (downloadQr.php):
<?php
session_start();
include "includes/functions.php";
if(isset($_GET['Descargar'])) {
echo $_SESSION['filename'];
descargar($_SESSION['filename']);
}
?>
As a control method I insert again in this file the instruction "echo $ _SESSION ['filename'];" so that I am impressed with the name of the file that is now saved in the global variable "$ _SESSION" already in the previous file "show_product2.php" I had created for the name of the image file "$ filename2". And indeed the name of the file is received in the variable, therefore, so far so good.
Finally the action begins to go through the instructions, prints again in my "echo" control the name of the image file, that means that it receives it, but here it stops, the blank screen with the name of the file is left but it does not download the file. So I think, by deduction, the error must be in the function "descargar()" but I do not know what it fails. I have described this function above. The variables with the file name of the image are passed correctly from one file to another and to the function.
I appreciate any help.
php image server downloadfile
add a comment |
I would like to download a server image using PHP. Specifications:
- I do not want to use javascript and I do not want to pass the name by database and then retrieve it.
- The image I want to download is a QR code that I generated and saved in a "php_action / temp" directory. Within this directory there are several images, so I am trying to download only the file I have generated.
I added the phpqrcode library and created a file that calls this library to generate the QR code. This file is show_product2.php in root.
I am not able to get download the file.
//set it to writable location, a place for temp generated PNG files
session_start();
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'php_action'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "phpqrcode/qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'test.png';
//processing form input
//remember to sanitize user input in real-life solution !!!
$errorCorrectionLevel = 'L';
if (isset($_REQUEST['level']) && in_array($_REQUEST['level'],
array('L','M','Q','H')))
$errorCorrectionLevel = $_REQUEST['level'];
$matrixPointSize = 4;
if (isset($_REQUEST['size']))
$matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
if (isset($_REQUEST['data'])) {
//it's very important!
if (trim($_REQUEST['data']) == '')
die('Introduzca la Referencia del Producto en el campo "Referencia"
y haga clic en "Generar", no puede dejar en blanco los datos! <a
href="?">Regresar</a>');
$ReferenciaProducto = $_REQUEST['data'];
// user data
$filename = $PNG_TEMP_DIR.$ReferenciaProducto.''
.md5($_REQUEST['data'].'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
$filename2 = $ReferenciaProducto.'- '.md5($_REQUEST['data']
.'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
$_SESSION['filename']=$filename2;
} else {
//default data
echo 'La Imagen QR que aparece por defecto, es de prueba, hasta que no
introduzca la referncia en el campo inferior y presione "Generar" no
se visualizará la imagen definitiva"<hr/>';
QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
}
//display generated file
// echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo '<img
src="'.'php_action'.DIRECTORY_SEPARATOR.$PNG_WEB_DIR
.basename($filename).'" /><hr/>';
//.'php_action'.DIRECTORY_SEPARATOR.
//config form
echo '<form action="show_product2.php" method="post">
Ref: <input name="data" value="'.(isset($_REQUEST['data'])?
htmlspecialchars($_REQUEST['data']):'Escriba Ref.de Producto').'" />
Definición: <select name="level">
<option value="L"'.(($errorCorrectionLevel=='L')?' selected':'').'>L
- Muy Baja</option>
<option value="M"'.(($errorCorrectionLevel=='M')?'
selected':'').'>Baja</option>
<option value="Q"'.(($errorCorrectionLevel=='Q')?'
selected':'').'>Media</option>
<option value="H"'.(($errorCorrectionLevel=='H')?'
selected':'').'>Alta - La Mejor</option>
</select>
Tamaño: <select name="size">';
for($i=1;$i<=10;$i++)
echo '<option value="'.$i.'"'.(($matrixPointSize==$i)?'
selected':'').'>'.$i.'</option>';
echo '</select>
**strong text** <input type="submit" value="GENERAR"></form><hr/>';
?>
<center>
<?php echo "<form method='get' action='php_action/downloadQr.php?
Descargar='".$_SESSION['filename'].">";?>
echo' <button class="btn btn-default button3" data-toggle="submit"
name="Descargar" data-target = "Descarga"><i class="glyphicon glyphicon-
download-alt"></i> Descargar Qr en su Computadora </button>
<button class="btn btn-default button3" data-toggle="submit"
id="GuardarQRlBtn" data-target="#GuardarQRlBtn"> <i class="glyphicon
glyphicon-tasks"></i> Guardar Qr en el Servidor </button></form>';
</center>
I have created in another directory a function that is called to download the file. This function is in "includes / functions.php." Since in the previous code this function is called by: "includes / functions.php";
function descargar($fichero){
$basefichero = basename($fichero);
$filename = 'php_action/temp'.$basefichero;
if (!empty($basefichero) && file_exists($basefichero)){
header('Content-Type:
application/vnd.openxmlformats-
officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;
filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
}
}
?>
When I insert the product reference and press "Generate", the code works fine, because the QR creates a name followed by a random extension and saves it in my "temp" directory with png format. I have included a control point that forces the program to write the reference of the image on the screen that is saved inside the variable "$ filename2" in the code, this impression is generated well so the variable is passed correctly.
When once it is generated the image which is in the variable path "$filename" and in the name of the file as I said in "$ filename2" and I press the button "Download QR on your computer" the program searchs the file where are the instructions to call the download function that is the file (downloadQr.php):
<?php
session_start();
include "includes/functions.php";
if(isset($_GET['Descargar'])) {
echo $_SESSION['filename'];
descargar($_SESSION['filename']);
}
?>
As a control method I insert again in this file the instruction "echo $ _SESSION ['filename'];" so that I am impressed with the name of the file that is now saved in the global variable "$ _SESSION" already in the previous file "show_product2.php" I had created for the name of the image file "$ filename2". And indeed the name of the file is received in the variable, therefore, so far so good.
Finally the action begins to go through the instructions, prints again in my "echo" control the name of the image file, that means that it receives it, but here it stops, the blank screen with the name of the file is left but it does not download the file. So I think, by deduction, the error must be in the function "descargar()" but I do not know what it fails. I have described this function above. The variables with the file name of the image are passed correctly from one file to another and to the function.
I appreciate any help.
php image server downloadfile
At a quick glance, you have a typo:header("Content-Transfer-Encoding: binay");
. Should bebinary
, notbinay
.
– JonJ
Nov 19 '18 at 15:10
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.
– JonJ
Nov 19 '18 at 15:53
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19
add a comment |
I would like to download a server image using PHP. Specifications:
- I do not want to use javascript and I do not want to pass the name by database and then retrieve it.
- The image I want to download is a QR code that I generated and saved in a "php_action / temp" directory. Within this directory there are several images, so I am trying to download only the file I have generated.
I added the phpqrcode library and created a file that calls this library to generate the QR code. This file is show_product2.php in root.
I am not able to get download the file.
//set it to writable location, a place for temp generated PNG files
session_start();
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'php_action'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "phpqrcode/qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'test.png';
//processing form input
//remember to sanitize user input in real-life solution !!!
$errorCorrectionLevel = 'L';
if (isset($_REQUEST['level']) && in_array($_REQUEST['level'],
array('L','M','Q','H')))
$errorCorrectionLevel = $_REQUEST['level'];
$matrixPointSize = 4;
if (isset($_REQUEST['size']))
$matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
if (isset($_REQUEST['data'])) {
//it's very important!
if (trim($_REQUEST['data']) == '')
die('Introduzca la Referencia del Producto en el campo "Referencia"
y haga clic en "Generar", no puede dejar en blanco los datos! <a
href="?">Regresar</a>');
$ReferenciaProducto = $_REQUEST['data'];
// user data
$filename = $PNG_TEMP_DIR.$ReferenciaProducto.''
.md5($_REQUEST['data'].'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
$filename2 = $ReferenciaProducto.'- '.md5($_REQUEST['data']
.'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
$_SESSION['filename']=$filename2;
} else {
//default data
echo 'La Imagen QR que aparece por defecto, es de prueba, hasta que no
introduzca la referncia en el campo inferior y presione "Generar" no
se visualizará la imagen definitiva"<hr/>';
QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
}
//display generated file
// echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo '<img
src="'.'php_action'.DIRECTORY_SEPARATOR.$PNG_WEB_DIR
.basename($filename).'" /><hr/>';
//.'php_action'.DIRECTORY_SEPARATOR.
//config form
echo '<form action="show_product2.php" method="post">
Ref: <input name="data" value="'.(isset($_REQUEST['data'])?
htmlspecialchars($_REQUEST['data']):'Escriba Ref.de Producto').'" />
Definición: <select name="level">
<option value="L"'.(($errorCorrectionLevel=='L')?' selected':'').'>L
- Muy Baja</option>
<option value="M"'.(($errorCorrectionLevel=='M')?'
selected':'').'>Baja</option>
<option value="Q"'.(($errorCorrectionLevel=='Q')?'
selected':'').'>Media</option>
<option value="H"'.(($errorCorrectionLevel=='H')?'
selected':'').'>Alta - La Mejor</option>
</select>
Tamaño: <select name="size">';
for($i=1;$i<=10;$i++)
echo '<option value="'.$i.'"'.(($matrixPointSize==$i)?'
selected':'').'>'.$i.'</option>';
echo '</select>
**strong text** <input type="submit" value="GENERAR"></form><hr/>';
?>
<center>
<?php echo "<form method='get' action='php_action/downloadQr.php?
Descargar='".$_SESSION['filename'].">";?>
echo' <button class="btn btn-default button3" data-toggle="submit"
name="Descargar" data-target = "Descarga"><i class="glyphicon glyphicon-
download-alt"></i> Descargar Qr en su Computadora </button>
<button class="btn btn-default button3" data-toggle="submit"
id="GuardarQRlBtn" data-target="#GuardarQRlBtn"> <i class="glyphicon
glyphicon-tasks"></i> Guardar Qr en el Servidor </button></form>';
</center>
I have created in another directory a function that is called to download the file. This function is in "includes / functions.php." Since in the previous code this function is called by: "includes / functions.php";
function descargar($fichero){
$basefichero = basename($fichero);
$filename = 'php_action/temp'.$basefichero;
if (!empty($basefichero) && file_exists($basefichero)){
header('Content-Type:
application/vnd.openxmlformats-
officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;
filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
}
}
?>
When I insert the product reference and press "Generate", the code works fine, because the QR creates a name followed by a random extension and saves it in my "temp" directory with png format. I have included a control point that forces the program to write the reference of the image on the screen that is saved inside the variable "$ filename2" in the code, this impression is generated well so the variable is passed correctly.
When once it is generated the image which is in the variable path "$filename" and in the name of the file as I said in "$ filename2" and I press the button "Download QR on your computer" the program searchs the file where are the instructions to call the download function that is the file (downloadQr.php):
<?php
session_start();
include "includes/functions.php";
if(isset($_GET['Descargar'])) {
echo $_SESSION['filename'];
descargar($_SESSION['filename']);
}
?>
As a control method I insert again in this file the instruction "echo $ _SESSION ['filename'];" so that I am impressed with the name of the file that is now saved in the global variable "$ _SESSION" already in the previous file "show_product2.php" I had created for the name of the image file "$ filename2". And indeed the name of the file is received in the variable, therefore, so far so good.
Finally the action begins to go through the instructions, prints again in my "echo" control the name of the image file, that means that it receives it, but here it stops, the blank screen with the name of the file is left but it does not download the file. So I think, by deduction, the error must be in the function "descargar()" but I do not know what it fails. I have described this function above. The variables with the file name of the image are passed correctly from one file to another and to the function.
I appreciate any help.
php image server downloadfile
I would like to download a server image using PHP. Specifications:
- I do not want to use javascript and I do not want to pass the name by database and then retrieve it.
- The image I want to download is a QR code that I generated and saved in a "php_action / temp" directory. Within this directory there are several images, so I am trying to download only the file I have generated.
I added the phpqrcode library and created a file that calls this library to generate the QR code. This file is show_product2.php in root.
I am not able to get download the file.
//set it to writable location, a place for temp generated PNG files
session_start();
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'php_action'.DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "phpqrcode/qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'test.png';
//processing form input
//remember to sanitize user input in real-life solution !!!
$errorCorrectionLevel = 'L';
if (isset($_REQUEST['level']) && in_array($_REQUEST['level'],
array('L','M','Q','H')))
$errorCorrectionLevel = $_REQUEST['level'];
$matrixPointSize = 4;
if (isset($_REQUEST['size']))
$matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
if (isset($_REQUEST['data'])) {
//it's very important!
if (trim($_REQUEST['data']) == '')
die('Introduzca la Referencia del Producto en el campo "Referencia"
y haga clic en "Generar", no puede dejar en blanco los datos! <a
href="?">Regresar</a>');
$ReferenciaProducto = $_REQUEST['data'];
// user data
$filename = $PNG_TEMP_DIR.$ReferenciaProducto.''
.md5($_REQUEST['data'].'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
$filename2 = $ReferenciaProducto.'- '.md5($_REQUEST['data']
.'|'
.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
$_SESSION['filename']=$filename2;
} else {
//default data
echo 'La Imagen QR que aparece por defecto, es de prueba, hasta que no
introduzca la referncia en el campo inferior y presione "Generar" no
se visualizará la imagen definitiva"<hr/>';
QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel,
$matrixPointSize, 2);
}
//display generated file
// echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo '<img
src="'.'php_action'.DIRECTORY_SEPARATOR.$PNG_WEB_DIR
.basename($filename).'" /><hr/>';
//.'php_action'.DIRECTORY_SEPARATOR.
//config form
echo '<form action="show_product2.php" method="post">
Ref: <input name="data" value="'.(isset($_REQUEST['data'])?
htmlspecialchars($_REQUEST['data']):'Escriba Ref.de Producto').'" />
Definición: <select name="level">
<option value="L"'.(($errorCorrectionLevel=='L')?' selected':'').'>L
- Muy Baja</option>
<option value="M"'.(($errorCorrectionLevel=='M')?'
selected':'').'>Baja</option>
<option value="Q"'.(($errorCorrectionLevel=='Q')?'
selected':'').'>Media</option>
<option value="H"'.(($errorCorrectionLevel=='H')?'
selected':'').'>Alta - La Mejor</option>
</select>
Tamaño: <select name="size">';
for($i=1;$i<=10;$i++)
echo '<option value="'.$i.'"'.(($matrixPointSize==$i)?'
selected':'').'>'.$i.'</option>';
echo '</select>
**strong text** <input type="submit" value="GENERAR"></form><hr/>';
?>
<center>
<?php echo "<form method='get' action='php_action/downloadQr.php?
Descargar='".$_SESSION['filename'].">";?>
echo' <button class="btn btn-default button3" data-toggle="submit"
name="Descargar" data-target = "Descarga"><i class="glyphicon glyphicon-
download-alt"></i> Descargar Qr en su Computadora </button>
<button class="btn btn-default button3" data-toggle="submit"
id="GuardarQRlBtn" data-target="#GuardarQRlBtn"> <i class="glyphicon
glyphicon-tasks"></i> Guardar Qr en el Servidor </button></form>';
</center>
I have created in another directory a function that is called to download the file. This function is in "includes / functions.php." Since in the previous code this function is called by: "includes / functions.php";
function descargar($fichero){
$basefichero = basename($fichero);
$filename = 'php_action/temp'.$basefichero;
if (!empty($basefichero) && file_exists($basefichero)){
header('Content-Type:
application/vnd.openxmlformats-
officedocument.wordprocessingml.document');
header('Content-Disposition: attachment;
filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
}
}
?>
When I insert the product reference and press "Generate", the code works fine, because the QR creates a name followed by a random extension and saves it in my "temp" directory with png format. I have included a control point that forces the program to write the reference of the image on the screen that is saved inside the variable "$ filename2" in the code, this impression is generated well so the variable is passed correctly.
When once it is generated the image which is in the variable path "$filename" and in the name of the file as I said in "$ filename2" and I press the button "Download QR on your computer" the program searchs the file where are the instructions to call the download function that is the file (downloadQr.php):
<?php
session_start();
include "includes/functions.php";
if(isset($_GET['Descargar'])) {
echo $_SESSION['filename'];
descargar($_SESSION['filename']);
}
?>
As a control method I insert again in this file the instruction "echo $ _SESSION ['filename'];" so that I am impressed with the name of the file that is now saved in the global variable "$ _SESSION" already in the previous file "show_product2.php" I had created for the name of the image file "$ filename2". And indeed the name of the file is received in the variable, therefore, so far so good.
Finally the action begins to go through the instructions, prints again in my "echo" control the name of the image file, that means that it receives it, but here it stops, the blank screen with the name of the file is left but it does not download the file. So I think, by deduction, the error must be in the function "descargar()" but I do not know what it fails. I have described this function above. The variables with the file name of the image are passed correctly from one file to another and to the function.
I appreciate any help.
php image server downloadfile
php image server downloadfile
edited Nov 21 '18 at 11:08
asked Nov 19 '18 at 14:17
Óscar
52
52
At a quick glance, you have a typo:header("Content-Transfer-Encoding: binay");
. Should bebinary
, notbinay
.
– JonJ
Nov 19 '18 at 15:10
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.
– JonJ
Nov 19 '18 at 15:53
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19
add a comment |
At a quick glance, you have a typo:header("Content-Transfer-Encoding: binay");
. Should bebinary
, notbinay
.
– JonJ
Nov 19 '18 at 15:10
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.
– JonJ
Nov 19 '18 at 15:53
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19
At a quick glance, you have a typo:
header("Content-Transfer-Encoding: binay");
. Should be binary
, not binay
.– JonJ
Nov 19 '18 at 15:10
At a quick glance, you have a typo:
header("Content-Transfer-Encoding: binay");
. Should be binary
, not binay
.– JonJ
Nov 19 '18 at 15:10
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.– JonJ
Nov 19 '18 at 15:53
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.– JonJ
Nov 19 '18 at 15:53
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19
add a comment |
1 Answer
1
active
oldest
votes
To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type
):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
To output an image in the browser, try:
header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);
// Then:
$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);
To different methods of outputting the file size are given.
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try$filename = 'php_action/temp'.$basefichero;
.
– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53376563%2fdownload-file-from-server-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type
):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
To output an image in the browser, try:
header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);
// Then:
$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);
To different methods of outputting the file size are given.
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try$filename = 'php_action/temp'.$basefichero;
.
– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
add a comment |
To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type
):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
To output an image in the browser, try:
header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);
// Then:
$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);
To different methods of outputting the file size are given.
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try$filename = 'php_action/temp'.$basefichero;
.
– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
add a comment |
To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type
):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
To output an image in the browser, try:
header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);
// Then:
$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);
To different methods of outputting the file size are given.
To download a file, here are the headers I've found work. Note that this is for a Word doc (as that's a complex example for the Content-Type
):
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="' . $filename .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . sprintf("%u", filesize($filename)));
// Then:
flush(); // just in case
readfile($filename);
To output an image in the browser, try:
header("HTTP/1.0 200 OK");
header("Content-Type: image/png"); // Or /jpg, /gif, etc
header("Content-Length: " . (string) filesize($filename));
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: inline");
header("Location: /" . $filename);
// Then:
$fileHandle = fopen($filename, 'rb');
fpassthru($fileHandle);
To different methods of outputting the file size are given.
answered Nov 19 '18 at 15:49
JonJ
6597
6597
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try$filename = 'php_action/temp'.$basefichero;
.
– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
add a comment |
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try$filename = 'php_action/temp'.$basefichero;
.
– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
Hi JonJ. your example, as it is, does not work., Is "$filename" = "$fiechero" in your exemple? and where do you define the path of file?. this is name file (base) $basefichero = basename($fichero); and this is the the "path"+basename. $filePath = 'php_action/temp'.$basefichero;
– Óscar
Nov 19 '18 at 16:18
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try
$filename = 'php_action/temp'.$basefichero;
.– JonJ
Nov 19 '18 at 16:21
You'll need to substitute your filenames and paths as necessary, I wanted to use English for the variable names. Try
$filename = 'php_action/temp'.$basefichero;
.– JonJ
Nov 19 '18 at 16:21
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
I have edited my question and replaced with your code for function "descargar()" which seems more logic than my previous one. But it still not working,
– Óscar
Nov 19 '18 at 16:41
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53376563%2fdownload-file-from-server-php%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
At a quick glance, you have a typo:
header("Content-Transfer-Encoding: binay");
. Should bebinary
, notbinay
.– JonJ
Nov 19 '18 at 15:10
HiJonJ, I have re-edited to write it correctly, but this is not the error because I run it again and re.mains same situation. I have tried so many times different options, that I wrote this parameter wrong by mistake.
– Óscar
Nov 19 '18 at 15:29
Content-Dsiposition
is also spelt wrongly. Didn't spot that one earlier.– JonJ
Nov 19 '18 at 15:53
re-edited now correctly.
– Óscar
Nov 19 '18 at 16:19