[php] Easy login script without database

How do I create an easy login script that does not require a database. I would like it to be safe.

Alright, what about this script, i just made it by my knowledge in php.

<?php 
// Start session
session_start(); 

// Username and password
$ID = "admin";
$pass = "123456";

if (isset($_POST["ID"]) && isset($_POST["pass"])) { 

    if ($_POST["ID"] === $anvandarID && $_POST["pass"] === $pass) { 
    /
    $_SESSION["inloggedin"] = true; 

    header("Location: safe_site.php"); 
    exit; 
    } 
        // Wrong login - message
        else {$wrong = "Bad ID and password, the system could not log you in";} 
}
?> 

The safe_site.php contains this and some content:

session_start();

if (!isset($_SESSION["inloggning"]) || $_SESSION["inloggning"] !== true) {
header("Location: login.php");
exit;
}

This question is related to php login

The answer is


I would use a two file setup like this:

index.php

<?php 
session_start(); 

define('DS',  TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF',  $_SERVER['PHP_SELF'] );

if (!USERNAME or isset($_GET['logout']))
 include('login.php');

// everything below will show after correct login 
?>

login.php

<?php defined('DS') OR die('No direct access allowed.');

$users = array(
 "user" => "userpass"
);

if(isset($_GET['logout'])) {
    $_SESSION['username'] = '';
    header('Location:  ' . $_SERVER['PHP_SELF']);
}

if(isset($_POST['username'])) {
    if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
  $_SESSION['username'] = $_POST['username'];
  header('Location:  ' . $_SERVER['PHP_SELF']);
    }else {
        //invalid login
  echo "<p>error logging in</p>";
    }
}

echo '<form method="post" action="'.SELF.'">
  <h2>Login</h2>
  <p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
  <p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
  <p><input type="submit" name="submit" value="Login" class="button"/></p>
  </form>';
exit; 
?>

***LOGIN script that doesnt link to a database or external file. Good for a global password -

Place on Login form page - place this at the top of the login page - above everything else***

<?php

if(isset($_POST['Login'])){

if(strtolower($_POST["username"])=="ChangeThis" && $_POST["password"]=="ChangeThis"){
session_start();
$_SESSION['logged_in'] = TRUE;
header("Location: ./YourPageAfterLogin.php");

}else {
$error= "Login failed !";
}
}
//print"version3<br>";
//print"username=".$_POST["username"]."<br>";
//print"password=".$_POST["username"];
?>

*Login on following pages - Place this at the top of every page that needs to be protected by login. this checks the session and if a user name and password has *

<?php
session_start();
if(!isset($_SESSION['logged_in']) OR $_SESSION['logged_in'] != TRUE){

header("Location: ./YourLoginPage.php");
}
?>

Save the username and password hashes in array in a php file instead of db.

When you need to authenticate the user, compute hashes of his credentials and then compare them to hashes in array.

If you use safe hash function (see hash function and hash algos in PHP documentation), it should be pretty safe (you may consider using salted hash) and also add some protections to the form itself.


You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:

  1. It's not very secure (username and password are trivially encoded on the wire)
  2. It's difficult to maintain (you have to log into the server to add or remove users)
  3. You have no control over the login dialog box presented by the browser
  4. There is no way of logging out, short of restarting the browser.

Unless you're building a site for internal use with few users, I wouldn't really recommend it.


FacebookConnect or OpenID are two great options.

Basically, your users login to other sites they are already members of (Facebook, or Google), and then you get confirmation from that site telling you the user is trustworthy - start a session, and they're logged in. No database needed (unless you want to associate more data to their account).


Try this:

<?php
        session_start();
        $userinfo = array(
            'user'=>'5d41402abc4b2a76b9719d911017c592', //Hello...
        );

        if(isset($_GET['logout'])) {
            $_SESSION['username'] = '';
            header('Location:  ' . $_SERVER['PHP_SELF']);
        }

        if(isset($_POST['username'])) {
            if($userinfo[$_POST['username']] == md5($_POST['password'])) {
                $_SESSION['username'] = $_POST['username'];
            }else {
                header("location:403.html"); //replace with 403
            }
        }
?>
<?php if($_SESSION['username']): ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Logged In</title>
        </head>

        <body>
            <p>You're logged in.</p>
            <a href="logout.php">LOG OUT</a>
        </body>
    </html>

<?php else: ?>
    <html>
        <head>
            <title>Log In</title>
        </head>
        <body>
            <h1>Login needed</h1>
            <form name="login" action="" method="post">
                <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
                    <tr>
                        <td colspan="3"><strong>System Login</strong></td>
                    </tr>
                    <tr>
                        <td width="78">Username:</td>
                        <td width="294"><input name="username" type="text" id="username"></td>
                    </tr>
                    <tr>
                        <td>Password:</td>
                        <td><input name="password" type="password" id="password"></td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td><input type="submit" name="Submit" value="Login"></td>
                    </tr>
                </table>
            </form>
        </body>
    </html>
<?php endif; ?>

You will need a logout, something like this (logout.php):

<?php
    session_start();
    session_destroy();
    header("location:index.html"); //Replace with Logged Out page. Remove if you want to use HTML in same file.
?>

// Below is not needed, unless header above is missing. In that case, put logged out text here.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>
    <body>
        <!-- Put logged out message here -->
    </body>
</html>

If you don't have a database, where will the PERMANENT record of your users' login data be stored? Sure, while the user is logged in, the minimal user information required for your site to work can be stored in a session or cookie. But after they log out, then what? The session goes away, the cookie can be hacked.

So your user comes back to your site. He tries to log in. What trustworthy thing does your site compare his login info to?


There's no reason for not using database for login implementation, the very least you can do is to download and install SQLite if your hosting company does not provide you with enough DB.


if you dont have a database, you will have to hardcode the login details in your code, or read it from a flat file on disk.