mtWeb  Home > PHP > Creating a Secure PHP Login ScriptSitemap  Search

Creating a Secure PHP Login Script

Posted by martin on 9 Jul 2002, last updated on 25 Aug 2002.

Explains how to create a secure PHP login script that will allow safe authentication. Features remember-me function using cookies, validates logins on each request to prevent session stealing.

How does this work

This is a short explanation why I have chosen these authentication methods.

Users with shell access to the web server can scan valid session id's if the default /tmp directory is used to store the session data.

The protection against this kind of attack is the IP check.

Somebody who has a site (on a shared host with you) can generate valid session for your site.

This is why the checkSession method is used and the session id is recorded in the database.

Somebody may sniff network traffic and catch the cookie.

The IP check should eliminate this problem too.

Preparation

You need first to decide what information to store about members, the examples provided will assume almost nothing to make it easier to read.

I will use the PHP 4.1 super global arrays like $_SESSION, $_GET, etc. If you want to make it work on an earlier version of PHP you will have to substitute these with $GLOBALS['HTTP_SESSION_VARS'].

Database schema

This is only an example bare structure suitable for online administration, if you want to have registered members you should add more columns.

The schema is somewhat MySQL specific, I have yet to use another database other than MySQL and PostgreSQL but if you are using PostgreSQL you can convert the schema with the example script provided in my article Converting a database schema from MySQL to PostgreSQL.

CREATE TABLE member (
  id int NOT NULL auto_increment,
  username varchar(20) NOT NULL default '',
  password char(32) binary NOT NULL default '',
  cookie char(32) binary NOT NULL default '',
  session char(32) binary NOT NULL default '',
  ip varchar(15) binary NOT NULL default '',
  PRIMARY KEY  (id),
  UNIQUE KEY username (username)
);

The password and cookie fields are md5 hashes which are always 32 octets long. Cookie is the cookie value that is sent to the user if he/she requests to be remembered, session and ip are respectively the session id and the current IP of the visitor.

Connecting to the database

function &db_connect() {
	require_once 'DB.php';

	PEAR::setErrorHandling(PEAR_ERROR_DIE);

	$db_host = 'localhost';
	$db_user = 'shaggy';
	$db_pass = 'password';
	$db_name = 'shaggy';

	$dsn = "mysql://$db_user:$db_pass@unix+$db_host/$db_name";

	$db = DB::connect($dsn);

	$db->setFetchMode(DB_FETCHMODE_OBJECT);
	return $db;
}

This function connects to the database returning a pointer to a PEAR database object.

Session variables

To ease access to the current user's information we register it as session variables but to prevent error messages and set some defaults we use the following function.

function session_defaults() {
	$_SESSION['logged'] = false;
	$_SESSION['uid'] = 0;
	$_SESSION['username'] = '';
	$_SESSION['cookie'] = 0;
	$_SESSION['remember'] = false;
}

... with a check like:

if (!isset($_SESSION['uid']) ) {
	session_defaults();
}

to set the defaults. Of course session_start must be called before that.

To the core of the script

To allow easier integration with other scripts and make things more modular the core script is an object with very simple interface.

class User {
	var $db = null; // PEAR::DB pointer
	var $failed = false; // failed login attempt
	var $date; // current date GMT
	var $id = 0; // the current user's id

	function User(&$db) {
		$this->db = $db;
		$this->date = $GLOBALS['date'];

		if ($_SESSION['logged']) {
			$this->_checkSession();
		} elseif ( isset($_COOKIE['mtwebLogin']) ) {
			$this->_checkRemembered($_COOKIE['mtwebLogin']);
		}
	}

This is the class definition and the constructor of the object. OK it's not perfectly modular but a date isn't much of a problem. It is invoked like:

$date = gmdate("'Y-m-d'");
$db = db_connect();
$user = new User($db);

Now to clear the code purpose, we check if the user is logged in. If he/she is then we check the session (remember it is a secure script), if not and a cookie named just for example mtwebLogin is checked - this is to let remembered visitors be recognized.

Logging in users

To allow users to login you should build a web form, after validation of the form you can check if the user credentials are right with $user->_checkLogin('username', 'password', remember). Username and password should not be constants of course, remember is a boolean flag which if set will send a cookie to the visitor to allow later automatic logins.

	function _checkLogin($username, $password, $remember) {
		$username = $this->db->quote($username);
		$password = $this->db->quote(md5($password));

		$sql = "SELECT * FROM member WHERE " .
			"username = $username AND " .
			"password = $password";

		$result = $this->db->getRow($sql);

		if ( is_object($result) ) {
			$this->_setSession($result, $remember);
			return true;
		} else {
			$this->failed = true;
			$this->_logout();
			return false;
		}
	}

The function definition should be placed inside the User class definition as all code that follows. The function uses PEAR::DB's quote method to ensure that data that will be passed to the database is safely escaped. I've used PHP's md5 function rather than MySQL's because other databases may not have that.

The WHERE statement is optimized (the order of checks) because username is defined as UNIQUE.

No checks for a DB_Error object are needed because of the default error mode set above. If there is a match in the database $result will be an object, so set our session variables and return true (successful login). Otherwise set the failed property to true (checked to decide whether to display a login failed page or not) and do a logout of the visitor.

The logout method just executes session_defaults().

Setting the session

function _setSession(&$values, $remember, $init = true) {
   $this->id = $values->id;
   $_SESSION['uid'] = $this->id;
   $_SESSION['username'] = htmlspecialchars($values->username);
   $_SESSION['cookie'] = $values->cookie;
   $_SESSION['logged'] = true;

   if ($remember) {
      $this->updateCookie($values->cookie, true);
   }

   if ($init) {
      $session = $this->db->quote(session_id());
      $ip = $this->db->quote($_SERVER['REMOTE_ADDR']);

      $sql = "UPDATE member SET session = $session, ip = $ip WHERE " .
         "id = $this->id";
      $this->db->query($sql);
   }
}

This method sets the session variables and if requested sends the cookie for a persistent login, there is also a parameter which determines if this is an initial login (via the login form/via cookies) or a subsequent session check.

Persistent logins

If the visitor requested a cookie will be send to allow skipping the login procedure on each visit to the site. The following two methods are used to handle this situation.

function updateCookie($cookie, $save) {
   $_SESSION['cookie'] = $cookie;
   if ($save) {
      $cookie = serialize(array($_SESSION['username'], $cookie) );
      set_cookie('mtwebLogin', $cookie, time() + 31104000, '/directory/');
   }
}

Checking persistent login credentials

If the user has chosen to let the script remember him/her then a cookie is saved, which is checked via the following method.

function _checkRemembered($cookie) {
	list($username, $cookie) = @unserialize($cookie);
	if (!$username or !$cookie) return;

	$username = $this->db->quote($username);
	$cookie = $this->db->quote($cookie);

	$sql = "SELECT * FROM member WHERE " .
		"(username = $username) AND (cookie = $cookie)";

	$result = $this->db->getRow($sql);

	if (is_object($result) ) {
		$this->_setSession($result, true);
	}
}

This function should not trigger any error messages at all. To make things more secure a cookie value is saved in the cookie not the user password. This way one can request a password for areas which require even higher security.

Ensuring valid session data

function _checkSession() {
	$username = $this->db->quote($_SESSION['username']);
	$cookie = $this->db->quote($_SESSION['cookie']);
	$session = $this->db->quote(session_id());
	$ip = $this->db->quote($_SERVER['REMOTE_ADDR']);

	$sql = "SELECT * FROM member WHERE " .
		"(username = $username) AND (cookie = $cookie) AND " .
		"(session = $session) AND (ip = $ip)";

	$result = $this->db->getRow($sql);

	if (is_object($result) ) {
		$this->_setSession($result, false, false);
	} else {
		$this->_logout();
	}
}

So this is the final part, we check if the cookie saved in the session is right, the session id and the IP address of the visitor. The call to setSession is with a parameter to let it know that this is not the first login to the system and thus not update the IP and session id which would be useless anyway.

Comments

This Script
by Vincent (vince@vtgames.com) on 14 Sep 2002 9:15pm GMT

This script isn't entirely helpful. Sure, it provides the front-end for the login, but it's buggy as hell. For one, even when choosing not to remember your login, it STILL does regardless.

Also, it's VERY insecure, as it's not encrypted well at all. If you're going to use encryption, make your own method. My method has so far been uncrackable, and is contest winning software in several places.

It's pretty nice for beginners, though.

So what's wrong?
by martin on 14 Sep 2002 10:13pm GMT

Ya, sure. Did you test that or you're just flaming?

I wouldn't call that insecure, just check most of the other scripts around. Get the point?

to vincent
by guillem (catalaestape@terra.es) on 23 Sep 2002 9:12pm GMT

hey u talk like a guru i'd like to see ur uncrackable user system, if you really made one ¬¬

hey martin very good job, there are many ways to do a member system i'll try yours and let you know if I have any doubts, ppl like you make other like me learn this nice language ;)

question
by guillem () on 24 Sep 2002 5:37pm GMT

i see u use session_id() how is that function? coz i think its not there?

2ond i dont really understand how this works $ip = $this->db->quote($_SERVER['REMOTE_ADDR']);

i'm trying to change whole database connection to a class I made by my own which has basic funcitons like querying and fetching results, there's too thing to change to use my method? could you put an example with the basics mysql connection functions instead of PEAR ?

thanks in advance ;)

Sessions and PEAR methods
by martin on 24 Sep 2002 6:04pm GMT

The session_id() function returns the current session id (or the new generated where applicable).

$db->quote quotes and escapes a string that will be used as a database field. You can replace the above call with:

$ip = "'" . mysql_escape_string($_SERVER['REMOTE_ADDR']) . "'"

I just don't have the time to change the script to MySQL native functions, don't you have PEAR available? If you are using a recent PHP version you can actually install it on your own (your hosting admin doesn't have to do anything).

love it
by guillem on 26 Sep 2002 8:08pm GMT

well i have been messing with this system and i love it. I made few changes to fill my needs but the algorythm is moreless the same. I have been thinking about how could this be improved, I thought that many users can use proxies which in some cases would make changing their ip in same session. My question is, how important can this be? maybe using something like catch ip like 23.234.123.X or can ip be avoided in the checksession or checklogin? in fact sniffing network in a shared host it's not as normal as it seems, it depents on the company u're being hosted if they catch someone sniffin legal actions can be taken...

i really don't know if this could be a problem thxs again for this script ;)

AOL style proxies
by martin on 27 Sep 2002 5:11pm GMT

A simple replace of the two references to $ip = $_SERVER['REMOTE_ADDR'] with

$ip = explode('.', $_SERVER['REMOTE_ADDR']);
array_pop($ip);
$ip = implode('.', $ip);

would do.

Nice
by OxiMoron (anything@oximoron.f2o.org) on 5 Oct 2002 7:51pm GMT

Nice script..

but why do you access mysql in that way??

there are way easyer ways to do it :?

PEAR::DB vs native calls
by martin on 5 Oct 2002 8:44pm GMT

Well OxiMoron, I've chosen this method because you don't have to rewrite the code if you change your database. You only that you have to make sure your queries will execute at the other RDBMS.

How do I get this to work?
by Poetic (shiller@telusplanet.net) on 4 Nov 2002 3:58pm GMT

Well first off I am a newbie to php and am wondering how I impliment all of the coding for this login. Any chance someone could send me the instructions?

Another module not mentioned
by Dougwo (dew@gfx.com) on 5 Nov 2002 3:27pm GMT

I noticed a reference to Table.php in user.php. Where can that module be found?

It's a PEAR module
by martin on 5 Nov 2002 4:30pm GMT
IP is a bad idea
by Brooklynite () on 8 Nov 2002 11:06pm GMT

It's nice to see tutorials such as this online, that's the great thing about the open source community.

That said, using the IP address in this way can be problematic.

For one, users can be behind a firewall, have a NATted client, or use a proxy. So you end up with several folks all sharing the same IP.

Also, dynamic IPs change. It is possible that the DHCP lease expires in the middle of browsing a site. Granted this isn't the norm, but still possible.

Basically, IPs aren't predictable and can introduce security issues.

More q's
by dougwo (doug@gfx.com) on 9 Nov 2002 3:45am GMT

I found Table Martin, thanks. I also noticed a reference to redirect in login. I assume this is a function to perform header("Location: ") operations to that the script can continue on right But I can't find it anywhere in the modules I downloaded. I'm kinda new at this or I'd write my own. Help?

Also, I am workign with several virtual hosts and want to use httpd.conf to set a default include_path addition to doc-root for each site. This will allow me to use require_once global.php without worrying about where it it. I saw your article on this, but I am in need of specifics for this particular command. Anyone ave any ideas?

Thanks for a great piece of code!

Redirects and PHP configuration via httpd.conf
by martin on 10 Nov 2002 4:52pm GMT

Hey Doug, redirect just does header("Location: /foo"); exit;.

For httpd.conf you can use the same syntax to define PHP configurations: php_value, php_flag and also php_admin_value and php_admin_flag.

where can i found db.php
by nofal (nofal_017@yahoo.com) on 16 Nov 2002 9:38am GMT

i can't found file db.php

nice login but qwirky
by nick () on 24 Nov 2002 12:24am GMT

Like others, I find it inspiring that people like you spend the time making tutorials like this available. It was a similar tutorial that got me started with php 18 months ago.

It really bores me when I see negative attacks from people like Vincent. At the end of the day tutorials like this give people a good starting point for developing their own login systems.

Keep up the good work!

password
by Marc () on 25 Nov 2002 11:22am GMT

Martin, great job on the scripts, thx.

I need your help, I want to encrypt some data and want to use the users password as the salt/key. Using the apache auth mod is easy, I just use the $PHP_AUTH_PW varible. Any idea how I could do the same with your scripts?

Thanks

Re: password
by martin on 25 Nov 2002 7:08pm GMT

Sorry Marc, I have no idea how to port your code to form authentication because I don't know how were the passwords encrypted for the HTTP basic authentication. If you know the method just look in the PHP manual for a function that does the same encryption.

Re: password
by Marc () on 26 Nov 2002 10:23am GMT

Martin, sorry, I may have been a bit unclear in my last message.... looking through your scripts, I am able to use variables like "$_SESSION['uid']" and "$_SESSION['username']".... now do you know of a way to be able to assign the variable "$_SESSION['password']" which will contain the unencrypted password the user used when loggin into the site?

Thanks for your help.

Re: password
by martin on 27 Nov 2002 8:57am GMT

The md5 algorthythm uses one-way encryption, once your passwords are encrypted there's no way back. The only way to get the original password is brute force which takes a lot of time.

Re: password
by Marc () on 28 Nov 2002 12:09pm GMT

I understand that... do you know of a way to register the password as a variable as they are logging into the site, that I am able to reference later on? Like $_SESSION['username']...

no brain
by pbob1 on 2 Dec 2002 1:13pm GMT

I'm currently trying to develope a virtual market place website and need to include some form of registration/login script, all attempts so far have failed, this code seems logical to me but still can't manage to manipulate it to use it can any one please help??

help error
by lore3k (lore3k@fsmail.net) on 4 Dec 2002 4:35pm GMT

Fatal error: Call to undefined function: begin_html() in c:\apache\htdocs\u2\php-login-script\index.php on line 4

whats wrong with this i downloaded and added that to my htdocs folder and setup the db whats rong

db.php
by lek (usanalek@hotmail.com) on 11 Dec 2002 10:21am GMT

Hi,

How I get db.php file?

cookie not saved in dbase?
by nautiboy () on 13 Dec 2002 5:12am GMT

Am I missing something or shouldn't the cookie value in the database get updated when you do an updateCookie? Otherwise, the checkRemembered will never succeed because there won't be a cookie in the database, thus the select will never return anything.

MySQL
by stabby (stabby123@hotmail.com) on 19 Dec 2002 12:43pm GMT

iv downloaded phpmyadmin anthough i cant add rows to my SQL database because everytime i do i got a 403error message. How do i add to my DB without using phpmyadmin, (directly add to it?)

a little bug
by Ken (hek@pku.edu) on 23 Dec 2002 5:54pm GMT

In the database schema, you lose a comma at the end of this line.

session char(32) binary NOT NULL default '',

Recommendation
by Carlos Vargas (cvmagic@magic-gamers.com) on 28 Dec 2002 6:35am GMT

Well, just to make the script a bit more secure i'd recomment to use the MD5 Function on the passwords

Re: Recommendation
by martin on 28 Dec 2002 9:56am GMT

It is already using md5.

login script
by francis ted seguerra (boggss@1asialink.com) on 9 Jan 2003 3:31am GMT

hi martin

i would like to implement a simple login script that uses only session handling with md5 and a database backend with "usr" and "pwd" as the fields in the postgres table. Or how about using the system users(linux users with shell access) to login.

can you make me a script for it?

i would appreciate your effort for this..

thank you so much...

Simple Cookie Login
by Boyer (sean@boyercentral.net) on 12 Jan 2003 10:07am GMT

Hey! I've been looging everywhere for a cookie based login system. However, I need a script to fit around a database (mysql) that's already operational. I run a journal system at www.bcjournal.net (check it if you wanna see what I mean). It uses session based logins, and that just doesn't cut it w/ my members (an myself). We want a login system that uses cookies and allows one to stay logged in for a very long time, or where the browser closes. I've combed your set of scripts, and I think it will be pretty difficult to extract the elements I need, as there is almost no documentation. Do you have sitting around somewhere, or know where I could fine, a script, or ever a guide to making just a simple login, with no extras? That would be super helpful! Thank you very much!

signup.php - Please help!!!
by Ravi Manda (mvrksravikumar69@yahoo.com) on 25 Jan 2003 3:29pm GMT

I am having trouble with signup.php My calls to $db->getmessge() fail, says undefined function. So I included (require_once)DB.php in signup.php. the error goes away, but when i submit details from login page, it doesnt get to the mySQL databaase. The member table is created. It seems it cant find the information in config.php to connect. I have tried including config.php. Didnt help. What can I do?? Please help!!!

Hey
by Kobra () on 2 Feb 2003 9:53pm GMT

There is no file html_form.php, all the files are blank when I view them... WHAT THE HELL?

rules!
by khn (fikfuk@hotmail.com) on 3 Feb 2003 2:01am GMT

hey bad site !! love it keep it up!

-----------------------------------

Simple login
by Sergio (svarga15@yahoo.com) on 3 Feb 2003 9:28pm GMT

I'm new to PHP, and I have a question: Is a simple cookie login(without session) secure? So my login checks the database for that username/password, than sets an encrypted cookie. I woul apreciate any remarks on this!

db.php
by marco (irmak@okulyillari.com) on 17 Feb 2003 3:41am GMT

where is db.php

How do I run a PHP login script
by MA (ma94117@hotmail.com) on 18 Feb 2003 12:00am GMT

I have an idea...and Ive heard of a few websites that allow to test, and run scripts.

Has anyone heard of this??

If so, any info would be greatly appreciated.

HELP!!!
by Andi (im_not_a_giraffe@hotmail.com) on 19 Feb 2003 3:03pm GMT

IM ABEGINNER AND KEEP TO GET THIS LOGIN SCRIPT WORKING BUT IM UNSURE WHICH FILES EACH BIT OF CODE GOES IN PLEASE WOLD SOMEONE EMAIL ME EXPLAINING, THANKS A LOT . KEEP UP GOOD WORK

help me!
by Antonio Fundone (xtra@interfree.it) on 7 Mar 2003 1:06pm GMT

Can you translate it in italian please?

I must modify it and insert other passwords and usernames! is it possible?

Best regards

Antonio Fundone

DB.php
by Jester (Jester@free2code.net) on 8 Mar 2003 8:16pm GMT

DB.php is a PEAR package, get the DB package from pear.php.net.

help
by fznetworks (dawg868@fznetworks.com) on 11 Mar 2003 6:35pm GMT

can someone just set up my login system for me and ill let you in on stuff you have never known

DB:connect stuck!
by keppy (keppy@lineone.net) on 25 Mar 2003 5:46pm GMT

i'm having problems at the $db = DB::connect($dsn); line. my script just won't move past it. i've checked all the parameters, etc... but no luck. ideas? tia

Thanks Martin
by ArrrDeee () on 26 Mar 2003 4:04am GMT

Martin- I really want to thank you for taking the time to do something so obviously helpful to others. Yours and the "Serve it Up" article from Mac World have helped me get a fast start. You're appreciated, dude.

how i get the nt login in php?
by karthik (karthikk_p@yahoo.com) on 26 Mar 2003 4:32am GMT

i don't know get nt login. so,pls,explain it

user details
by jennifer (jenniferbullfrog@cs.com) on 28 Mar 2003 2:45am GMT

how do i get the user details to work. i got the list but when i click on a username it says 404 or member not found. help!

I don't get it
by Beauford () on 28 Mar 2003 10:15pm GMT

For two weeks I have tried many scripts to get login/authentication to work on my site with no luck. This one appears not much different than the rest I have tried. The problem is first that I don't completely understand sessions and the second is trying to get these script to work on a pre-existing site without having to rewrite it. Is there a really good straight forward plain english tutorial out there somewhere that can explain sessions in a better manner than I have come accross?

There are A LOT easier Secure Login scripts...
by Mankiy (CoreyGHomie@aol.com) on 11 Apr 2003 2:14am GMT

There are a lot more easier secure login scripts then this one, at least that i know of......

I coded a decent one myself (never been cracked to this day that i know of...)

and it has been working decently well for me........

Uses a check.php on every pg to make sure no one trieds to access it if its logged in and such, but, thats jsut what i say.......

also, for the login script, use HTTP_POST_VARS[username]

It takes the username from the form and uses it.....

this can also work with a password if needed :P

What would be wrong with...?
by Jonathan () on 11 Apr 2003 6:20pm GMT

I am currently in the process of implementing this script, however I had one question.

This is what I normally do:

include a verify_session.php page in my page_header.php page which is included in every page.

After a successful login, I do this

$_SESSION['current_session'] = mktime().session_id();

header("admin/menu.php");

then in this verify_session.php page I have the following code

if($_SESSION['current_session'] != mktime().session_id();

header("login/login.php");

if ($_REQUEST['logout'] == "logout")

{

$_SESSION['current_session'] = NULL;

header("login/login.php");

}

and in the page_header.php file,there is a link which is as simple as

<a href="<? echo $_SERVER['PHP_SELF'] ?>?logout=logout">Logout</a>

What would be wrong with this?

In either case, I'm still implementing what I have found here

PEAR
by darwin (widjaja_darwin@yahoo.com) on 13 Apr 2003 11:26pm GMT

Hi, I've been testing the scripts and i got weird error. Suppose my mysql database is hosted at blah.com, then when i use native sql connect functions, i can go there easily with no error, but when i use your db_connect functions, i got error DB_ERROR NOT FOUND

anybody know what's wrong?

secured login
by Newbie () on 14 Apr 2003 2:43am GMT

i'm a complete newbie to linux, php & mysql.

i have a database set up in mysql.

i have a web page set up with a username box, a password box, and submit query button, i want a user to be able to input the info. hit query and it check whats input against my database to get to the next 'secured' page. it seems i have to have a 'code' in the page itself that lists my 'master' username & password in it to connect to the database before the query can take place? how is that secure? and how is it done using whats listed above?

Here's the code...
by V9TecAdmn () on 15 Apr 2003 1:37am GMT

Here's the code for connecting to your database, assuming you have PHP set up correctly and your database is on the same server (and don't worry, when you view it through a web browser, nobody can see the password):

$db = mysql_connect("localhost", "username", "password");

mysql_select_db("database_name",$db);

Re: Simple login with cookies
by martin on 15 Apr 2003 11:37am GMT

Sure it's safe as long as you check the info on every request, sessions depend on cookies after all so it's almost the same (although the data is on the server and doesn't fly on the wire).

secured login
by Newbie () on 15 Apr 2003 3:35pm GMT

Thanks for the info V9TecAdmin.

i'm still having alot of problems.

everything i pasted into my page from the code at top is printed out on the web page. (except master id & password)(which is visible if you view source on the page.)

I think my form is wrong too.

I have put a copy of it here. www.geocities.com/alucard2323/login.htm

please tell me how much is screwed up

geocities lol
by john () on 20 May 2003 4:45pm GMT

geocities doesnt support php m8

Nice tutorial...
by Kristoffer Nustad (babyorphan@scripting-network.net) on 22 May 2003 8:02am GMT

Nice tutorial...

I just skimmed through it though, and I stand corrected if you do this, but I usually store in a field of the members database the cookie set if you wanted to be remembered with the exact values, basically to check if the cookie has been tampered with.. then check on re-visit if it was tampered with, if tampered, die('hack attempt message') etc.. there's alot of things possible to do for a totally secure login, but as always.. nothing can ever get totally secure, but you can do your best to throw "hackers" off :)

It is a nice tutorial that surely will and probably has helped alot of people.

Keep it up :D

Read me please
by hendra (juhendra_regar@yahoo.com) on 9 Jun 2003 7:09am GMT

this is bad script

your script have much disadvantage!!!

QUESTION:register_global&session handling
by jun (junjun_290@emailaccount.com) on 10 Jun 2003 3:38am GMT

I have a login page where i register the username and password....but it seems that it is always null when i access it in other php files to check if the user has properly logged in......

what must be the problem... can anybody help regarding session handling with register_global turned off.

Thanks in advance.....

Thanks
by jun (junjun_290@emailaccount.com) on 10 Jun 2003 6:06am GMT

if you have answers to my question....please email i to me.... Thanks.

HELP!!!
by afroman (skatersebjb@aol.com) on 16 Jun 2003 6:06pm GMT

i don't know what to do in order to be able to get the scripts to work. in the angelfire pages i use, i enter it directly as shown, and all i get is those exact words all over the page.

umm
by ben (ben@ozepride.com) on 18 Jun 2003 10:36am GMT

u dont use it as html...

anywayz.. for a basic basic basic login page that cant be skipped or cheated by reading html, what would i have to do???

Nice but....
by Stu (stuart_lindley@hotmail.com) on 8 Jul 2003 9:24pm GMT

This is a great I idea for handling logins but my only porblem is the mess left in the database. At a guess the data stays in there until the user logs in again and it overwritten or somethin or would you just use CRON to clean up the expired sessions say once an hour or something?

trouble trouble...
by steve (steveyeago@yahoo.com) on 23 Jul 2003 1:30am GMT

"the examples provided will assume almost nothing to make it easier to read"

I agree that the script is very intelligible, I think that martin here assumes a little more about one's ability to structure the peices. I know a good amount, while still being a newbie, I will figure it out, but it will take a few hours... could have been avoided with a working script sample.

instructions
by fusion_dm on 31 Jul 2003 1:09am GMT

here are the instuctions for those who can't do it themselves (i've been doing php for a day now, too).

http://pear.php.net/package-info.php?package=PEAR

http://pear.php.net/package-info.php?package=DB

download the latest stable releases PEAR and DB from the php web site listed above and unpack them.

copy PEAR.php into your current directory. i moved the DB directory and DB.php into my current directory. Make sure you have you config setting correct. mine are:

$db_host = 'localhost';

$db_user = 'root';

$db_pass = '';

$db_name = 'mydb';

on my mandrake box. i used the commands:

mysqladmin -u root create mydb

mysql -u root mydb < mydb.dump

to create the db. as you can see in my config, that i specify mydb.

in global.php i made all the require_once paths to be my current directory.

my current directory is the apache document root.

"SetFetchMode undefined function error will occur when database connect fails." that means your password, username, or other config options are wrong.

hope this helps. enjoy!

How does remember me work?
by John () on 12 Aug 2003 9:22am GMT

Hi,

I'm also working on sessions right now.. and i dont really know how to make the remember me functions..

How do u do it?? What are the concepts behind it??

Do u create your own session ID's?

PEAR and DB and CONFIG
by Gonzo (glennfoster@emailaccount.com) on 14 Aug 2003 9:28am GMT

Yes, those missing files. No they are not missing (thanks to fusion_dm for pointing that out). Belive it or not I have been programming for a coupleof years but my hosting provider doesnt let me do a lot of things like this.

So, anyone know the answer to this question?

Apprently Pear is already installedon the server (which is shared with about 40 other sites) so Can I install it again in my own directory? I would ask my hosting provider but they are being gits at the moment.

classes
by Kev (kprice@emailplace.com) on 17 Sep 2003 1:09pm GMT

Hi, I'm not that new to PHP but I am new to classes and so can't get this script to work.

I can understand the flow of it and what it does. I just dont know how to include it in my pages and get it to verify the username and password as it is passed through the login page

checking the password by verifying it
by Anders Syvertsen (anderssyvertsen@hotmail.com) on 26 Sep 2003 11:53pm GMT

This is a little extension i wrote that requires the user to type his/hers password two times so theres no mistyping taking place!!

The following is in signup.php

$form->addRule('password', 'range:5:20',

'Enter your <strong>passeword</strong>, between 5 and 20 characters.');

$form->addRule('confirmpassword', 'range:5:20',

'Enter your <strong>passeword</strong>, between 5 and 20 characters.');

$form->addRule('password', 'equals:confirmpassword',

'Your <strong>two passwords</strong> did not match each other.');

And you add this to the if-clausul in the function valid() in html_form.php:

( (substr($rule['rule'],0,6) == 'equals') && ( !$this->fieldsMatch($value,substr($rule['rule'],7)) ) ) or

and in signup.php also add this method and youre done:

function fieldsMatch($value,$compareVarName)

{

$value2 = $this->getValue($compareVarName);

return $value == $value2;

}

Well, that was it. I can also try to explain a little.

the "new" rule i've added was (currenttextfield,'equals:fieldnametomatch',msg)

the fieldnametomatch is the textfield that you want the currenttextfield to be equal to.

password
by Dommert (jdommert@yahoo.com) on 27 Sep 2003 4:14pm GMT

How do you get the php to check the user name and password against the servers login/passwords ??? Is there a way to do that. If so could someoen email stuff about it

Ip check
by () on 27 Sep 2003 8:55pm GMT

Can someone plz explain the logic of the ip check to me.and explain in detail jus exactly how t works and how it prevents any illegal logisns

thanks guys

There are to many mistaken
by yudhi (cyudhisaputrapribadi@yahoo.com) on 8 Oct 2003 3:55am GMT

I dont know ho to fix it but tyhe script for php you are given in the web. Still have fails for example the index also login.php.Please send me the newest and the fixed new.If you want to publish script check the script are they urrently correct or not.ok then.

Good notes
by Kai (khairul@petisurat.com) on 14 Oct 2003 10:49am GMT

I think you have done a good job here in providing information and ideas . Keep it up man.

Tested and works fine.
by Wally (webmaster@nwrafters.com) on 20 Oct 2003 3:35am GMT

I modified the script you had and it works fine for me, good job! It can be viewed at: <a href="http://www.nwrafters.com>NW Rafters</a>.

Great Script
by Arif Harbott () on 20 Oct 2003 2:11pm GMT

I have been programming PHP for about a year now, and am really impressed with your tutorials. They have helped my development of understanding classes a lot and have given me a lot to think about.

Thanks

Leider nur ein Newb
by arnd572 (arnd572@hotmail.com) on 20 Oct 2003 7:41pm GMT

Hi leute, das tutorial selber fand ich sehr interessant. Leider habe ich nicht so sehr viel wissen über php. Das verzeichnis /user, ist doch bei jedem freewebspace anderst oder? Und bei mir kommt jedesmal folgender fehler: Fatal error: Call to undefined function: begin_html() in /data/members/free/tripod/de/e/f/a/efaspace/htdocs/index.php on line 4

Also ich versuchs trotzdem weiter, vielleicht schaff ichs ja irgendwann :-)

cu

??Need Help??
by Rick (vickers@hotpop.com) on 22 Oct 2003 7:36pm GMT

Hi,

"I am new to PHP, and told a company I can write this stuff, but they want it to work on a parallel-cpu architecture...can you re-write this.."

Martin...don't you get tired of these type of questions...tell 'em to go hire an engineer if they cannot figure out free code presented as an example. Thanks for the sample..Rick

??Need Help??
by Rick (vickers@hotpop.com) on 22 Oct 2003 7:44pm GMT

Hi,

"I am new to PHP, and told a company I can write this stuff, but they want it to work on a parallel-cpu architecture...can you re-write this.."

Martin...don't you get tired of these type of questions...tell 'em to go hire an engineer if they cannot figure out free code presented as an example. Thanks for the sample..Rick

With HTTPS :D
by WillemM (willem@mein-design.nl) on 29 Oct 2003 6:02pm GMT

The only thing I have to say is: your encryption is missing :) But for the rest it's perfect!

With HTTPS or SSL (which is the same?)

You can make this a very secure system.

Help
by Ian (thesimpsonsrulz@hotmail.com) on 1 Nov 2003 7:12pm GMT

Where does all the coding go on which page(s) and so on?

PHP Login scripts by Martin Tsachev
by Charles (cmorehead@houston.rr.com) on 5 Nov 2003 8:52pm GMT

Usually, when you publish a FAQ it also provieds the answers to the 'Frequently Asked Questions'. Since this is not a simple copy to any directory and it works app there should be some documentation somewhere with the setup requirements.

Session ID
by bboy () on 10 Nov 2003 7:18pm GMT

how about on host servers that changes your session id upon hitting refresh on your browser? it would log you out of a logged in page when you hit the refresh button.

IDIOTIC TWAT
by () on 20 Nov 2003 12:04pm GMT

WHY DELETE MY LAST MESSAGE TO YOU? CAN YOU NOT HANDLE A LITTLE >TRUTH< YOUR SCRIPT JUST CONFUSES MORE PEOPLE THAN IT DOES HELP THEM< DO US ALL A FAVOUR AND STOP POSTING CRAPPY SCRIPTS UNTIL YOU ARE ABLE TO WRITE ONES THAT WORK YOU TIT.

php logn scrpt
by dan zarrella (zan@stargeek.com) on 27 Nov 2003 8:22am GMT

this articles is great, but also check out my [http://www.stargeek.com/php_scripts.php?script=16&cat=misc::php login script], tell me what you think

What sets the cookie value?
by atteSmythe () on 30 Nov 2003 12:42am GMT

So, I finally got this script up and working in my own pages. Nifty! It required a couple tweaks (for example, needing to strip slashes from $cookie before unserializing it, depending on server settings), but all in all, it's very serviceable.

I've looked over and over and I still don't see what to do with the cookie field, though. We store the value in the cookie and in the database, but it never changes, and we never update the database with a new value. You mention at the top that it should be an md5 hash, but a hash of what?

Thanks a lot, hopin' the hear back from you.

New to php...need instruction
by sonny (knightstn2002@yahoo.com) on 4 Dec 2003 11:59am GMT

Hi Martin,

I'm also a newbie to php. Can you send me some detailed instruction on how to implement this login algo into my html. Thanks

ip will not work
by mike () on 4 Dec 2003 2:47pm GMT

retreiving the ip will not work

tried this in one of my own on a dhcp network on adsl - no go!

now using session id instead

I am now using session_id, used ip, stored in db with u/name & p/word to authenticate users & form to php submissions

ps. don't use cookies

my version of this program
by stargeek (zan@stargeek.com) on 11 Dec 2003 6:56am GMT

check out my version of this:

[http://www.stargeek.com/php_scripts.php?script=16&cat=misc::PHP Login Script]

Have you intentionally hidden some lines of codes?
by Harry (hshin21@yahoo.com) on 24 Dec 2003 5:31pm GMT

Have you intentionally hidden some lines of codes? I'm an experienced C++ programmer. It seems that you are hiding something and having people waste time.

To invoke begin_html(), global.php should be included. I cannot find global.php included anywhere.

begin_html is used in 9 files in your scripts.

Am I missing any information you have given?

This script really sucks.
by Harry (hshin21@yahoo.com) on 25 Dec 2003 10:10pm GMT

Folks, if you are not a well experienced oop programmer, don't try this script. It has too many bugs, and I suspect this guy, martin, intents to waste your time. Or, he is unbelievably irresponsible person.

I have more than ten years of experience in oop. I am struggling with this garbage-like script. Now it's almost done anyway. You will hardly succeed with this script unless you are not really good since this script really sucks.

I can't believe it
by Daniel () on 28 Dec 2003 11:40pm GMT

I really can't believe there's a lot of people like Harry or Vincent really wasting their time saying this script does not work. Don't you like it?...Then DON'T use it...If you can do it better...¿why do you come here to try to find YOUR job done? Shut up, please. Martin just wants to help (and it really does) By the way..."OOP programmer" ¿Where is your wonderful, fabulous, amazing and awesome php login script? Shut up, please...and try to use your OOP head often.

By the way...
by () on 28 Dec 2003 11:44pm GMT

Martin, Thanks for your work. Maybe this script could be enhanced (I supposed based upon comments), but it lets to get started on login topic. Thanks so much, and keep working.

Thank for all
by milionaru din galati (defe@de.de) on 29 Dec 2003 7:07pm GMT

nice work martin !

Bullet Proof!
by Jared (director@astro.org.nz) on 7 Jan 2004 9:34am GMT

Hey thanks Martin, this has given me some good ideas.

I am designing a highly critical system and need absolute security. I have a list of 'to dos' I have picked up from various tutorials and wonder if you have any to add/edit for near bullet proof security.

Thanks alot,

Jared.

www.astro.org.nz

...alliance without politics...

------------------------

GlobalNet Security:

- Using SSL communications.

- Use double encrypted MD5 session information.

- Session ID and Username in cookie for verifying in conjunction with session information

- Encrypting information once on the server - not sure how but will likely have to write own encryption script for URL's and documents.

- Plus all the checklist on http://www.onlamp.com/pub/a/php/2003/03/20/php_security.html

Basically, you name it, I will go away and learn and impliment it.

Thanks. Jared

Re: Bullet Proof!
by martin on 7 Jan 2004 11:29am GMT

What's that double encrypted md5? First of all md5 is a hash algo not an encyption, and it doesn't make any sense to use md5 on a md5 hash, it just uses more CPU and will give you a 1:1 from the source to destination hash.

Otherwise, the only thing to mention is if you use only SSL you should mark your cookies as secure so no secure data is passed to the non SSL site. You can also use 2 levels of security, one for plain HTTP and one for SSL'd if you have to support HTTP only for performance/other reasons.

RE: Bullet Proof
by Jared Broad (director@astro.org.nz) on 8 Jan 2004 4:36am GMT

Hi,

In one forum someone said that doing:

md5(md5($password)) would make it take much longer to crack by brute force method. Naiivity?

Thanks for the tip, have a look at ASTRO if curious. Is for GlobalNet:

http://www.astro.org.nz/index.php?pageid=1000

Jared

md5(md5($pass))
by Jared Broad (director@astro.org.nz) on 9 Jan 2004 8:39am GMT

Hey Looked it up and found the better way to use MD5 doubled

http://www.phpbuilder.com/board/showthread.php?threadid=10242570

function str_encode($str) {

$strMD5feed = sha1("y8Vyica9aspPHs9H9X6Z"); // random key added to md5

$str = base64_encode($str);

$str = str_rot13($str);

$str = bin2hex($str);

$str = md5($str + md5($strMD5feed + $str));

return $str;

}

Re: md5(md5($pass))
by martin on 9 Jan 2004 5:14pm GMT

Actually the algo strength doesn't seem to justify the CPU ticks needed for it. Better compile PHP with the crypto module in and look for what you need there.

If you use this anyway, you should obviously replace that + with . unless you want to get md5(0) all the time.

Error
by Dave Flynn () on 17 Feb 2004 9:06pm GMT

I think that is wrong!

Great
by Justin (rather@notsay.com) on 3 Mar 2004 9:04pm GMT

This is really cool, thanks for the hard word in the face of hatred. Keep it up, we appreciate it.

missing?
by Justin () on 4 Mar 2004 2:48am GMT

Is the User class missing a closing curly? }

thanks
by biyono sugianto (biyonos@yahoo.com) on 10 Mar 2004 7:45am GMT

thanks for your services

subject is 'thank you'
by dan () on 10 Mar 2004 5:27pm GMT

right.

i liked this last one. :-)

martin, just thanks !

need help HELP help HELP me plz.
by deepanshu mukherjee (deepanshu_mukherjee@yahoo.com) on 13 Mar 2004 12:10pm GMT

this is my login script in php but its not the complete i guess some additional features need to be add such as(A)check weather user is alredy login/not.(B)password crypt in this script

<?php

session_start();

$log = $_POST[loginid];

$pass = $_POST[password];

session_register($log);

session_register($pass);

session_register($logged_in);

if($_POST[what]=="")

{

echo "<table cellpadding='0' cellspaccing='0' width='30%' border='0' align='center' valign='center' bordercolor='black' bgcolor='#eff5fd'>

<form action='http://192.168.0.1/~deepanshu/test1.php' method='post'

<tr>

<tr>

<td align='center'>

<table cellpadding='0' cellspaccing='0' border='1' width='100%' bordercolor='black'>

<tr>

<td align='left'> login </td>

</tr>

<tr>

<td align='center'>

<table cellpadding='0' cellspaccing='0' border='0'>

<tr>

<td align='right'>login id &rarr;</td>

<td><input type='text' name='loginid' size='20' maxlength='25'></td>

</tr>

<tr>

<td align='right'>password &rarr;</td>

<td><input type='password' name='password' size='20' maxlength='25'></td>

<td><input type='hidden' name='what' value='checkdata'></td><br><br>

</tr>

<tr>

<td align='center' valign='bottom' colspan='2'><input type='submit' name='submit' value='submit'>

<input type='reset' name='reset'></td>

</tr>

<tr>

<td align='left'><a href='http://192.168.0.1/~deepanshu/test.php'>forgot password</a></td>

<td align='right'><a href='http://192.168.0.1/~deepanshu/index.php'>sign up now</a></td>

</tr>

</td>

</tr>

</form>

</table>";

}

else

{

$errormessage == "";

if(!$log || !$pass)

{

$errormessage .= "you have not fill your id/password<br>" ;

echo "<br><a href='http://192.168.0.1/~deepanshu/test1.php'>back</a>";

}

if($errormessage == "")

{

include("deep.php");

$query = "select login_id,password from user_profile where login_id = '$log' and password = '$pass'";

$result = mysql_query($query);

$row = mysql_fetch_array($result);

if(($row[login_id] != session_register($log)) && ($row[password] != session_register($pass)))

{

echo " Login failed! invalid id/password";

unset($log);

unset($pass);

session_destroy();

echo "<br><a href='http://192.168.0.1/~deepanshu/test1.php'>back</a>";

}

else

{

echo "login as $log";

echo "<br><a href='http://192.168.0.1/~deepanshu/index.php?assign=$log'><font color='black'>Modify Your Acount</font></a>";

}

}

else

{

echo $errormessage;

}

}

?>

New to the world of Web development
by Sarju () on 18 Mar 2004 2:23pm GMT

Hi,

I am planning for a new website which will allow user to sign up and then login.

I am hosting it on a server which has MySQL. Please let me know how can i take user data and put it in the table and later use the same for validating during login.

I am not sure if this is the right forum for it or not.

I am planning to develop the static pages using some tool available in the website

Any suggestion and pointers appreciated.

Thanks Sarju

"sniffing" am i missing something ?
by joe () on 25 Mar 2004 4:42am GMT

Hi Martin,

Solid explanation and good code; just wanted to say that up front after looking at some of these other comments. I do want to know how this secures logins against "sniffing" since it seems that the passwords are sent plaintext to the server.... or is the only way to encrypt on the client side to use SSL?

Sniffing
by martin on 27 Mar 2004 5:16pm GMT

Yes Joe, it's impossible to secure the login itself, but after that point the password itself or anything that would allow an attacker to discover the password (hash, etc.) is not sent over the network. The only exception is when changing the password, but otherwise an attacker would be able to change your password if he hijacks your session.

You are right though, the only way to have truely secure sessions is through SSL.

Cookie Field
by FD () on 29 Mar 2004 8:25am GMT

I noticed to people asked about this before but never got answered.

The cookie field is set when the user creates and account and when the user updates their password, apart from that is it not changed to my knowlege.

The cookie is updated every time the user logs in with the data "$values->cookie" This I presume is just whats in the cookie field when its created so it simply updates the cookie with the cookie data from the DB.

As to what is stored in the cookie field is the result of the function generateCookie(). Which just creates a random_unique id for the cookie.

Hope that answers any questions about that.

Its a good script Martin and thank you for sharing it with us. I think you should mention somewhere that the script is uncomplete in the sense that you don't just download it and run it. I see a lot of people are confused about this, to be honest I thought it was complete when downloading it but it didn't take long to figure it out ;)

Anyway thanks again, It has provided me with an insight into how I shall be coding a similar script.

P.S For all the people who haven't noticed this is a "Comments" board and not a "Request" board you should stop asking if this or that should be done for you, do it yourself ;) This is the very reason I do not release code anymore :(

Help!
by mittchel (mittchelhawk@hotmail.com) on 29 Mar 2004 5:05pm GMT

look guys i dont know ANYTHING about php can someone help me with the login stuff because i want it very much!

RE: Help!
by FD () on 31 Mar 2004 10:01am GMT

To use this script you need to at least some know PHP fact.

So the answer to your question is no we can't help you. Can you help you self though? Yes you can. Read some PHP tutorials. I did ;)

Update
by FD () on 31 Mar 2004 11:42am GMT

Well as I mentioned in the "Cookie Field" post. I said I would be using this script for an insight into how I might go about coding my own. Well I finished half of that yesterday and now its fully finished. Granted its very different to you code but the same principals apply like use of a cookie ID code, sessions and IP checking.

So thanks again Martin!

I have had another look at some of the comments left. Its a shame some people are like that. Im not calling them stupid for not being able to use the script but they are stupid for acting so immaturely. The fact is all who post such comment are probably around 16 or younger (no offense to any <16 posting here who ARE mature enough not to behave in such away).

I hope my words and the words of many others who have thanked you for such a helpfull script will outweigh all the negatives that immature people with poor understanding of PHP have left ;)

I think this script has a flaw !
by bonefry () on 7 Apr 2004 10:13pm GMT

something went wrong after trying this script, and after hours of debuging, I finnaly found out what happened.

this script just refused to login the user using cookie authentification. what is wrong ?

on my server, magic_quotes is on, so the cookie's restored valued had a \ in front of every quote. the result is that the function unserialize (which restores the cookie) doesn't work.

My solution is to explode - implode the string, but surely there has to be a better way. PLZ HELP !

plz
by plz (mustdesi1211@hotmail.com) on 8 Apr 2004 2:19am GMT

can u plz amke this esaier by tellin wat scripts should go on wat pages. i dont have a clue

Looks good
by Sam Coleman (webmaster@scattered-ashes.com) on 12 Apr 2004 10:42pm GMT

I visited this page months before, but never tested it.

I have read a small portion of the comments and find it amazing that 'advanced' programmers are posting saying how bad it is and that there is no encryption. I have been coding in PHP for roughly 6 months, the 1st language i have tried and examining exaple scripts like this really help you understand how to do things, and give you new ideas in which to accomplish things. The script may not be perfect, but it is a sample piece to get you going on coding PHP not a production piece (although i'm sure with a few changes it could well be).

Nice to see a bit a PEAR in there, it will give me a chance to test my setup.

Thanks for the script Martin, I will be looking at it in greater detail another day :)

--Renegade

Help
by Antoine (antoineyow@hotmail.com) on 13 Apr 2004 10:39pm GMT

Hi, I need to build a login systme that each user go to a different page because of the password the put in, please help if you can. Thank you

Step by step?
by Mariku (mariku@yuugiou.net) on 16 Apr 2004 12:48am GMT

Hey Martin, is there anywhere that I can find a step-by-step method to getting this working?

Poor docs and structure
by PvUtrix () on 19 Apr 2004 7:21pm GMT

The package is very poor and it takes time to get it to work... you have to move stuff around, edit code and generally waste time. The code is good, but the presentation is poor.

N00bs, don't bother...

looks good but...
by pete (noclip@home.com) on 5 May 2004 5:47pm GMT

I agree, it does lack presentation and polish, it looks like it may work well but I just don't have the time or patience. How about a full working version?

Really.
by pyriX () on 10 May 2004 6:49am GMT

Here he is, kind enough to offer a free .php login scipt, and the very first post is someone looking to bust him up about it.

Bloody hell, this reinstalls my faith in the human race...

SMTP problem
by Andrew (spy_charly@hotmail.com) on 26 May 2004 6:09pm GMT

hi martin, its a nice login as i was looking for, but i have some problems, when i register a user it appears two messages that tell me errors,(i ckecked yesterday, so i dont remember them exactly) and dont send the email, and i have to setup users manually, can u give me a hand, im a begginer in php

good work!!!

Tell me to use this files.
by eRIC (eric@manas.kg) on 27 May 2004 10:53am GMT

Sorry i'm new here. i downloaded them. i'm trying to understand them one by one.

it will be good if where file how to install them(use them? how to configure them). is there any file such this?

as i looked to code i understand that i have to create new folder to place there your files.

thanks.

freelance web designer http://pdesigner.net
by zaur (zaur@pdesigner.net) on 8 Jun 2004 1:30am GMT

http://pdesigner.net

<a href ="http://pdesigner.net">freelance web designer</a>

Great help
by Josh () on 9 Jun 2004 7:50am GMT

Martin:

Despite the clutter of angry little folks who seem to be in over (and under) their heads, I think you've done a fantastic job of explaining both the risks and some potential solutions for secure logins.

From one geek to another, thanks.

:-j

Hey look, it worked!
by Josh () on 9 Jun 2004 9:22am GMT

Martin:

So I just implemented this system on a client site, after some minor tweaking (in particular, there's no _logout() member function).

It works like a dream. Not bad considering I only spent about an hour of my time and... oh yeah, zero dollars.

Once again, nice work.

:-j

study php nd mysql
by andi (abah_brodin@yahoo.com) on 9 Jun 2004 10:20pm GMT

thank's give me explain

Thanks
by Bruce (bruce.bushby@wol.co.za) on 10 Jun 2004 10:51pm GMT

Howz that code !!!!

Martin, I owe you man! thanks!!

I've not got anything working yet, but your explanation and examples have made life a lot easier!!

So now I'll go away and copy that code and make it work for my shit!! Hope you don't mind!!

Later

good
by ice-breaker () on 17 Jun 2004 2:11pm GMT

respect,

yu've wrote a good login script! but i have got a question: does this script has got an protection against brute-force? and is the script seeing at the top the actually version or exists a nearer?

stuff
by hey (mal318@psu.edu) on 17 Jun 2004 6:44pm GMT

i have computer stuff, electronics, stereo's , cloths, furniture, and a lot of other things for sale at low low prices. even a 93 ford areostar that we will sell for 350 bucks. let me know mal318@Psu.edu

wowza
by Winsmith () on 20 Jun 2004 4:58pm GMT

Either I am stupid or you write very obfuscated code. It might be both, but I just cannot follow that script.

From what I understand it looks really sophisticated and it seems all possible attack vectors are covered up, but I'd really have appreciated some more explanations as to what exactly you are doing.

Secure Login Script
by The Wizzard () on 28 Jun 2004 11:19pm GMT

Martin, job well done. I have to hand it to you, it takes a lot of good will in a person to go as far with this as you have. Hats off to you.

This script, while simple and basic, is secure and easy to modify for a variety of uses. I myself use a modified version of it to allow users to login to the main areas of a website using the same login/password/authorities that were set when the user registered at that site's forum board (yabbse 1.5.5). I use the forum registration scripts to register new members, and modified the table/database to point to the existing forum database instead. The passwords and incrypted using the exact same method, which is the most important part of the process to make them compatible.

A moderate understanding of php and mysql is helpful, of course, but this is a simple and effective script that everyone should find useful.

brute force cracking
by Andrew () on 30 Jun 2004 4:00pm GMT

Why are you worried about a password being cracked by brute force? Do you have any idea how long that would take? The universe will be dead long before then..

Wow
by :-) () on 6 Jul 2004 8:55am GMT

is this korean it power?

Yes..
by lei (test@test.com) on 6 Jul 2004 9:07am GMT

It's wonderful korean power..

I.N.V.U

Just missss......
by KURAKI () on 6 Jul 2004 10:30am GMT

excuse him. or she.

sorry .
by korean () on 6 Jul 2004 12:11pm GMT

sorry... spam no ...

wow..

sorry .
by korean () on 6 Jul 2004 12:11pm GMT

sorry... spam no ...

wow..

Hello!
by cleuza (cleuzza@hotmail.com) on 1 Aug 2004 7:31pm GMT

Hello!

I stay hear because inthe site I meeting my friendy from dennmark:"hello Klaus! how arte you?"

cleuza from Brasil.

Persistant logins
by Gareth Morris () on 5 Aug 2004 9:44am GMT

Hi, just setting up a login based on this code on my site - it all works fine apart from the persistant logins part - I can't see any code anywhere that actually sets the cookie value in the database?

_checkLogin performs a SELECT on the database selecting the "cookie" field amongst others (which is empty initially!), this then calls _setSession and in turn updateCookie - but where does the value of "cookie" actually get set in the database so it can be used for persistant logins?

Am i missing something?

Thanks for a great script!

Thanks
by Gustavo (gustavo@seanpiolas.com.ar) on 13 Aug 2004 12:15pm GMT

Hola mundo!

Si alguien tiene alguna puta idea de como usar el mod_ntlm del Apache para validar un usuario usando el dominio NT de Windows, agradeceré que me envie la solución por mail.

Saludos y maten al ponja del orto ese.

AOL
by Henry (henry@hotmail.com) on 16 Aug 2004 6:53pm GMT

This script doesn't work with AOL clients - could it be the IP check part?

Error message(REQUEST_URI ) on index.php
by Toochukwu Onyemelukwe (opk22000@yahoo.com) on 28 Aug 2004 5:21pm GMT

Hello Martins, Lovely jod u're doing out here. I got your script and tried working aroun it. Please I get this error each time I load the index.php page:

Welcome to the login page. Notice: Undefined index: REQUEST_URI in e:\inetpub\wwwroot\user.php on line 234

This page is available only to registered members, you have to login first, if you haven't registered yet you can do that for free.

I have tried opening the signup.php and login.php pages directly which opens but takes no action when I click the submit button.

Please, help me out with any tutorial or documentation. I have a deadline to met.

Thanks,

SecurePHP
by Mark () on 30 Aug 2004 2:40pm GMT

There's a good site that offers some more information on creating secure login scripts and PHP security in general. Check it out: <a href="http://securephp.damonkohler.com/">SecurePHP</a>

sql injection
by anonymous () on 11 Sep 2004 1:15am GMT

hello

First of all, thanks for your guide which contains very important and sensitive information.

what makes your script secure against SQL injection attacks?

i'm newbie on php programming, so my question must be really stupid since it hasn't been made yet. Sorry in advance...

Thanks

Firefox issues
by Helz () on 11 Sep 2004 4:43am GMT

When you open a new tab in FireFox the same session_id() will be used, will it still use the same $_SESSION['username']? Because say an Admin logs on, $_SESSION will set the user name to Admin, and a regular use logs on setting the $_SESSION to user. The Admin's $_SESSION username is user now. I haven't tried this script, but will it prevent that?

markinch
by () on 19 Sep 2004 1:32pm GMT
comment about Creating a Secure PHP Login Script
by wanedan (wanedan@yahoo.com) on 26 Sep 2004 4:58pm GMT

can you give me solution about creating a Secure PHP Login Script more simple becouse your's is complexxx or give me code can run direct in my computer

thanks

question
by franches (rhodora232002@yahoo.co.uk) on 30 Sep 2004 2:21am GMT

i'm doing a login form. And I'm using PHP and MySQL. i'm a newbie and having difficulty looking for a login tutorials or script. do you have a login script in PHP and MySQL?

help with signin
by brit (Briton14@hotmail.com) on 7 Nov 2004 5:06pm GMT

Hello :)

I Was wondering if you could help me with a problem ive been having for a couple of moths?

See im in to html and am looking for a login or signup screen that they can accsess and set up there own account. i have microsoft frontpage 2003

P.S I love your fourm bored do you know where i can get some free cheap ones?

Thanks

-Briton Swiercinsky

Age 14

Texas

free cheap ones?
by Rob () on 10 Nov 2004 8:12pm GMT

what is a free cheap ones?

stuff
by Mike () on 24 Nov 2004 7:04pm GMT

"i dont want to do any work, you do it for me and ill do something for you that you dont give a crap about" lol.

hey people, learn it on your own. i dont understand a THING on how to access php with mySQL, dont understand anything but the basic function and purpose of sessions, dont understand how they work at all, yet im not gonna come here and ask someone to teach me a language or do my work for me.

this dude cant help everyone who is a noob to the language, dont overload him! we dont want ppl that are willing to help to just give up and quit cuz of the flood of requests do we? lol.

No Idea
by los (los@stylz.co.nz) on 30 Nov 2004 12:23am GMT

Hey dude... i have never made a website or done anything with computers. I play alot of online games (well only Counter-Strike) and im making a website!! go figure. Anyways i need a login script for my clan to have there accounts so ill read all this having no idea about it and let you know how i get on. lol.

itll be awesome if it works.

thanks man

Is it possible...
by Frederic (ulmo2003@hotmail.com) on 4 Dec 2004 8:15am GMT

Several questions from a newbie...

1. Would it be possible for whatever PHP/MySQL login script to use the Windows integrated authentication method (I have IIS 5)? My scripts all use the same MySQL user account. I know that this authetication method would not be recommended as many "outside" users just don't use MSIE or aren't set up to "hand-shake" with that type of authentication, but it would be used behingd closed doors, within an intranet... Thanks for your great script!!

A special note: for those who would prefer a full code without any outside classes or packages (as PEAR), I would humbly suggest to re-consider : as a computer scientist, of course it's more satisfactory (and maybe adaptive) to build up your own code libraries... But it could turn out to be counter-productive, especially when you are an independant consultant.

More-over, as a complete total definitive newbie regarding PHP and MySQL, your script permitted me to dig deeper into PHP and globally into the PHP/MySQL community. The result - in less than two weeks I've been able to:

1. fully intall MySQL and PHP with tight security

2. create an full-blown WebApp by assembling pieces of codes / classes / extensions from here and there (a Photo Catalog with Administrative interface, including all goodies you could ask for that: infinite categories, multi-categorization for one item, EFIX/IPCT, dynamic layout of tables given user preferences, grouping of pictures (like a shoping basket or a favorite list) for users, optional gateway to paypal (for one/several items or one/several groups of items selected by the user), etc...

YOU WERE THE FIRST SCRIPT I'VE IMPLEMENTED AND STUDIED (after some modifications), and doing so forced me to dig into classes and such...

I used to work with JavaScrip, some ASP, mostly ColdFusion (which is much better than ASP imho), Perl. NOW, PHP ROCKS (still, ColdFusion is much better in terms of security and developpment speed)!

One week... I'm still flabergasted to have discovered such a language, more over such a community. I WILL NEVER BE ABLE TO THANK YOU ENOUGH!!! :-))

Help
by Briton Swiercinsky (Briton14@hotmail.com) on 18 Dec 2004 7:14am GMT

Hey,

I never really got my question anwsered. ill i got was being made fun of.

If you decide to help im trying to get a forum bored and a login and user sign up i use microsoft front page 2000 and only know html

Request
by Mohd Faheen (faheem_4ever@yahoo.com) on 26 Dec 2004 4:37am GMT

Sir..

i want to break login page,please tell me how can i break the login page,its my humble request to you.

Your's Faithfully

Mohd Faheem

:'(
by joey101 () on 26 Dec 2004 6:29am GMT

I set the class all up just like I was suposed to and tried running it... and it said:

PHP Parse error: parse error, unexpected $ in /home/user/extreme_webmasters/projects/Bear-PHP-0.1/user.inc on line 102

and line so happens to be the end of the file :(

can any one help?

help
by Muhammad (waqas@mwaqas.com) on 3 Jan 2005 7:26am GMT

i need free online user login and pass form when in back end we define user name and pass and on front end user put that pass and login name then they reach on desire page, i want to do with out any data base so any body can give me hole code for help, reply me on my email add waqas@mwaqas.com

stupid
by up yo (scooby_1992@hotmail.com) on 3 Jan 2005 4:49pm GMT

every time i play FAMILY feud and i log in it never shows my score and its always higher than everyones. like one time i hade like 4800 and someone hade like 3oo0 and thyey still one. I just wanted to tell you that my high scores never show up so i wanted to tell that this enternet sucks

login script
by vikram (markiv421@yahoo.com) on 7 Jan 2005 5:11am GMT

hello martin...

i wonder if you still go through these posts, coz man, u hav helluva lotta patience. anyways...

first off i'd like to thank you for the script.. realli helped me understand some basics...

i hav implemented a login script at http://markiv.thefreebizhost.com/forum/forum.php

i store a cookie with the encrypted session info when the user logs in and check it against the session id stored in the database (mysql) when the user wants to post a message...

it doesn't work in all comps coz of some browser cookie settings... is there any way to bypass this... the trouble seems to be specific to IE...

and if there wuz som1 tryin to hack the site... is there som dumb thing ive overlooked that wuld make it a walk in the park for the hacker?

thanks

Need Help
by Chakri (ckruthiventi@krify.com) on 7 Jan 2005 10:48am GMT

Hi,

You created the script with sessions and cookies, but if i want to create a secure PHP Login Script with out using cookies, sessions. Then how can you manage the authentication through out the web site.

In the some cases browsers doen't allow to cookies. Then with out using cookies, sessions or with out storing the information in database how we can authinticate the user.

Regards,

Chakri.

Last comment
by () on 9 Jan 2005 11:45pm GMT

Thanks - that last comment helped me finish building my radio controlled helicopter

unsecure
by john () on 11 Jan 2005 11:05pm GMT

why the fuck would someone go to all the trouble of

Users with shell access to the web server can scan valid session id's if the default /tmp directory is used to store the session data.

Somebody who has a site (on a shared host with you) can generate valid session for your site.

Somebody may sniff network traffic and catch the cookie.

If all they have to do is wait for a user to submit the form and then look at the username and password in the packet that was sent?

Holy
by () on 12 Jan 2005 2:32am GMT

man I dont know but it works fine for me. Thanks a lot for this cool script I use it on many sites now, and it works with SSL too!!!! Very secure in my opinion.

Login.php brining up error
by Gatesie on 27 Jan 2005 10:17pm GMT

Hello Martin

My server is picking up an error on line 9 of login.php. for some reason it does not like this line.

$form = new Form(uri_self());

Any idea

Login.php brining up error
by Gatesie on 27 Jan 2005 10:22pm GMT

Sorry I forgot the error message...

Fatal error: Call to undefined function: uri_self() in /home/*/public_html/login.php on line 9

the code
by () on 27 Jan 2005 10:54pm GMT

firstly i cant believe the comments, some people have no idea.

to me it appears to be some ideas slapped together, incomplete code to give people some insight. it's not complete code and imo should not be used at all - write your own script from scratch!

finally this script does have some terrible flaws, and i think it should have been mentioned that it is almost entirely untested and incomplete code.

people should read independant session and cookie tutorials. and cookies are most certainly not needed without the persistant connections and auto-login type features.

Taking the credit for another persons work ?
by curious dude. (nomail@thisaddress.please) on 29 Jan 2005 3:09pm GMT

http://www.devshed.com/c/a/PHP/Creating-a-Secure-PHP-Login-Script/

Not knocking this tute, but I spotted it at the above URL, and wondered, if they copied you, or you copied them, or both are your work ?

Another guy?
by martin on 30 Jan 2005 12:51pm GMT

Have you noticed that the article on DevShed says Contributed by Martin Tsachev?