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

$html_header = <<<ID1
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">
<title>Wysyłanie plików</title>
</head>
<body>
<div>
ID1;

$html_footer = <<<ID2
</div>
</body>
</html>
ID2;

$html_nofile = <<<ID3
<p style="text-align:center">Nie ma takiego pliku na serwerze!</p>
<p style="text-align:center"> 
  <a href="http://localhost/download.php">Powrót do strony pobrań</a>
</p>
ID3;

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;
}

function printList($path, $ext)
{
  $fd = opendir($path);
  if(!$fd) return false;
  $ext_count = strlen($ext);
  echo "<ul>";
  while (($file = readdir($fd)) !== false){
    if(is_dir($path.$file)) continue;
    if(substr($file, strlen($file) - $ext_count, $ext_count + 1) != $ext) continue;
    echo("<li><a href=\"http://localhost/download.php?name=");
    echo("$file\">$file</a></li>");
  }
  echo "</ul>";
  closedir($fd);
}

if(isSet($_GET['name'])){
  if(!checkFileName($_GET['name'], $filesPath)){
    echo $html_header;
    echo $html_nofile;
    echo $html_footer;
  }
  else{
    if(!send($_GET['name'], $filesPath)){
      echo $html_header;
      echo $html_nofile;
      echo $html_footer;
    }
  }
}
else{
  echo $html_header;
  printList($filesPath, $ext);
  echo $html_footer;
}

?>
