<?php
$list_file = "downloads.txt";

function send($id, $list_file)
{
  if(!($fd = fopen($list_file, "r"))){
    return false;
  }

  $found = false;

  while (!feof ($fd)){
    $line = trim(fgets($fd));
    $arr = explode(";", $line);
    if(count($arr) == 4){
      if($id === $arr[0]){
        $found = true;
        $path = $arr[2];
        $name = $arr[1];
        break;
      }
    }
  }

  if((!$found) || (!file_exists($path.$name))){
    return false;
  }

  if(!($fd = fopen($path.$name, "r"))){
    return false;
  }
  $size = filesize($path.$name);
  $contents = fread($fd, $size);
  if($contents === false){
    return false;
  }

  fclose($fd);

  header("Content-Type: application/octet-stream");
  header("Content-Length: $size;");
  header("Content-Disposition: attachment; filename=$name");

  echo $contents;
  return true;
}

if(isSet($_GET['fileid'])){
  if(!send($_GET['fileid'], $list_file)){
    include "nofile.html";
  }
}
else{
  include "download_list.php";
}
?>
