title: Download file from Server PHP
body: <p>I would like to download a server image using PHP. Specifications:</p>
  <ul>
  <li>I do not want to use javascript and I do not want to pass the name by database and then retrieve it.</li>
  <li>The image I want to download is a QR code that I generated and saved in a &quot;php_action / temp&quot; directory. Within this directory there are several images, so I am trying to download only the file I have generated.</li>
  <li>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.</li>
  </ul>
  <p>I am not able to get download the file.</p>
  <pre><code>    //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 &quot;phpqrcode/qrlib.php&quot;;
  
      //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']) &amp;&amp; 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 &quot;Referencia&quot; 
      y haga clic en &quot;Generar&quot;, no puede dejar en blanco los datos! &lt;a 
      href=&quot;?&quot;&gt;Regresar&lt;/a&gt;');
       $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 &quot;Generar&quot; no 
        se visualizará la imagen definitiva&quot;&lt;hr/&gt;';
        QRcode::png('PHP QR Code :)', $filename, $errorCorrectionLevel, 
         $matrixPointSize, 2);
  
          }
  
             //display generated file
           // echo '&lt;img src=&quot;'.$PNG_WEB_DIR.basename($filename).'&quot; /&gt;&lt;hr/&gt;';
           echo '&lt;img 
    
         src=&quot;'.'php_action'.DIRECTORY_SEPARATOR.$PNG_WEB_DIR
       .basename($filename).'&quot; /&gt;&lt;hr/&gt;';
  
        //.'php_action'.DIRECTORY_SEPARATOR.
  
        //config form
      echo '&lt;form action=&quot;show_product2.php&quot; method=&quot;post&quot;&gt;
      Ref:&amp;nbsp;&lt;input name=&quot;data&quot; value=&quot;'.(isset($_REQUEST['data'])? 
      htmlspecialchars($_REQUEST['data']):'Escriba  Ref.de Producto').'&quot; /&gt;&amp;nbsp;
           Definición:&amp;nbsp;&lt;select name=&quot;level&quot;&gt;
          &lt;option value=&quot;L&quot;'.(($errorCorrectionLevel=='L')?' selected':'').'&gt;L 
          - Muy Baja&lt;/option&gt;
          &lt;option value=&quot;M&quot;'.(($errorCorrectionLevel=='M')?' 
          selected':'').'&gt;Baja&lt;/option&gt;
          &lt;option value=&quot;Q&quot;'.(($errorCorrectionLevel=='Q')?' 
           selected':'').'&gt;Media&lt;/option&gt;
          &lt;option value=&quot;H&quot;'.(($errorCorrectionLevel=='H')?' 
          selected':'').'&gt;Alta - La Mejor&lt;/option&gt;
           &lt;/select&gt;&amp;nbsp;
           Tamaño:&amp;nbsp;&lt;select name=&quot;size&quot;&gt;';
  
             for($i=1;$i&lt;=10;$i++)
            echo '&lt;option value=&quot;'.$i.'&quot;'.(($matrixPointSize==$i)?' 
             selected':'').'&gt;'.$i.'&lt;/option&gt;';
  
           echo '&lt;/select&gt;&amp;nbsp;
        **strong text** &lt;input type=&quot;submit&quot; value=&quot;GENERAR&quot;&gt;&lt;/form&gt;&lt;hr/&gt;';
  
  
       ?&gt;
       &lt;center&gt;
  
        &lt;?php echo &quot;&lt;form method='get' action='php_action/downloadQr.php? 
       Descargar='&quot;.$_SESSION['filename'].&quot;&gt;&quot;;?&gt;
  
        echo' &lt;button class=&quot;btn btn-default button3&quot; data-toggle=&quot;submit&quot;
        name=&quot;Descargar&quot; data-target = &quot;Descarga&quot;&gt;&lt;i class=&quot;glyphicon glyphicon-
       download-alt&quot;&gt;&lt;/i&gt; Descargar Qr en su Computadora &lt;/button&gt;
  
      &amp;nbsp;&lt;button class=&quot;btn btn-default button3&quot; data-toggle=&quot;submit&quot;
      id=&quot;GuardarQRlBtn&quot; data-target=&quot;#GuardarQRlBtn&quot;&gt; &lt;i class=&quot;glyphicon
      glyphicon-tasks&quot;&gt;&lt;/i&gt; Guardar Qr en el Servidor &lt;/button&gt;&lt;/form&gt;';
  
  
       &lt;/center&gt;
  </code></pre>
  <p>I have created in another directory a function that is called to download the file. This function is in &quot;includes / functions.php.&quot; Since in the previous code this function is called by: &quot;includes / functions.php&quot;;</p>
  <pre><code>      function descargar($fichero){
        $basefichero = basename($fichero);
  
        $filename = 'php_action/temp'.$basefichero;
  
  
           if (!empty($basefichero) &amp;&amp; file_exists($basefichero)){
           header('Content-Type: 
           application/vnd.openxmlformats- 
           officedocument.wordprocessingml.document');
           header('Content-Disposition: attachment; 
           filename=&quot;' . $filename .'&quot;');
           header('Expires: 0');
           header('Cache-Control: must-revalidate');
           header('Pragma: public');
           header('Content-Length: ' . sprintf(&quot;%u&quot;, filesize($filename)));
  
  
          // Then:
         flush(); // just in case
         readfile($filename);
         }
          }
           ?&gt;
  </code></pre>
  <p>When I insert the product reference and press &quot;Generate&quot;, the code works fine, because the QR creates a name followed by a random extension and saves it in my &quot;temp&quot; 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 &quot;$ filename2&quot; in the code, this impression is generated well so the variable is passed correctly.</p>
  <p>When once it is generated the image which is in the variable path &quot;$filename&quot; and in the name of the file as I said in &quot;$ filename2&quot; and I press the button &quot;Download QR on your computer&quot; the program searchs the file where are the instructions to call the download function that is the file <strong>(downloadQr.php):</strong></p>
  <pre><code>      &lt;?php
        session_start();
        include &quot;includes/functions.php&quot;;
  
        if(isset($_GET['Descargar'])) {
  
        echo $_SESSION['filename'];
  
         descargar($_SESSION['filename']);
  
  
          }
  
         ?&gt;
  </code></pre>
  <p>As a control method I insert again in this file the instruction &quot;echo $ _SESSION ['filename'];&quot; so that I am impressed with the name of the file that is now saved in the global variable &quot;$ _SESSION&quot; already in the previous file &quot;show_product2.php&quot; I had created for the name of the image file &quot;$ filename2&quot;. And indeed the name of the file is received in the variable, therefore, so far so good.</p>
  <p>Finally the action begins to go through the instructions, prints again in my &quot;echo&quot; 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 <code>descargar()</code> 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.</p>