<?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'] = 'user1';
      header("Location: glowna.php");
      exit();
    }
    else{
      $_SESSION['komunikat'] = "Niepoprawne dane logowania.";
      header("Location: index.php");
      exit();
    }
  }
  if(isset($_SESSION['komunikat'])){
    $komunikat = $_SESSION['komunikat'];
    unset($_SESSION['komunikat']);
  }
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Moja strona WWW</title>
  </head>
  <body>
    <div>
      <form action = "http://localhost/index.php"
            method = "post">
      <?php 
        if(isset($komunikat)):
      ?>
      <div><?=$komunikat?></div>
      <?php
        endif; 
      ?>
        <table>
          <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" style="text-align:center">
              <input type="submit" value="Wejdź">
            </td>
          </tr>
        </table>
      </form>
    </div>
  </body>
</html>
