title: Download pdf and image files with php instead of displaying them on your desktop
body: <p>I have created a script that works only with some files and I would like to improve it.
  In practice, this PHP script saves the uploaded file on the server disk and the file name in a mySQL database.</p>
  
  <p>When I press on the download button, the script saves the name of the file into <code>$filename</code>so when I use the code shown below, I'm able to download the file:</p>
  
  <pre><code>header ("Location: http://". $ _SERVER ['SERVER_NAME']. "/ FILE_DOWNLOAD /". $ filename);
  </code></pre>
  
  <p>The problem is that if the file is an image or a PDF and I try to open it from my browser, it opens the file instead of downloading it to my desktop.</p>
  
  <p>I've looked for a solution on many forums but have had no success.</p>
  
  <p>Here's an alternative that is very close to what I'm looking for:</p>
  
  <pre><code>$files_folder = $_SERVER['DOCUMENT_ROOT']. "/file_download/";
      if (is_file($files_folder.$filename))
      {
          $spliturl = explode (".", $filename);
          $file_extension = $spliturl[sizeof($spliturl)-1];
          switch(strtolower($file_extension)) {
                case "pdf": $ctype="application/pdf"; break;
                case "png": $ctype="image/png"; break;
                case "jpeg": $ctype="image/jpeg"; break;
                case "jpg": $ctype="image/jpeg"; break;
                default: $ctype = false; break;
          }
          if($ctype) {
              header("Content-Type: $ctype");
              header("Content-Disposition: $disposition; filename=".$filename);
              header("Content-Description: Download ");
              echo file_get_contents($files_folder.$filename);
          }echo "Error extension!";
      }else echo "The file does not exist!";
  </code></pre>