Hello! The question is as follows:

Suppose there is an html page on which there is one single field for entering a password. If you successfully enter the password, the person flips to the desired page.

The password is not stored in the database, but in any file, or in the code of the same page.

How to organize access by password, so that if you enter the password incorrectly under the input, a div will immediately appear with the specified text like "You are mistaken."

  • 2
    Does [Basic access] [1] HTTP authorization not suit you? [1]: wiki.apache.org/httpd/PasswordBasicAuth - Johny
  • Keep the password in the page code - moveton and gross violation of security rules. To store the password, use a hash function, for example md5 - Johny
  • @Johny, no matter how many times you have hashed, rehashed the key string, there will be no more sense from this. Anyway, this line will be part of the same AJAX request, which will be true for the server, and, therefore, the attacker (or student) will be able to pull it out without any problems. - AseN

3 answers 3

If it is very simple:

<form id="auth"> <input type="password" id="pass" autofocus /><br/> <div id="err" style="display: none; color: red;">Кривой пароль</div> <button>Войти</button> </form> <script> auth.addEventListener('submit', function (evt){ evt.preventDefault(); // отменяем действие по умолчанию var xhr = new XMLHttpRequest; xhr.open('POST', '/ctrl.php', false); // отправляем синхронный запрос на сервер xhr.send('pass='+pass.value); if( xhr.responseText == 'invalid' ){ // проверяем ответ err.style.display = ''; // выводим ошибку } else { location.href = xhr.responseText; // переходим на страницу } }); </script> 


ctrl.php:

 <?php $pass = isset($_POST['pass']) ? trim($_POST['pass']) : ''; if($pass == $secret){ echo "/secret-page.html"; } else { echo "invalid"; } ?> 
  • I could say that the example works fine, but if you do not understand it, then fine. - RubaXa

The best way to change the extension of your file from .html to .php So you will at least make the code that is presented from below compiled by the server. This means that it will not be accessible by another user. They will get only the final result.

Instruction:

  1. Just add this script at the top of your page.
  2. Replace login and pass with the values ​​you need.
  3. Use on health :)

PS This is a weak defense, for large projects it is worth finding another solution.

 <?php $valid_passwords = array ("login" => "pass"); $valid_users = array_keys($valid_passwords); $user = $_SERVER['PHP_AUTH_USER']; $pass = $_SERVER['PHP_AUTH_PW']; $validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]); if (!$validated) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); die ("Not authorized"); } // Тут мы пишем те echo "<p>Здравствуйте $user.</p>"; echo "<p> Поздравляем, Вы успешно прошли авторизацию.</p>"; ?> 

    A million ways. It is not safe to store the password in the code of the page itself, because it will be transferred to the client and, if desired, it will be decoded two times. I suggest you implement through AJAX, the meaning is as follows:

    • when you press a button, say, "input", a request is sent to the server
    • if server is not available or response from server "error" show div
    • if the response from the server is "accept" then form.submit ();

    The code may be:

     $('a').click(function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: 'login-ajax.php', success: function(response){ if (response == 'accept') { $('#do').submit(); } else { $('div').fadeIn(400); } }, error: function(response){ $('div').fadeIn(400); } }); }); 

    Fiddle: http://jsfiddle.net/CxrVg/

    Well, in PHP, actually something like this:

     <?php $pass = ''; if (isset($_POST['pass']) { $pass = $_POST['pass']; } /.. обезопасить входящие данные ../ /.. сверить с базой ../ if ( %ПАРОЛЬ СОВПАЛ% ) { die('accept'); } else { die('error'); } ?> 
    • HERE Zaminusovali: ( - ferrari
    • one
      Rave. Regular means (HTML | JS | AJAX) to protect nothing happens. Unless "schoolchildren" weed out. Well, the one who needs it, he will be able to fake a request without any problems, having studied JS in the browser and get access .. - AseN
    • Thank. The essence is clear. What about the php file? I meant that the password is in a variable on the page. Well, then security is not required, as people who will go to the page will not even know the words PHP and HTML. - Frontender
    • But who offers you to encrypt the password in js? check without rebooting with a helper and submit a form and check there. - ferrari
    • one
      if it is used as a cross-check (do not rely on the data sent and recheck), then you can do md5sum () with random salt, i.e. pass to user md5 (password.rand ()); on his side of input, we consider the danger in this case - brutfors (you can try to artificially increase the number of hits of brutfors, but it still reduces the security). - zb '