<?php
$filesPath = "./downloads/";

function checkFileName($name, $path)
{
  $fd = opendir($path);
  if(!$fd) return false;
  while (($file = readdir($fd)) !== false){
    if(is_dir($path.$file)) continue;
    if($file == $name) return true;
  }
  closedir($fd);
  return false;
}

function send($fileName, $filePath)
{
  if(!file_exists($filePath.$fileName)){
    return false;
  }
  $fd = fopen($filePath.$fileName,"r");
  $size = filesize($filePath.$fileName);
  $contents = fread($fd, filesize($filePath.$fileName));
    if($contents === false){
    return false;
  }

  fclose($fd);

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

  echo $contents;
  return true;
}

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

