S
S
Sanders Rocket2020-04-27 23:37:58
PHP
Sanders Rocket, 2020-04-27 23:37:58

How to do authentication in php?

How to make a website with php authentication?
I saw an article - https://blog.foolsoft.ru/php-sozdanie-formy-vxoda-... (not advertising)
Code from it:

<?php
header('Content-type: text/html;charset=utf-8');
session_start();

define('SALT', 'As913yr-1u3 -ru1 mr=1r=1 m=0r813'); //рандомная строка

function getPassword($password)
{   //функция получения зашифрованного пароля
    return md5($password.SALT);
}

$users = array( //мы не используем БД, поэтому пользователей храним в массиве
    //пароль = getPassword('password1')
    'login1' => array('password' => '4b0e292e27ee63a490a5214e225999b0', 'name' => 'Имя пользователя'),
    //пароль = getPassword('password2')
    'login2' => array('password' => 'cf4578943c7db66051404d5c2b535c7f', 'name' => 'Имя пользователя 2'),
);

if(!isset($_SESSION['user']) && isset($_COOKIE['login']) && isset($_COOKIE['password'])
    && isset($users[$_COOKIE['login']]) && getPassword($users[$_COOKIE['login']]['password']) == $_COOKIE['password']) {
    //если нет сессии пользователя, но есть куки с пользовательским логином и паролем
    //проходим аторизацию
    $_SESSION['user'] = $_COOKIE['login'];
}

define('AUTH', isset($_SESSION['user']) && isset($users[$_SESSION['user']])); //флаг аторизованы мы или нет
$user = AUTH ? $users[$_SESSION['user']] : null;


$message = '';
if(!empty($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

I don't understand what the username and password is here, or how to add my own user with a password.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
John Didact, 2020-04-27
@sandersik

login.php

<?php
include __DIR__.'/config.php';

if(!AUTH) {
  //мы еще не авторизованы
  if(!empty($_POST['login']) && !empty($_POST['password']) && isset($users[$_POST['login']])) {
      //передали данные для входа и логин существует
      if($users[$_POST['login']]['password'] == getPassword($_POST['password'])) {
          //пароль совпадает
          $_SESSION['user'] = $_POST['login'];

          if(isset($_POST['remember'])) {
            //стоит галка "запомнить меня"
            setcookie('login', $_POST['login'], time() + 3600 * 24 * 365, '/');
            setcookie('password', getPassword($users[$_POST['login']]['password']), time() + 3600 * 24 * 365, '/');
          }

      }
  }
  if(!isset($_SESSION['user']) || $_SESSION['user'] != $_POST['login']) {
    //авторизация не прошла, сохраним ошибку
    $_SESSION['message'] = 'Неверный логин или пароль';
  }
} else {
    if(isset($_GET['logout'])) { //выход из системы
        unset($_SESSION['user']);
        setcookie('login', '', time() - 3600 * 24 * 365, '/');
        setcookie('password', '', time() - 3600 * 24 * 365, '/');
    }
}

header('Location: index.php'); //переходим на главную страницу

The "method" that is described in the article, I think, is extremely stupid to use ...
If you have such questions, then you do not need Q&A resources, but not training ones. I can advise the book of Koterov and Kostarev, read it from beginning to end and such a question will not arise. Also, in addition, I recommend watching the video tutorials "PHP Specialist" for all levels. The material is very accessible and interesting, in my opinion. Of course, I’m not special in this, as I’m a lazy person (therefore, I didn’t read it to the end and didn’t watch the video tutorials), but I understood the basics. I advise you not to stop, but to take all the courses.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question