<?php 
include_once 'common.inc';
include_once 'db.inc';

session_start();

$uid = isset($_POST['uid']) ? $_POST['uid'] : $_SESSION['uid'];
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : $_SESSION['pwd'];

if(!isset($uid))
  header("Location: login.html");

$_SESSION['uid'] = $uid;
$_SESSION['pwd'] = $pwd;

$db = dbconnect($connection_string);  
$query = "SELECT * FROM users 
          WHERE userid = '$uid' 
            AND password = '$pwd'";
$result = pg_query($db,$query);
if (!$result)
  error('A database error occurred while checking your login details.');

if (pg_num_rows($result) == 0) {
  unset($_SESSION['uid']);
  unset($_SESSION['pwd']);
  ?>
  <html>
  <head>
    <title> Access Denied </title>
  </head>
  <body>
  <h1> Access Denied </h1>
  <p>Your user ID or password is incorrect, or you are not a
     registered user on this site. To try logging in again, click
     <a href="login.html">here</a>. To register for instant
     access, click <a href="signup.php">here</a>.</p>
  </body>
  </html>
  <?php
  exit;
}

$_SESSION['username'] = pg_result($result, 0, 'fullname');
?>