<?php
session_start();

function checkPass($user, $pass)
{
  if(!$fd = fopen("/secure/passwords.txt", "r")){
   return false;
  }
  $result = false;
  while (!feof ($fd)){
    $line = trim(fgets($fd));
    $arr = explode(":", $line);
    if(count($arr) < 2) continue;

    if($arr[0] != $user) continue;

    if($arr[1] == $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 XHTML 1.0 Strict//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<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>
