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.