<?

include 'connect.php';
if(isset($_GET['out'])){
unset ($_SESSION['login']);
unset ($_SESSION['pass']);
setcookie('clogin', '');
setcookie('cpass', '');
header('location: index.php');
exit;
}

if($u['id']) { header('location: index.php'); exit; }

if ($_SESSION['err'] == 1){
$kod = num($_GET['kod']);
   if ($_SESSION['r'] == $kod ){
   $_SESSION['err'] = 0;
   }
}

if($_SESSION['err'] == 0) {
$id = isset($_GET['id']) ? num($_GET['id']) : NULL;
$login = isset($_GET['login']) ? check($_GET['login']) : NULL;
$pass = isset($_GET['p']) ? check($_GET['p']) : NULL;

if ($pass && ($login || $id)) {
$sql = $id ? "`id` = '$id'" : "`login` = '$login'";
$req = mysql_query("SELECT * FROM `users` WHERE $sql LIMIT 1");
   if (mysql_num_rows($req)) {
        $u = mysql_fetch_assoc($req);
		if (md5(md5($pass)) == $u['pass']) {
		   // Установка данных COOKIE
           if ($_GET['save'] == 1) {
            $clogin = $u['login'];
            $cpass = md5($pass);
            setcookie("clogin", $clogin, time() + 3600 * 24 * 365);
            setcookie("cpass", $cpass, time() + 3600 * 24 * 365);
 
}
		// Установка данных сессии
		$_SESSION['login'] = $u['login'];
		$_SESSION['pass'] = md5(md5($pass));
		header('Location: start.php?s=ok');           
		exit;
		} else {
		$_SESSION['err'] = 1;
        header('Location: aut.php');
		exit;
		}
   } else {
   $_SESSION['err'] = 1;
   header('Location: aut.php');
   exit;
   }
}
}
include 'head.php';
echo '<div class="title"><img src = "img/aut.gif"> Вход</div>';
echo '<div class="block_action">';
if ($_SESSION['err'] == 1){
echo '<div class = "action">Не правильно введен логин или пароль!</div><hr>';
}
echo '
<form action="aut.php" method=get>
Ваш Логин:<br/>
<input type=text name=login maxlength=25 size="15"><br/>
Ваш пароль:<br/>
<input type=password name=p maxlength=25 size="15"><br/>';
echo '<input name="save" type="checkbox" value="1"/>&nbsp;Запомнить<br/>';
if ($_SESSION['err'] == 1){
$_SESSION['r']=rand(1111,9999);
echo 'Введите код <font color = "red"><b>'.$_SESSION['r'].'</b></font>: <br/>
<input type=text name=kod maxlength=4><br/>';
} else {}
echo '
<input type=submit class=btn value="Войти" size="15" class="submit white"/><br/>
</form><hr>';
echo '<img src = "img/reg.gif"> <a href="reg.php">Регистрация</a>';
echo '</div>';
include 'foot.php';
?>
