0

A beginner coder here. I am trying to build a very basic php login system with html and php. But I need some help here:

<html>
<head></head>
<body>

   <form method="POST">
        User <input type="text" name="user"></input><br/>
        Pass <input type="password" name="pass"></input><br/>
        <input type="submit" name="submit" value="Go"></input>
        </form>  

And:

    <?php

$user = $_POST['user'];
$pass = $_POST['pass'];

$passw= md5($pass);


if ($user == "admin" && $passw == "8b1a9953c4611296a827abf8c47804d7") {
    echo "Login completed";
} else {
    echo "Try Again Please";
}
?>

</body>
       </html>

But something isn't quite working here, when I type a username and a password, and click the button, the screen just refreshes like nothing happened.

What am I missing?!

Coder48
  • 49
  • 5
  • Does `` do anything? Or any other PHP code? What shows up in the browser if you View > Source? – Quentin Jan 06 '20 at 16:03
  • This seems to work fine to me (admittedly with a couple of warning notices, but you can deal with those later). Are you definitely typing *Hello* for the password? md5 hashes will be different based on the input's case, so make sure you've got the capital H – iainn Jan 06 '20 at 16:04
  • @iainn — If they were getting the password wrong then it would echo "Try Again Please" which it doesn't seem to be. – Quentin Jan 06 '20 at 16:05
  • It shouldn't be the cause of any of the problems you are asking about but you should [use a validator](https://validator.nu/) as you have invalid HTML and also [learn to love labels](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/) – Quentin Jan 06 '20 at 16:05
  • @Quentin Assuming this is all one file it echoes that on the first page load as well, since there's no checking that the form has been submitted. Which would look the same as the page refreshing. – iainn Jan 06 '20 at 16:06
  • @iainn — Possibly. I'd expect the OP to mention the error though … and the undefined index error. I'm betting on this being a duplicate of https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-instead-code-shows-on-the-page – Quentin Jan 06 '20 at 16:07
  • 1
    Are you sure you've actually run your script on a web server with PHP installed? For example, if you just create an HTML document on your computer and open it in your browser, the PHP code in your file won't actually do anything. – BadHorsie Jan 06 '20 at 16:14
  • `md5()` is obsolete for hashing passwords and should *not be used*. PHP provides [password_hash()](//php.net/manual/en/function.password-hash.php) and [password_verify()](//php.net/manual/en/function.password-verify.php), please use them. And here are some [good ideas about passwords](//www.owasp.org/index.php/Password_Storage_Cheat_Sheet). If you are using a PHP version prior to 5.5 [there is a compatibility pack available here](https://github.com/ircmaxell/password_compat) (and you should consider upgrading to a supported version of PHP). – John Conde Jan 06 '20 at 16:16

2 Answers2

0

Usually on login pages there is a input page where you enter your credentials, that is submitting the variables to another site. Then you must have something like this , in witch you include the credential form.

<form method="post" action="https://example.com/landing_site.php">
<?php
    include "credencial_html.php";
?>
</form>

credencial_html.php looks like this (simple html code):

 User <input type="text" name="user"><br/>
 Pass <input type="password" name="pass"><br/>
 <input type="submit" name="submit" value="Go">

And now you make that "if" part. ... If the credentials are right you post OK, if not you bring the input boxes again, and say try again ...

<?php

define('rightpass', '8b1a9953c4611296a827abf8c47804d7');
define('rightuser', '21232f297a57a5a743894a0e4a801fc3'); // md5('admin') ;-)    

$user = md5($_POST['user']);
$pass = md5($_POST['pass']);


if ($user == rightuser && $pass == rightpass) {
    echo "Login completed";
} else {
    echo "Try Again Please";
    include "credencial_html.php";
}

?>
-1

By basic, I see you mean illogical, and insecure. Relax, I'm just giving you a hard time. You should encrypt your passwords (maybe SHA2) and store them in a database. I'm guessing you want to use MySQL.

Step #1

Create two databases. One for your encryption keys and one for your usernames and passwords. You should be able to do that through some kind of control panel (cPanel).

Step #2

Create a secure restricted folder (Permission 100) and put https.php and connect.php files (both Permission 400) in the restricted folder.

<?php /* restricted/https.php */
if(!isset($_SERVER['HTTPS'])){
  header("LOCATION:https://{$_SERVER['SERVER_NAME']}{$_SERVER['PHP_SELF']}"); die;
}
?>

and

<?php /* restricted/connect.php */
$kb = new mysqli('keyHost', 'keyDatabaseUsername', 'keyDatabasePassword', 'keyDatabaseName');
$db = new mysqli('userHost', 'userDatabaseUsername', 'userDatebasePassword', 'userDatabaseName');
?>

Of course, you will want to use the correct 'host', 'username', 'password', 'database' names.

Step #3

Create two tables. One for your encryption keys and one for your passwords. At this point I would use PHP to create the MySQL. Let's call this file pass_create.php (Permission 400). Put it in the restricted folder too.

<?php /* restricted/pass_create.php */
require_once 'https.php'; require_once 'connect.php';
if(!$kb || $!db)die('connection failure');
$kb->query('CREATE TABLE passkeys(
  user TINYTEXT NOT NULL,
  pass TINYTEXT NOT NULL
)ENGINE=InnoDB');
$keyStatement = $kb->prepare('INSERT passkeys VALUES (?, ?)'); 
$keyStatement->bind_param('ss', 'iYa9Ab%5@3m', 'w*Fu4m^Ga92'); $keyStamement->execute();
$db->query('CREATE TABLE passes(
  id BIGINT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(id),
  user TINYBLOB NOT NULL,
  pass TINYBLOB NOT NULL
)ENGINE=InnoDB');
// normally you would do the new password inserts dynamically with AJAX - just an example
$keyResult = $kb->query('SELECT user, pass FROM passkeys');
$keyObj = $keyResult->fetch_object(); $userKey = $keyObj->user; $passKey = $keyObj->pass;
$keyResult->free();
$createPassStatement = $db->prepare('INSERT passes (user, pass) VALUES(DES_ENCRYPT(?, ?), DES_ENCRYPT(SHA2(?), ?))');
$createPassStatement->bind_param('ssss', 'usernameHere', $userKey, 'passwordHere', $passKey);
$createPassStatement->execute(); $kb->close(); $db->close();
?>

Create and execute a temp.php page with <? require_once 'restricted/https.php'; require_once 'restricted/pass_create.php'; ?> on it in htdocs. Run temp.php file in your Browser, then delete it. Change $keyStatement->bind_param('ss', 'iYa9Ab%5@3m', 'w*Fu4m^Ga92') on restricted/pass_create.php to $keyStatement->bind_param('ss', '', ''). Type die('hacker'); directly after <?php on restricted/pass_create.php and resave it, or just get rid of that page altogether.

Step #4

Create a js folder (Permission 100) to hold your JavaScript files and a small library that makes it easy to send data to the Server (see below). We'll call the file external.js (Permission 444). Put external.js in your js folder.

//<![CDATA[
/* js/external.js */
var get, post, doc, html, bod, nav, mobile, M, I, S, Q, aC, rC, special, unspecial; // for use on other loads
addEventListener('load', function(){
get = function(url, success, context){
  var x = new XMLHttpRequest;
  var c = context || this;
  x.open('GET', url);
  x.onload = function(){
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  x.send();
}
post = function(url, send, success, context){
  var x = new XMLHttpRequest;
  var c = context || this;
  x.open('POST', url);
  x.onload = function(){
    if(success)success.call(c, JSON.parse(x.responseText));
  }
  if(typeof send === 'object' && send && !(send instanceof Array)){
    if(typeof FormData !== 'undefined' && send instanceof FormData){
      x.send(send);
    }
    else{
      var s, r = [];
      for(var p in send){
        s = send[p];
        if(typeof s === 'object')s = JSON.stringify(s);
        r.push(encodeURIComponent(p)+'='+encodeURIComponent(s));
      }
      x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); x.send(r.join('&'));
    }
  }
  else{
    throw new Error('send argument must be an Object');
  }
  return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator;
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
aC = function(element, className, yFunc){
  var s = element.className.split(/\s+/), n = s.indexOf(className);
  if(n === -1){
    s.push(className); element.className = s.join(' ').trim();
    if(yFunc)yFunc(element);
  }
  return function(className, yFunc){
    return aC(element, className, yFunc);
  }
}
rC = function(element, className, yFunc){
  var s = element.className.split(/\s+/), n = s.indexOf(className);
  if(n !== -1){
    s.splice(n, 1); element.className = s.join(' ').trim();
    if(yFunc)yFunc(element);
  }
  return function(className, yFunc){
    return rC(element, className, yFunc);
  }
}
special = function(str){
  return str.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
unspecial = function(str){
  return str.replace(/&amp;/g, '&').replace(/&apos;/g, "'").replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}
}); // end load
//]]>

Step #5

Create a css and login folder (both Permission 100). Put a file called external.css (Permission 444) in your css folder. Put an html page called index.php (Permission 444) in your login folder. See the code below:

/* css/external.css */
*{
  box-sizing:border-box;
}
html,body{
  padding:0; margin:0; width:100%; height:100%;
}
#logon{
  background:#ccc; padding:5px 7px;
}
label{
  display:inline-block; font-size:24px; width:100%;
}
input{
  width:100%; font-size:24px; padding:3px 5px; margin-bottom:7px; border:1px solid #d00;
}
.yes{
  border-color:#0a0;
}
#login{
  background:linear-gradient(#0a0, #070); color:#fff; border-radius:5px; margin-top:7px; 
  padding:5px 0;
}
.error{
  color:#a00; text-align:center; padding-bottom:5px;
}
.hide{
  display:none;
}
<?php /* login/index.php */ require_once '../restricted/https.php'; ?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Title Here</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='../js/external.js'></script>
    <script src='../js/login.js'></script>
  </head>
<body>
  <div class='main'>
    <div id='logon'>
      <label for='user'>Username</label>
      <input id='user' type='text' maxlength='64' />
      <label for='pass'>Password</label>
      <input id='pass' type='password' maxlength='64' />
      <input id='login' type='button' value='LOGIN' />
      <div id='login_error' class='error'>Username and Password Required</div>
    </div>
  </div>
</body>
</html>

Step #6

Create a file called login.js (Permission 444) in the same js folder you already created.

//<![CDATA[
/* ..js/login.js - up a level because we're in the login folder - requires ..js/external.js */
addEventListener('load', function(){
var user = I('user'), pass = I('pass'), login = I('login'), error = I('login_error');
function emptyTests(){
  var uv = user.value, pv = pass.value;
  if(uv.value === ''){
    if(pv.value === ''){
      rC(pv, 'yes'); error.innerHTML = 'Username &amp; Password Required';
    }
    else{
      aC(pv, 'yes'); error.innerHTML = 'Username Required';
    }
    rC(uv, 'yes'); rC(login, 'yes'); rC(error, 'hide'); // remove error and hide classes
  }
  else if(pv.value === ''){
    aC(uv, 'yes'); rC(pv, 'yes'); rC(login, 'yes'); error.innerHTML = 'Password Required'; 
    rC(error, 'hide');
  }
  else{
    aC(uv, 'yes'); aC(pv, 'yes'); aC(login, 'yes'); aC(error, 'hide'); // no require error - hide error class
    return true;
  }
  return false;
}
function logTest(){
  if(emptyTests()){
    var fd = new FormData;
    fd.append('pepper', 'lim7it8!#WTF'); fd.append(user, user.value); 
    fd.append(pass, pass.value);
    post('login.php', fd, function(r){
      var o = JSON.parse(r);
      if(o && o.good){
        location = 'login_success.php';
      }
      else{
        // don't give username password details
        error.innerHTML = 'Login Error'; rC(user, 'yes'); rC(pass, 'yes'); 
        rC(login, 'yes'); rC(error, 'hide');
    });
  }
}  
user.onkeyup = pass.onkeyup = function(e){
  if(e.key === 'Enter'){
    logTest();
  }
  else{
    emptyTests();
  }
}
login.onclick = logTest;
}); // end load
//]]>

Step #7

Create a index.php file (Permission 444) and put it in the login folder you already created:

<?php
session_start(); // send before headers
require_once '../restricted/https.php'; $o = new StdClass; $o->good = false;
if(isset($_POST['pepper'], $_POST['user'], $_POST['pass']) && $_POST['pepper'] === 'lim7it8!#WTF' && strlen($_POST['user']) < 65 && strlen($_POST['pass']) < 65){ // limit and test for submission
  require_once '../restricted/connect.php';
  $user = $_POST['user']; $pass = $_POST['user']; $o = new StdClass;
  $keyRes = $kb->query('SELECT user, pass FROM passkeys'); $keyObj = $keyRes->fetch_object();
  $userKey = $keyObj->user; $passKey = $keyObj->pass; $keyRes->free(); $kb->close();
  $logStmt = $db->prepare("SELECT 'good' FROM passes WHERE user=DES_ENCRYPT(?, ?) && pass=DES_ENCRYPT(SHA2(?), ?)");
  $logStmt->bind_param('ssss', $user, $userKey, $pass, $passKey); $logStmt->execute();
  $logStmt->bind_result($yes);
  if($logStmt->fetch() && $yes === 'good'){
    $o->good = true; $_SESSION['login'] = 'can!B4Hard2?';
  }
  $logStmt->free(); $db->close();
  echo json_encode($o);
}
else{
  echo json_encode($o);
  die('hacker');
}

Step #8

Create your login_success.php (Permission 444) in your htdocs folder:

<?php /* login_success.php - you should really call this what you want   - just make sure the location in the JavaScript AJAX is the same */
session_start(); // before headers
require_once 'restricted/https.php';
if(!isset($_SESSION['login']) || $_SESSION['login'] !== 'can!B4Hard2?')die('hacker');
?>
<!-- now create your other html page -->

Now you can tell your users to login at yourdomain/login!!! Make sure you are serving over https. And... yes, I know some of those steps are really multiple steps. They're really just references for you to ask questions about.

StackSlave
  • 10,436
  • 2
  • 17
  • 33
  • 2
    While this answer is great. I can't help but think this _massively_ over-complicates things for a beginner (which OP clearly is). – GROVER. Jan 07 '20 at 04:32
  • I'm also 90% sure you just copy and pasted this, which is fine in some cases, but it doesn't even explain where he went wrong in the first place or use **any** of his original code. – GROVER. Jan 07 '20 at 04:33
  • It's not a copy and paste, so there could be typos. Let me know! – StackSlave Jan 07 '20 at 04:37
  • First of all, this is nothing for a beginner and thus extreme overkill. It could only be used with copy/paste by the user as he has no idea what is going on. Secondly, while you put in a lot of effort to create steps, it provides a false sence of security because it adds next to nothing security wise. Like using a fast hash to store passwords, adding a pepper to the formdata, using two database to store keys but put the db passwords in plaintext, etc. I apploud the effort you are willing to put in, but we now have an answer that `looks` great, but isn't when you look into it. – Hugo Delsing Jan 10 '20 at 12:03