title: Secure file download in PHP, deny user without permission
body: <p>I'm making a website where you can buy files for virtual points, and then download them. I don't want to let users download the files without buying it, so I have to hide them. I put all the files in a folder without permission for anyone except host, the problem is when someone buys a file and wants to download it.</p>
  
  <p>I decided to make a file getter, that will check permissions of user and then print out the file contents. My code so far:</p>
  
  <pre><code>&lt;?php
      require_once('content/requirements.php'); //mysql connections
      secure(1); //disconnect unlogged users
  
      if (!isset($_GET['id'])) //if no file id provided
          die();
  
      $fid=mysql_real_escape_string($_GET['id']); //file id
  
      $query="SELECT * FROM files WHERE user_id = "$_SESSION['user_id']." AND file_id = ".$id;
  
      $q=mysql_query($query);
  
      if (mysql_num_rows($q)!=1) //if no permission for file or multipe files returned
          die();
  
      $file=mysql_fetch_array($q); //file id
      $sub=mysql_fetch_array(mysql_query("SELECT * FROM sub WHERE id = ".$file['file_id'])); //payment id
  ?&gt;
  </code></pre>
  
  <p>Now when Im sure the user is authorized to do this, phpScript should write the file contents and send appropiate header to let user download it.</p>
  
  <p>How to read file byte-by-byte and print it and what should i write in header(), to make the file downloadable (so you don't have to copypaste its contents).</p>
  
  <p>Maybe this is not the best way to do this, but it was the best thing I thought of in a while.</p>
  
  <p>Thanx for any help.</p>