title: php header force download returning unusable mp3
body: <p>i have been working on this for 5 days now... tearing down code and rebuilding it. I am trying to force a mp3 file download. When it has no special characters ( ampersand, quote, apostrophe), the download works fine. I loose all the metadata in the file, but the file downloads and is playable.<br>This is my download script for file download:</p>
  
  <pre><code>header('Content-type: audio/mpeg');
  header('Content-Disposition: attachment; filename="TraxXMP3_'.$file.'"');
  readfile($file);
     exit;
  </code></pre>
  
  <p>My humble guess is the data from the database is not being returned/sanitized correctly. But unsure how.i have tried this:</p>
  
  <pre><code>$var =  str_replace("'","%27", $var);
  $var =  str_replace("%27", "'" , $var);
  $var = htmlentities($var,ENT_QUOTES,'UTF-8');
  $var = html_entity_decode($var,ENT_QUOTES,'UTF-8');
  </code></pre>
  
  <p>All of these will allow input and retrieval from database. it will display in the database as the modified string, and back to the html page. All other non-escaped files will download without issue. Only when there is escaped code does it fail.<br>Output files vary with the string escaping. Results like... file is transfered, but no content. Or, file is returned with unusable string (part of the filename without the mp3 extension).
  <br>This is the whole file download header file:</p>
  
  <pre><code>if(isset($_GET['file'])){
  $file = $_GET['file'];
  $sql = "SELECT * FROM main_lib WHERE file_name='.$file.' LIMIT 1";
  $query = mysqli_query($db_conn, $sql) or die (mysqli_error()); 
  while ($row = mysqli_fetch_array($query)) { 
  $count_dl            = $row['count_dl'];
  }
  //mysqli_free_result($query);
  mysqli_query($db_conn, "UPDATE main_lib SET count_dl='$count_dl'+1 WHERE file_name='$file'");
  /**
  * 
  *   EMAIL SCRIPT HERE
  * 
  */
  mysqli_free_result($query);
  $file =     cleanVarsDn($file);
      header('Content-type: audio/mpeg');
      header('Content-Disposition: attachment; filename="TraxXMP3_'.$file.'"');
      readfile('../data/lib/'.$file);
      exit;
  }
  </code></pre>
  
  <p>This is my string escape file:</p>
  
  <pre><code>function cleanVarsUp($var){
      //$var = htmlentities($var,ENT_QUOTES,'UTF-8');
      //$var =  str_ireplace("\"",  "&amp;quot;", $var);
      $var =  str_replace("'","%27", $var);
      return $var;
  }
  function cleanVarsDn($var){
      //$var =  str_ireplace("&amp;apos;",  "'", $var);
      //$var = html_entity_decode($var,ENT_QUOTES,'UTF-8');
      $var =  str_replace("%27", "'" , $var);
      return $var;
  }
  </code></pre>
  
  <p>Commented out lines are what i have tried. Note... this script DOES work. Just not with unsanitized Data.
  I am totally lost here. NOT a rookie programmer, but not a pro either.</p>