<?php
session_start();

function checkPass($user, $pass)
{
  if(!$fd = fopen("/secure/passwords.txt", "r")){
   return false;
  }
  $result = false;
  while (!feof ($fd)){
    $lineUser = rtrim(fgets($fd));
    $linePass = rtrim(fgets($fd));

    if($lineUser != $user) continue;

    if($linePass == $pass){
      $result = true;
      break;
    }
  }
  fclose($fd);
  return $result;
}

if(isSet($_SESSION['zalogowany'])){
  header("Location: glowna.php");
  exit();
}
else if(isSet($_POST['user']) && isSet($_POST['haslo'])){
  if(checkPass($_POST['user'], $_POST['haslo'])){
    $_SESSION['zalogowany'] = $_POST['user'];
    header("Location: glowna.php");
    exit();
  }
  else{
    $komunikat = "Niepoprawne dane logowania.";
  }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">
<title>Logowanie użytkowników</title>
</head>
<body>
<div>
<form action = "http://localhost/index.php"
      method = "post"
>
<?php
  if(isSet($komunikat)):
?>
<div><?php echo $komunikat; ?></div>
<?php
  endif;
?>
<table border="0"><tr>
<td>Użytkownik:</td>
<td>
  <input type="text" name="user" />
</td>
</tr><tr>
<td>Hasło:</td>
<td>
  <input type="password" name="haslo" />
</td>
</tr><tr>
<td colspan="2" align="center">
  <input type="submit" value="Wejdź" />
</td>
</tr></table>
</form>
</div>
</body>
</html>
