define FILE_NAME htpasswd function getHash string salt iterationCount

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
define('FILE_NAME', '.htpasswd');
function getHash($string, $salt, $iterationCount){
for ($i = 0; $i < $iterationCount; $i++) $string = sha1($string . $salt);
return $string;
}
function saveHash($user, $hash, $salt, $iteration){
$str = "$user:$hash:$salt:$iteration\n";
if(file_put_contents(FILE_NAME, $str, FILE_APPEND)) return true;
else return false;
}
function userExists($login){
if(!is_file(FILE_NAME)) return false;
$users = file(FILE_NAME);
foreach($users as $user){
if(strpos($user, $login) !== false) return $user;
}
return false;
}
session_start();
header("HTTP/1.0 401 Unauthorized");
require_once "secure.inc.php";
if($_SERVER['REQUEST_METHOD']=='POST'){
$user = trim(strip_tags($_POST["user"]));
$pw = trim(strip_tags($_POST["pw"]));
$ref = trim(strip_tags($_GET["ref"]));
if(!$ref) $ref = '/eshop/admin/';
if($user and $pw){
if($result = userExists($user)){
list($login, $password, $salt, $iteration) = explode(':', $result);
if (getHash($pw, $salt, $iteration) == $password){
$_SESSION['admin'] = true;
header("Location: $ref");
exit;
}else{
$title = 'Неправильный пароль!';
}
}else{
$title = 'Неправильное имя пользователя!';
}
}else{
$title = 'Заполните все поля формы!';
}
}
session_start();
if(!isset($_SESSION['admin'])){
header('Location: /eshop/admin/secure/login.php?ref='.$_SERVER['REQUEST_URI']);
exit;
}
function logOut(){
session_destroy();
header('Location: secure/login.php');
exit;
}
if(isset($_GET['logout'])){
logOut();
}