CrankBerry Blog Title
2009


(87) Comments

Secure PHP login without database

Although not recommended but maybe for some reason you need to create a PHP login without the use of any database (SQL). For some reason you maybe scared to approach, but here I made a script that is fairly secure without utilizing any database at all. It allows users to login and stay logged in. If you are one of those people then here's the script for you.

Now this script does not use any external files to store user names and password as it opens up more security flaws for hackers, so everything is managed in an array within the PHP. If somebody was able to get a hold of your PHP file this will compromise things but the chances of that happening is fairly close to utilizing a database.

Features

  • Utilizes cookies to give users ability to stay logged in across multiple pages
  • Secure login algorithm mitigates hacking attempts

Drawbacks

Now by not utilizing a database there are some drawbacks and they are:

  • Users cannot change password and user names manually
  • Users can attempt login as many times as they want

With that said, it means that usernames and passwords must be managed by an admin. If this is still something for you. If this is not for you wait around because I will convert this script into a database version in the future.

Less Talk More Script

Installation:

Just download all the necessary files which includes:

  • _login.php
  • _login_page.php
  • _login_class.php
  • _login_users.php
  • login.php
  • logout.php

Once you put these in your root folder you need to edit the users and settings. Open up _login_users.php and you'll see:

<?php

//My Login Script
//Attach this to any page that requires Login

//Users and Settings
$domain_code = 'website';       //Alpha Numeric and no space
$random_num_1 = 20;             //Pick a random number between 1 to 500
$random_num_2 = 565;            //Pick a random number between 500 to 1000
$random_num_3 = 3;              //Pick a random number between 1 to 3

//Usernames can contain alphabets, numbers, hyphens and underscore only
//Set users below – Just add " => " with the first " being
//the username and the second " after the => being the password.
//Its an array so add an , after every password except for the
//last one in the list. As shown below
//Eg. $users = array(
//              'user1' => 'password',
//              'user2' => 'password'
//      );

$users = array(
                'user1' => 'password',
                'user2' => 'password'
        );

?>

Modify the domain code and three random numbers. The three random numbers is the key that makes login secure and unique to your website only. Then at the bottom you can create all of your users.

Now in every page that you require the user to login just add the following code to the very top of the page, exactly on line 1.

<?php require('_login.php'); ?>

That's pretty much all you need to do to install the secure login script. The only other thing if you want is you can edit _login_page.php. That's the page people see when they need to login.

Login and Logout

You can lead users to login and logout with links to login.php and logout.php as such.

<a href="login.php">Login</a> | <a href="logout.php">Logout</a>

Displaying Macors

In this case the only macro you can call up is the username after they have logged in. You can call it in a welcome back message like this (placed in your HTML).

Welcome back <?php echo $login->username; ?>

Download the files:
PHP Login Without Database.zip

Alternative Versions:
PHP Login Without Database (Email).zip (Login using Email as username)
PHP Login Without Database (Custom).zip (Custom login page for each user)

Tags: ,

TL
This entry was posted on Friday, October 23rd, 2009 at 10:55 pm and is filed under PHP, Web Security. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.
BL

87 Responses to “Secure PHP login without database”

  1. Jerry Jerry Low says:

    James,

    Basically the script will ensure all your settings are valid before it'll work. The settings are all in _login_users.php

    You have to conform to the comments I have there. And user names can only be alphanumeric with no whitespace (hyphen and underscore is ok).

  2. James James says:

    Hey I tried to use this, but I can't seem to figure out how to login , sorry I really don't feel like having to search this up somewhere else -.-…

    Whenever I go to the index.php it tell me that the admin settings are wrong, I know that the code for that is on page _login.php but how to I get a login form?

  3. Hi! Thanks for sharing this great php login tutorial! I have some improvements… in each page that you want to protect add these lines:

    session_start();
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); #Date in the Past
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); #Always modified
    header("Cache-Control: no-store, no-cache, must-revalidate"); #HTTP/1.1
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache"); #HTTP/1.0
    require_once('_login.php');
    if (!$login->verify_login($key_uid, $key_cid)) {
      header("Location: login.php");
      exit();
    }
    

    The first five headers avoid that another user that have the same session opened backs to previous page and posts again… the if statement verify if the user has logged in or not

    Thanks again!!!

  4. jonas luin jonas luin says:

    i cant stay logged in and have to re-enter my user and password all the time. Whats the problem?

  5. Dumbledore27 Dumbledore27 says:

    One more question. Is there a way to do a log in page for this? So when a user fills out the necessary fields, an email is sent with a validation link and when the user is validated, another username & pass are added to the _login_users.php?

    Thanks. :)

    Btw, I no longer need the thing I asked in my previous comment. ;)

  6. Dumbledore27 Dumbledore27 says:

    It works perfect, but I have just one question.

    Only one directory is password-protected.
    So directories /web and /gfx are not protected, but /vip is.
    I would like to have the "You are logged in as username; ?>" on all of the pages, but since only one directory requires login, would it be possible to say "You are not logged in/You are logged in as Guest" if user is not logged in. If I do it with the code above and am not logged in, I get:
    "You are logged in as ."

    Anything I can do?

  7. Jerry Jerry Low says:

    Kin, this can support up to as many as you like, but the problem is it is not manageable. I'm still working on a deployable database one, only problem is that its fairly simple in management and hard to integrate with prebuilt systems.

  8. Sven Sven says:

    Hello!

    How well does this go up against rainbow tables? Is there a salt? (im noob)

  9. Kin Kin says:

    Hi, Could you please let me know how many user names and passwords will it be best to use this method ? Eg. Is there any limit for the no. of users like less than 100 users only etc., stuff ?

    Could you also provide me the code for login of users USING the Database?

    Thank you,
    Kin

  10. AdamB AdamB says:

    hey jerry awesome code btw.. I don't know exactly what im doing wrong BUT even if i unzip the default php login site you have here and keep all the files in one folder and use the generic username and password you have in the default code i just get brought back to the same login page ;( any suggestions?

  11. shawna shawna says:

    is there a way to embed the form into a div on an existing website? im new to php, and I have it working for when someone clicks on the link to get to the protected site. the username and password screen comes up with no issues and they can login, but I would also like to add a username and password field to the main page of the website in a div so they can just enter the credentials there. what code would I use in the div on the main page from the form? can i just add this line of code from the _login_page.php?

    Please Login
    You must login to view the following content. Contact admin if you are having problem or have forgotten your password.

    error_login(); ?>

    Username

    Password

    would I then have to put the

    line of code at the top of the index page as well?

    thanks so much

  12. Jack Jack says:

    hi, i was wondering if i could add values automattically to this table, because i am going to have an automated signup system

    Thanks,

    Jack Renshaw

  13. jack jack says:

    Hi jerry,
    I posted something before but I can,t see it on the webpage.

    It was about some type of automated adding system. If its possible could I please have a script.

    Thanks a lot,

    Jack

  14. Jack Jack says:

    Hi,

    I was wondering if there was any was of adding to the array automatically. Also, i have an addition for anyone else interested:

    You can add an email(or other information) with this:

    $users['user1']=array('email'=>'bob@bob.com','password'=>'mypass','other'=>'info');

  15. Jerry Jerry Low says:

    Hey Babs just point the page where they need to go to the zip file. The custom script at the bottom has one that directs the user to a different page after logging in.

    -Jerry

  16. Babs Babs says:

    Great script! What I need is only one password and no username. If the password is correct, they should be redirected to a zip-file. What should I change in the code in order to get this? Thanks for the help!

  17. Jerry Jerry Low says:

    Can you elaborate some more. Typical message when the username and password combination doesn't match. Maybe I missed something here.

  18. aerifal aerifal says:

    why it says: "invalid login username and password"?
    help me pls

  19. Nathanial Nathanial says:

    Oh! I figured it out after trying for a bit. Thanks again!

  20. Nathanial Nathanial says:

    Oops, my code got hidden… Here it is:

    Currently the first line of my directed to page is:

    I tried, without luck:

  21. Nathanial Nathanial says:

    One more question if you don't mind…
    I think I'm asking the same thing that Kyle asked back in mid-January, but I couldn't figure it out. Again, I'm using the "PHP Login Without Database (Custom).zip" version.
    Rather than checking the username as Kyle asked, I would rather check the forwarded page name instead, as I have multiple users forwarded to each different page.

    Currently the first line of my directed to page is:

    I tried, without luck:

    Basically I have around 100 users, 25 of them direct to page-1.php, 25 direct to page-2.php, 25 direct by page-3.php, and 25 direct by page-4.php. I want to make sure that once somebody logs in and is directed to page-1.php, they can't just change the address bar to reference any of the three other pages.

    Thanks in advance for your guidance!
    ~Nathanial

  22. Nathanial Nathanial says:

    Amazing!
    It's perfect, thank you so much!

  23. Jerry Jerry Low says:

    Nathanial

    Open up your _login_users.php

    For each user add as much as you like after the redirect page:

    array('user1', 'test', 'page1.php', 'John Doe', 'Age 28'),

    Now open up your _login_class.php

    Add the following line after line 16:

    var $userArray = array();

    Replace the two functions from line 76 – 106 with:

    function check_login ($username, $password) {
    	//Check Login
    	foreach ($this->users as $userArray) {
    	if($username== $userArray[0] && $password == $userArray[1]){
    		$this->username = $userArray[0];
    		$this->forward = $userArray[2];
    		$this->userArray = $userArray;
    
    		return TRUE;
    	}
    	}
    
    	return FALSE;
    }
    
    function verify_login ($key_uid, $key_cid) {
    	//Check Login
    	if ($key_cid = $this->code_encryption($key_uid)) {
    		//Validate Username Is True
    		foreach ($this->users as $userArray) {
    		if($key_uid==$this->user_encryption($userArray[0])){
    			$this->username = $userArray[0];
    			$this->userArray = $userArray;
    
    			return TRUE;
    		}
    		}
    	}
    
    	return FALSE;
    }
    

    Now on individual pages you can call on the data from each user with

    < ?php echo $login->userArray[3]; ?>

    With userArray[3] being the name and userArray[4] being the age (for my example).

    Hope that helps.

  24. Nathanial Nathanial says:

    Hello!
    Regarding the "PHP Login Without Database (Custom).zip" version. How could I add a fourth variable to the _login_users.php file and reference it to display on the logged in page?
    For example, I have my username, password, and forward page currently. I would like to add a friendly_name and have the logged in page display it.
    Even if username = MyUserName I would want the friendly_name to be "John Smith". This way when 'MyUserName' logs in, the welcome page can say "Hello John Smith".

    Thanks!

  25. Jerry Jerry Low says:

    Kyle,

    You may have to build something to the top of the page to cross check that the user is the right one and allowed to use that page. Something like

    if ($users[0] != 'kyle') exit();

    With $user[x] != 'x' for each individual pages.

  26. Kyle Kyle says:

    Hey Jerry – thanks for this.. I'm using the custom script and have built my user array and kicking them to there own pages. But these users are in effect "super users" and can access another users custom page while logged in. How do I restrict the custom pages to their specific users?

    Thanks,
    Kyle

  27. Becky Becky says:

    Hi Jerry, first of all this is brilliant! and exactly what I've been looking for for weeks!

    Unfortunately I have the same problem as Mathias has been having, despite not altering the code. Originally I customized the code to display my own design elements and when I published it the login failed to work. So I re-downloaded the original source files and tried just running it without alterations and still had the same problem.

    Basically when I enter the username and password and hit login it returns to the same page minus the username and password details. Any ideas? It would be great if you could help as the login script is perfect for my project!

    Thanks, Becky

  28. David David says:

    Hi, this is just what I am looking for only on the customised version I can not get it to go to page1.php or page2.php? It still goes to index.php when the login is successful rather than each unique page per user. Any help would be great.

  29. Ralph Ralph says:

    Hi Jerry,

    I saw that you have a customized version that redirects users to a certain page, so I did a test with a page1.php and a page2.php but both users still goes after login to index.php. This is not so strange cause the header location in login.php is index.php. So what do we have to change that user1 goes to page1.php and user2 to page2.php after login?

  30. Jerry Jerry Low says:

    Tutto, there were a bunch of small changes in the class file and the login.php file. I had to change the way it authenticated the user name. If you open the files side by side you should be able to sniff through the differences.

    I actually didn't post the database version because it wasn't as clear cut deployable. Unfortunately I haven't had time to modify the code to work for everybody yet.

    -Jerry

  31. Tutto Tutto says:

    Hey Jerry,

    Thanks for the code to re-route users to different pages. I see the changes to the "_login_users.php" page but if you don't mind my asking, what else did you change to make the other php docs recognize this change (trying to learn what I can, teach a man to fish etc…)

  32. Tutto Tutto says:

    Hey Jerry,

    Sorry for my tardy response to your quick response, I was away this past week. Thanks for the markup I'll take a look and do some testing. Thanks! For a different project, you were talking about creating a version that did in fact work with a database. Did I miss the link?

    Best,
    Tutto

  33. Jerry Jerry Low says:

    Hey Mathias,

    I tried giving it some test but, without looking at the coding I won't be able to figure it out. I was wondering if you made any modifications to the code specifically in the login_class or login file.

    -Jerry

  34. Mathias Mathias says:

    it should be user1 and the pw is test

  35. Jerry Jerry Low says:

    Mathias, what is the username and password? I tried with the one you posted but it wasn't working.

    Yes my apologies. I have been quite busy the last little bit.

  36. Mathias Mathias says:

    Hi Jerry,

    No my problem ain't resolved.
    I'm checking every day these comment page, but i understand you are busy ;).

    So can you have a look, what i'm doing wrong…

    Thx mate

  37. Jerry Jerry Low says:

    Hey Mathias, I was wondering if your problem was resolved?

Leave a Reply

Spam protection by WP Captcha-Free