Viedt Viedt - 29 days ago 4
PHP Question

Creating a very simple 1 username/password login in php

I want to make a single login for just 1 user without storing in a database but I can't seem to get this to work.

My code: login.php

<html>
<head>
<title>Login</title>
</head>
<h3>Add entry</h3>
<p> Add another Article</p>
<form action="trylog.php" method = "post">
<label for="username">Username</label> <input type="username" id="usename" name="username"><br /><br />
<label for="password">Password:</label> <input type="text" id="password" name="password"><br /><br />
<button type = "submit">Login</button>
</form>
</html>


trylog.php

<html>
<title>Login</title>
<body>
<?php
$usr = "admin";
$psw = "password";
$username = '$_POST[username]';
$password = '$_POST[password]';
//$usr == $username && $psw == $password
session_start();
if ($_SESSION['login']==true || ($_POST['username']=="admin" && $_POST['password']=="password")) {
echo "password accepted";
$_SESSION['login']=true;
else {
echo "incorrect login";
}
?>

<form name="input" action="adminportal.php" method="get">
<input type="submit" value="Home">
</form>
</body>
</html>

Answer

Your code could look more like:

<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
  $username = $_POST['username']; $password = $_POST['password'];
  if($username === 'admin' && $password === 'password'){
    $_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
  }
  if($username !== 'admin')$userError = 'Invalid Username';
  if($password !== 'password')$passError = 'Invalid Password';
}
echo "<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <style type='text.css'>
       @import common.css;
     </style>
   </head>
<body>
  <form name='input' action='{$_SERVER['PHP_SELF']}' method='post'>
    <label for='username'></label><input type='text' value='$username' id='username' name='username' />
    <div class='error'>$userError</div>
    <label for='password'></label><input type='password' value='$password' id='password' name='password' />
    <div class='error'>$passError</div>
    <input type='submit' value='Home' name='sub' />
  </form>
  <script type='text/javascript' src='common.js'></script>
</body>
</html>";
?>

Now, when the page is redirected based on the header('LOCATION:wherever.php), put session_start() at the top of the page and test to make sure $_SESSION['login'] === true. Remember that == would be true if $_SESSION['login'] == 1 as well. Of course, this is a bad idea for security reasons, but my example may teach you a different way of using PHP.

Comments