Skip to page content or skip to Accesskey List.
Search evolt.org
evolt.org login: or register

Work

Main Page Content

Creating a Login Script with PHP 4, Part II

Rated 4.38 (Ratings: 17) (Add your rating)

Log in to add a comment
(79 comments so far)

Want more?

 
Picture of jesteruk

Jester uk

Member info | Full bio

User since: December 22, 2001

Last login: December 22, 2001

Articles written: 6

There was a fair bit of interest in my previous article which showed you how to create a crude login script included in each document. This article is an update offering better coding, a user database, sign-up script, login/logout scripts and a little script we will use to check a user's login status. Let's get started.

Notes

There are a few things you should know before you attempt to use this script. The next release of PHP will have register_globals set to Off by default. You're encouraged to write your scripts with this in mind, in this article we won't be using normal variables, we will be using $_POST, $_GET... etc.

We will also be using sessions with PHP, if you don't understand sessions, or don't know what they are it would be a good idea to read the page so you can understand the coding, and edit it to your needs.

I will be using the PEAR::DB classes to access the database, so you can easily make the scripts work with whatever database you are using. If you are unfamiliar with PEAR::DB read this great article: Abstract PHP's database code with PEAR::DB.

With this in mind, I recommend using a .htaccess file (if you use apache) to set some PHP values, use the following, if relevant.

php_value register_globals Off
php_value track_vars On
php_value arg_separator.output "&"
php_value arg_separator.input "&"

Planning

We want a system that will allow a user to 'login', preserve that user's login data across multiple requests, allow them access to certain areas only when they are logged in, and allow them to be able to logout. So let's think logically, what do we need?

  • User database, containing their password, username, and some personal information to create a community feel.
  • Allow them to 'sign up' if they aren't a member.
  • A method of checking whether or not the user is 'logged in.'
  • Allow them to 'log in' if they're not.
  • Allow them to 'log out' when they are done.

Now we need to turn that logic into code, so let us continue....

User database

We need a place to store user information. We need to be able to extract this data to authenticate them and insert new data for new members. This article will use an SQL database for this. We need to design the user database, but first of all we need to connect to the database.

Connecting

We are using the PEAR::DB classes for more portable database coding, rather than using database-specific functions.

<?php
require_once 'DB.php';	//require the PEAR::DB classes.

$db_engine = 'mysql';
$db_user = 'jester';
$db_pass = 'password';
$db_host = 'localhost';
$db_name = 'database';

$datasource = $db_engine.'://'.$db_user.':'.$db_pass.'@'.$db_host.'/'.$db_name;

$db_object = DB::connect($datasource, TRUE);
/* assign database object in $db_object, if the connection fails $db_object will contain
the error message. */

if(DB::isError($db_object)) {
	die($db_object->getMessage());	// If $db_object contains an error print out the
}							// error and exit.

$db_object->setFetchMode(DB_FETCHMODE_ASSOC);

include('check_login.php'); // we write this later on, ignore for now.
?>

There we have it, that script will create a connection object which we can use in other scripts to do stuff with the database. This script should be put outside your document tree, or in a protected directory to prevent people accessing it directly. There are various things you need to customise.

  • $db_engine - Your database engine, a list of possible values is below.
  • $db_user - Your username to access the database.
  • $db_pass - Your password.
  • $db_host - The host of the database server.
  • $db_name - The name of the database to connect to.

A list of possible database engine values are:

mysql -&gt; MySQL<br>
pgsql -&gt; PostgreSQL<br>
ibase -&gt; InterBase<br>
msql -&gt; Mini SQL<br>
mssql -&gt; Microsoft SQL Server<br>
oci8 -&gt; Oracle 7/8/8i<br>
odbc -&gt; ODBC (Open Database Connectivity)<br>
sybase -&gt; SyBase<br>
ifx -&gt; Informix<br>
fbsql -&gt; FrontBase

So now we have our connection to the database, save this file as db_connect.php. Next we need to design the database, I am providing a script that will create this table for you.

Our Table

<?php
require('db_connect.php');	// require above script, change the path to match wherever you put it.

$table = "CREATE TABLE users (
id int(10) DEFAULT '0' NOT NULL auto_increment, 
username varchar(40),
password varchar(50), 
regdate varchar(20),
email varchar(100),
website varchar(150),
location varchar(150),
show_email int(2) DEFAULT '0',
last_login varchar(20),
PRIMARY KEY(id))";

$create = $db_object->query($table);	// perform query

if(DB::isError($create)) {
	die($create->getMessage());	// check is query was successful
}						// if not error and exit.
else{
	echo 'Table created successfully.';
}
$db_object->disconnect();
?>

That script will create a table in the database you specified, once you have executed this script you can take it out of your document tree so others cannot run it. We will use this table to store user information, retrieve it and check it. Now we need to allow users to become members.

Allow Them To 'Sign Up'

A user database is no good unless we have users in it, so we need to allow users to add themselves, we use a simple form to allow them to pick a username, password, enter their e-mail address and any other information they choose, and then insert this data into the database.

<?php
require('db_connect.php');	// database connect script.

?>
<html>
<head>
<title>Register an Account</title>
</head>
<body>
<?php
if(isset($_POST['submit'])) { // if form has been submitted
	/* check they filled in what they supposed to, passwords matched, username
	isn't already taken, etc. */
	if(!$_POST['uname'] | !$_POST['passwd'] | !$_POST['passwd_again'] | !$_POST['email']) {
		die('You didn\'t fill in a required field.');
	}
	// check if username exists in database.
	if(!get_magic_quotes_gpc()) {
		$_POST['uname'] = addslashes($_POST['uname']);
	}
	$name_check = $db_object->query("SELECT username FROM users WHERE username = '".$_POST['uname']."'");
	if(DB::isError($name_check)) {
		die($name_check->getMessage());
	}
	$name_checkk = $name_check->numRows();

	if($name_checkk != 0) {
		die('Sorry, the username: '.$_POST['uname'].' is already taken, please pick another one.');
	}
	// check passwords match
	if($_POST['passwd'] != $_POST['passwd_again']) {
		die('Sorry your password and confirmation password did not match, please try again.');
	}
	// check e-mail format
	if(!preg_match("/.*\@.*\..*/", $_POST['email']) | preg_match("/(\)/", $_POST['email'])) {
		die('Sorry the e-mail address you submitted was of invalid format.');
	}
	// no HTML tags in username, website, location, password
	if(preg_match("/(\)/", $_POST['uname']) | preg_match("/(\)/", $_POST['passwd']) | preg_match("/(\)/", $_POST['website']) | preg_match("/(\)/", $_POST['location'])) {
		die('Invalid input, no HTML tags are allowed.');
	}
	// check show_email data
	if($_POST['show_email'] != 0 & $_POST['show_email'] != 1) {
		die('Nope.');
	}
	/* the rest of the information is optional, the only thing we need to check is if they
	submitted a website, and if so, check the format is ok. */
	if($_POST['website'] != '' & !preg_match("/^(http|ftp):\/\//", $_POST['website'])) {
		$_POST['website'] = 'http://'.$_POST['website'];
	}
	// now we can add them to the database.
	// encrypt password
	$_POST['passwd'] = md5($_POST['passwd']);
	if(!get_magic_quotes_gpc()) {
		$_POST['passwd'] = addslashes($_POST['passwd']);
		$_POST['email'] = addslashes($_POST['email']);
		$_POST['website'] = addslashes($_POST['website']);
		$_POST['location'] = addslashes($_POST['location']);
	}
	$regdate = date('m d, Y');
	$insert = "INSERT INTO users (username, password, regdate, email, website, location, show_email, last_login) VALUES ('".$_POST['uname']."', '".$_POST['passwd']."', '$regdate', '".$_POST['email']."', '".$_POST['website']."', '".$_POST['location']."', '".$_POST['show_email']."', 'Never')";
	$add_member = $db_object->query($insert);
	if(DB::isError($add_member)) {
		die($add_member->getMessage());
	}
	$db_object->disconnect();
?>
<h1>Registered</h1>
<p>Thank you, your information has been added to the database, you may now <a href="login.php" title="Login">log in</a>.</p>
<?php
}
else {	// if form hasn't been submitted
?>
<h1>Register</h1>
<form action="<?=$HTTP_SERVER_VARS['PHP_SELF']?>" method="post">
<table align="center" border="1" cellspacing="0" cellpadding="3">
<tr><td>Username*:</td><td><input type="text" name="uname" maxlength="40"></td></tr>
<tr><td>Password*:</td><td><input type="password" name="passwd" maxlength="50"></td></tr>
<tr><td>Confirm Password*:</td><td><input type="password" name="passwd_again" maxlength="50"></td></tr>
<tr><td>E-Mail*:</td><td><input type="text" name="email" maxlength="100"></td></tr>
<tr><td>Website:</td><td><input type="text" name="website" maxlength="150"></td></tr>
<tr><td>Location</td><td><input type="text" name="location" maxlength="150"></td></tr>
<tr><td>Show E-Mail?</td><td><select name="show_email"><option value="1" selected="selected">Yes</option><option value="0">No</option></select></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="submit" value="Sign Up"></td></tr>
</table>
</form>
<?php
}
?>
</body>
</html>

The above script allows the user to register an account, inserting their data into the database, we must perform various checks before we allow this. Checking if the username has been taken, if their passwords matched, and a few security checks. We also encrypt the password in the database for extra security. If all checks are okay we insert the data. Now the user is in the database, we still have to allow them to login, but first we need to write the script that will check if they are logged in or not.

Check if they are logged in

This script will assign a variable, $logged_in to either 1 (if they are logged in), or 0 if they aren't. We can then use this variable in our scripts. A few points:

  • We are going to use $_SESSION['username'] for our user's username and $_SESSION['password'] for their password.
  • $_SESSION['password'] will be encrypted.
  • We need to start our session somewhere, here is a good place.
<?php
/* check login script, included in db_connect.php. */

session_start();

if(!isset($_SESSION['username']) | !isset($_SESSION['password'])) {
	$logged_in = 0;
	return;
}
else {
// remember, $_SESSION['password'] will be encrypted.

if(!get_magic_quotes_gpc()) {
	$_SESSION['username'] = addslashes($_SESSION['username']);
}
// addslashes to session username before using in a query.

$pass = $db_object->query("SELECT password FROM users WHERE username = '".$_SESSION['username']."'");
if(DB::isError($pass)) {
	$logged_in = 0;
	unset($_SESSION['username']);
	unset($_SESSION['password']); // kill incorrect session variables.
}
$db_pass = $pass->fetchRow();
// now we have encrypted pass from DB in $db_pass['password'], stripslashes() just incase:

$db_pass['password'] = stripslashes($db_pass['password']);
$_SESSION['password'] = stripslashes($_SESSION['password']);
//compare:

if($_SESSION['password'] == $db_pass['password']) { // valid password for username
	$logged_in = 1; // they have correct info in session variables.
}
else {
	$logged_in = 0;
	unset($_SESSION['username']);
	unset($_SESSION['password']); // kill incorrect session variables.
}
}
// clean up
unset($db_pass['password']);
$_SESSION['username'] = stripslashes($_SESSION['username']);
?>

What we did here was:

If session variables aren't set, they're not logged in. If they are set, fetch the password row from the database where the username is equal to the session variable username. If password cannot be fetched, the username mustn't exist, kill bad session variables. If the password is fetched, username is correct, compare the encrypted password from the database to the session variable password, if it matches log them in, if not the password is incorrect. Don't set them as logged in and kill bad session variables.

So now we have our database connection, users can register accounts, we are capable of checking whether they are logged in or not. We can use $logged_in in our scripts now. All that is left is to allow users to log in and log out.

Allow them to 'log in'

Now we need to create the script that will allow the user to submit their username and password, check if they are correct and, if so, register them as session variables. Once we register the session variables the user will be deemed as "logged in", $logged_in will be true until they 'log out.'

<?php
require('db_connect.php');	// database connect script.
if($logged_in == 1) {
	die('You are already logged in, '.$_SESSION['username'].'.');
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<?php
if(isset($_POST['submit'])) { // if form has been submitted
	/* check they filled in what they were supposed to and authenticate */
	if(!$_POST['uname'] | !$_POST['passwd']) {
		die('You didn\'t fill in a required field.');
	}
	// authenticate.
	if(!get_magic_quotes_gpc()) {
		$_POST['uname'] = addslashes($_POST['uname']);
	}
	$check = $db_object->query("SELECT username, password FROM users WHERE username = '".$_POST['uname']."'");
	if(DB::isError($check)) {
		die('That username doesn\'t exist in our database.');
	}
	$info = $check->fetchRow();
	// check passwords match
	$_POST['passwd'] = stripslashes($_POST['passwd']);
	$info['password'] = stripslashes($info['password']);
	$_POST['passwd'] = md5($_POST['passwd']);
	if($_POST['passwd'] != $info['password']) {
		die('Incorrect password, please try again.');
	}

	// if we get here username and password are correct, register session variables and set
	// last login time.
	$date = date('m d, Y');
	$update_login = $db_object->query("UPDATE users SET last_login = '$date' WHERE username = '".$_POST['uname']."'");
	$_POST['uname'] = stripslashes($_POST['uname']);
	$_SESSION['username'] = $_POST['uname'];
	$_SESSION['password'] = $_POST['passwd'];
	$db_object->disconnect();
?>
<h1>Logged in</h1>
<p>Welcome back <?=$_SESSION['username']?>, you are logged in.</p>
<?php
}
else {	// if form hasn't been submitted
?>
<h1>Login</h1>
<form action="<?=$HTTP_SERVER_VARS['PHP_SELF']?>" method="post">
<table align="center" border="1" cellspacing="0" cellpadding="3">
<tr><td>Username:</td><td><input type="text" name="uname" maxlength="40"></td></tr>
<tr><td>Password:</td><td><input type="password" name="passwd" maxlength="50"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="submit" value="Login"></td></tr>
</table>
</form>
<?php
}
?>
</body>
</html>

Now we have our 'log in' script. When the user loads this page they are presented with a form that allows them to submit their username and password. We then check if thatsuers is in the database, if it is we take the password associated with that username and compare it with the user's submitted password, if they match the user submitted the correct information. We can register the username and password (encrypted) as session variables. Now these session variables will be subject to inspection by the check_login.php script, authenticating the user each time a page is loaded, allowing us to use our $logged_in variable to check for a correct log in. When the user has done, it's a good idea to allow them to "log out".

Allow them to 'log out'

To log a user out we simply destroy their session variables and their session.

<?php
require('db_connect.php');	// database connect script.
if($logged_in == 0) {
	die('You are not logged in so you cannot log out.');
}

unset($_SESSION['username']);
unset($_SESSION['password']); // kill session variables
$_SESSION = array(); // reset session array
session_destroy();   // destroy session.
header('Location: index.php'); // redirect them to anywhere you like.
?>

That script is very simple, once the session variables are unset the check_login.php script will set $logged_in to zero, so they will not be classed as "logged in".

Usage

Now we have the base of a login system, so let's look at a practical usage of these scripts. A page would look like so:

<?php
require('db_connect.php');	// require our database connection
					// which also contains the check_login.php
					// script. We have $logged_in for use.

if($logged_in == 0) {
	die('Sorry you are not logged in, this area is restricted to registered members. Click here to log in.');
}

// show content

$db_object->disconnect(); // when you are done.
?>

This makes it very easy to restrict access to a document, only a person whose information has been authenticated by check_login.php will be able to view the page, the others will be offered a link to 'log in.'

More...

There are various ways we can jazz up this little member system, such as a user online script, a member list, member profiles, instant message system... the list goes on and on. This is the bear minumum, it's up to you to edit it to your needs, if you need any help use the comments system below and someone will answer.

We can use $_SESSION['username'] to interact with the database row associated with the current logged in user, $logged_in to check for a positive login, we can do just about anything now. We could do this:

<?php
require('db_connect.php');

if($logged_in == 1) {
	echo 'Logged in as '.$_SESSION['username'].', logout';
}
else {
	echo 'Not logged in. Login';
}

?>

Showing the user what name they are logged in as and offering a link to logout, while they are logged in, or telling them they aren't logged in and offering them a link to do so, if they're not logged in.

The list really is endless, I cannot really include more, this article is long enough, if you would like to see a how-to on a few things you can do with this, leave a comment below, if there is enough interest I will find the time to write it.

Conclusion

Remember this script isn't ready-to-go, you will need to do some editing. The layout of each page leaves a lot to be desired, jazz them up, you can add more to the user table, create different user levels so members have different access rights depending on their rank -- be creative. Just rememeber to include the db_connect.php script in any document that is part of the member system.

Here are a few links that may help you get to grips with the features discussed in this article.

These scripts have been tested and worked fine for me, if you have any problems feel free to comment, certain databases may require the system to be edited slightly. This article is somewhat discursive, if anyone is confused by my rambling feel free to drop me an e-mail and I'll be happy to elaborate on the areas in which you are having difficulties.

-Jester (contact)

I just like messing around with web design stuff, just a hobby.

Particularly perl, PHP and SQL.

http://www.free2code.net/

Darn it

Submitted by jesteruk on May 20, 2002 - 05:30.

I apologise for the &lt;?=$var?&gt; type output in the script, it isn't very portable for an article but I type it by instinct, there are only three occurances of it, so you should find it easy to change them to &lt;?php echo $var; ?&gt; should you desire.

login or register to post comments

note on validation

Submitted by Martin Tsachev on May 21, 2002 - 11:52.

The validation method is quite rude, you just display the first error and then die. The best method is to show all errors and have the form displayed with the submitted values filled in already.

login or register to post comments

Yes

Submitted by jesteruk on May 21, 2002 - 13:38.

This is just an article Shaggy, it isn't a ready-to-go script -- as I stated. It is short and simple, to give people ideas, introduce them to new concepts. If you'd prefer a different validation method, modify it. I try to keep my scripts as simple as possible for an article, getting too deep into it and writing a huge code bores the reader and they leave.

Good point though, maybe it will help someone.

login or register to post comments

help?

Submitted by davidjaymz on May 23, 2002 - 05:13.

hi. I followed the above tutorial and changed the reg script to use a mysql table that I already had. The script will stop if I fill in info that is already in the table or is incorrect format. But if i enter the form correctly and submit it comes back with "DB:error already exists" Does anyone have any ideas how I can fix this or what is actually causing the problem... Thanx in advance DavidJaymz

login or register to post comments

Re: help

Submitted by Martin Tsachev on May 23, 2002 - 11:04.

Already exists means that you are trying to insert a row with a value that already exists but is defined as unique. Display the query along with the error that will help.

login or register to post comments

Yes

Submitted by jesteruk on May 23, 2002 - 14:58.

What database are you using? I only ever use MySQL, so maybe shaggy can answer this, do all databases support auto incrementing fields?

login or register to post comments

Also

Submitted by jesteruk on May 23, 2002 - 15:00.

Does your database use auto incrementing fields? If not you will have to edit the scripts to compensate for this. Which is why I said this: "certain databases may require the system to be edited slightly".

login or register to post comments

Thanx 4 the help

Submitted by davidjaymz on May 23, 2002 - 15:24.

I'm using mysql... How do I get to display the query when I run the script so i can see which value already exists... DavidJaymz

login or register to post comments

uh

Submitted by Martin Tsachev on May 23, 2002 - 15:57.

Change for example:

die($name_check->getMessage());

to:

die('Query: ' .$sql . ' ' . $name_check->getMessage());

but you'll have to assign the query to $sql before executing it. It's also a good practice to always do that.

login or register to post comments

hmmmm

Submitted by jesteruk on May 23, 2002 - 17:21.

The table that you are using in place of the one i did, is the "id" field auto incrementing? if not set it do so, it makes things easier, it has advantages and disadvantages like everything else. If you don't, you will need to alter the script.

login or register to post comments

Database caveats

Submitted by bobince on May 26, 2002 - 10:13.

You've got a few common but little-known problems with your sign-up script. This comes from treating your database as a 'perfect' store for a string. Which actually it isn't.

Firstly and most trivially, there's the forty-character username limit. If a user can supply a longer username it will be accepted, but the wrong (cropped) information will go into the database. They won't be able to log on, and it will be possible to create 'duplicate' user entries, which is likely to confuse any scripts using the database.

Secondly, MySQL VARCHAR fields have all spaces trimmed from the end. So if your user is called "admin" I can create a duplicate user by supplying a username "admin ". Depending on what order MySQL decides to return the rows in, this could either just confuse scripts again and make me unable to login, or it might allow me to usurp the admin account.

This space-stripping behaviour, along with the default case insensitivity of matching in MySQL, is annoying and not compliant to the SQL standard. You can avoid case-sensitivity problems at least by declaring columns to be BINARY. IIRC the only way to avoid the stripping was to use a BLOB, which isn't good. Alternatively you could just disallow usernames with spaces on the end.

BTW, what's with all the addslashing into _POST? Writing to _POST seems a dubious strategy in any case, but here, where you are then having to remove the slashes again on exit, it's very odd. Why not just do it on the fly, eg. "WHERE username = '".addslashes($_POST['uname'])."'"?

Doing the same with htmlspecialchars on text output would also mean you wouldn't have to disallow '<' and '>' in strings. (If you're disallowing you'll also want to block the ampersand, to stop users masquerading as each other by using an HTML-encoded version of a letter.

login or register to post comments

Thanks...

Submitted by jesteruk on May 30, 2002 - 15:40.

..for the tips, but you obviously didn't read this line:

Remember this script isn't ready-to-go, you will need to do some editing

It's intended as an introduction, not a bullet-proof members system. It was the theory and mechanics I was trying to introduce, let's not quibble over semantics.

Yet... good points you made, thanks for commenting.

-J

login or register to post comments

One more point...

Submitted by jesteruk on May 30, 2002 - 15:50.

What if someone using this script has "magic quotes" on?

'".addslashes($_POST['uname'])."'"

Would just add slashes to an already slashed array item, that is why I did it the long way, if you're writing for yourself you know the status of magic quotes, trying to write for anyone and everyone is a different matter. I could have stripslashed them first to make sure, but then, TMTOWTDI. Also I could have forced magic quotes off, but I was trying to keep it relativleyt simple, the security leaves some to be desired, but I hope I got the basic concepts across.

login or register to post comments

Re: magic quote

Submitted by Martin Tsachev on May 31, 2002 - 05:59.

That's why people have made $db->quote, where $db is a pointer to a PEAR::DB database connection.

login or register to post comments

DB Error: no database selected

Submitted by CHAOSiTEC on June 5, 2002 - 07:46.

im quite new to this, actually this is my first time playing with php...

i saved the scripts and edited the db_connect.php like the following:

$db_engine = 'mysql';
$db_user = 'users'; // username for that db is users
$db_pass = 'users'; // same goes for password
$db_host = 'localhost';
$db_name = 'users'; // the db is called users

and i tried to create the tables, but with no luck all i got was 'DB Error: no database selected' i have created the database, and the username and password but i cant seem to be able to get to create the table... so i created them by hand, and when i then try the login.php script, i get the same... what have i missed??
CHAOSiTEC

login or register to post comments

hmmmmmm

Submitted by jesteruk on June 8, 2002 - 10:58.

The only time I have gotten that error is when I've written a script and forgot to include db_connect.php, so it's got no database connection. I don't know why you'd get that error, the scripts worked fine for me. (ponders)

login or register to post comments

DB Error

Submitted by DJ747 on June 22, 2002 - 08:54.

Hi I read your artical and did everything it said but It tells me: Fatal error: Undefined class name 'db' in (my web directory) on line 12. below is line 12 i don't know what to do with it.


$db_object = DB::connect($datasource, TRUE);

If someone can help me please e-mail me Click Here
I'm not good with php I just started learning last week.

login or register to post comments

Re: DB Error

Submitted by Martin Tsachev on June 23, 2002 - 10:43.

You forgot to do require_once 'DB.php' in the include file which connects you to the database.

See the second textarea - first line ;-))

login or register to post comments

a little off topic

Submitted by chowmein858 on July 27, 2002 - 04:18.

Thanks for the help jesteruk. With your article I was able to write a login script.

I just needed advice on one last thing though. I was wondering if more than one person try to modify the same DB table (i.e. creating a membership), would this cause errors using the example in the article? Cause after reading parts of the MYSQL manual I am getting the impression that if certain things arent' specified about the table or query errorrs may accur. I'm still new to this so I maybe wrong.

login or register to post comments

Re: concurency

Submitted by Martin Tsachev on July 27, 2002 - 17:44.

MySQL should be able to deal with a lot of simultaneous queries against the database, you should worry about that if you use plain files instead of a database.

login or register to post comments

!HELP!

Submitted by Koburoshi on July 29, 2002 - 08:58.

Hi I have very little experience with php, but that is not the point. everything was going peachy till it came to DB.php I figures since you didn't say I needed to create it that is was just there since I had php version 4.2.1. When I didn't create it I got error messages so I created a DB.php (do I need to put any coding inside of there) I got no error. Then I came to db_connect.php and I got this error: Fatal error: Undefined class name 'db' in (my web directory) on line 12. below is line 12 i don't know what to do with it. $db_object = DB::connect($datasource, TRUE); then on the next line: /* assign database object in $db_object, if the connection fails $db_object will contain the error message. */ I dunno what the object is to assign, is that my problem? Oh yes I noticed someone asked this question before and you said You forgot to do require_once 'DB.php' in the include file which connects you to the database. I copied the script exactly so require_once 'DB.php' is at the top. So eh please help me! Thanks!

login or register to post comments

Re: DB.php

Submitted by Martin Tsachev on July 29, 2002 - 19:48.

Koburoshi DB.php is a part of PEAR - the standard PHP library, either ask your administrartor to add the path to PEAR in PHP's include_path or if it's you add it yourself.

On Unix systems the default is /usr/local/lib/php, I don't know anything about Windows, sorry. If you can't find it you can download separate packages from the PEAR website.

login or register to post comments

Remembering Login?

Submitted by cassius on August 22, 2002 - 02:30.

How would you intergrate a cookie to remember a login?

login or register to post comments

Re: Remembering Login?

Submitted by Martin Tsachev on August 22, 2002 - 05:35.

Add a field in the database that keeps the cookie, never use the password itself.

Send a cookie with the username and the database cookie field to the visitor, check it when he comes back.

login or register to post comments

Question

Submitted by grissom3588 on August 23, 2002 - 20:06.

I learn scripts by seeing which parts of a READY TO GO script do what by comments and.... is there anyone who can get me a login script for mysql?? I'm trying to start my own game. I keep getting an error with this code Warning :Unexpected parse code $ on line 93 but I have no idea what is wrong with it. My aim is Grissom3588, my msn is Grissom3588@hotmail.com, my yahoo is Grissom3588@yahoo.com. Please help me!

login or register to post comments

Scratch my previous post

Submitted by grissom3588 on August 23, 2002 - 21:06.

I edited my own version after dissecting it and It says parse error on that get magic quotes thing. What? I'm confused please help me

login or register to post comments

Re: whatever

Submitted by Martin Tsachev on August 25, 2002 - 03:53.

Can you identify which line it is, it's a bit hard to guess which line are you talking about?

login or register to post comments

another dumb newbie

Submitted by mattie_here on August 27, 2002 - 17:31.

Firstly, Jesteruk - You're doing a great job with the articles! I have learnt some useful concepts so far, although I remain stumped in getting a user login working... which brings me to my point: It seems that access to DB.PHP isn't enabled with my web host, so I found the file at pear.php.net and uploaded it to my site. This got me a little further until I got an error about PEAR.PHP, so again I located that file and added it. Now I get the error 'DB Error: not found'. I know it would probably be better to contact the web host and ask them to set PEAR up, but I'm impatient! (and I am not that confident with Unix to start tampering myself). Any help greatly appreciated...

login or register to post comments

Setup of PEAR

Submitted by Martin Tsachev on August 28, 2002 - 03:11.

Mattie, upload PEAR.php, DB.php, DB/Common.php, DB/mysql.php.

If you are using a database different than MySQL upload the respective DB handler instead of DB/mysql.php.

login or register to post comments

another noob sorry for adding to the trend

Submitted by bluSCALE on August 30, 2002 - 20:19.

i'd like to add that remember login and lost password? thing to my login as well but i really do not know how to use cookies. (but i got this login to work :D) anyway, im hard at work on my website and i'd really like to add those features. if someone could refer me to a tutorial or explain (i'll probably understand what your trying to say by the end of the day) i would greatly appretiate that. thanks ahead of time. -Luis

login or register to post comments

Re: another noob sorry for adding to the trend

Submitted by Martin Tsachev on September 1, 2002 - 01:45.

Hi BluSCALE, I wrote an article called Creating a Secure PHP Login Script, it deals with the remember-me function.

login or register to post comments

authentication problem

Submitted by jce on September 1, 2002 - 12:20.

Hi, great article. I am having a bit of a problem with the login phase. It seems as if the users passwords aren't being decrypted or something, I am getting this error : Incorrect password, please try again. I have used my own table setup, and made sure it is changed throughout the scripts, I did not use the last login or show email fields. I know I am using the correct password, so I am completely lost. Here is my login script :

<?php
if(isset($_POST['submit'])) { // if form has been submitted
    /* check they filled in what they were supposed to and authenticate */
    
if(!$_POST['uname'] | !$_POST['passwd']) {
        die(
'You didn\'t fill in a required field.');
    }
    
// authenticate.
    
if(!get_magic_quotes_gpc()) {
        
$_POST['uname'] = addslashes($_POST['uname']);
    }
    
$check $db_object->query("SELECT user_login, user_password FROM users WHERE user_login = '".$_POST['uname']."'");
    if(
DB::isError($check)) {
        die(
'That username doesn\'t exist in our database.');
    }
    
$info $check->fetchRow();
    
// check passwords match
    
$_POST['passwd'] = stripslashes($_POST['passwd']);
    
$info['password'] = stripslashes($info['password']);
    
$_POST['passwd'] = md5($_POST['passwd']);
    if(
$_POST['passwd'] != $info['password']) {
        die(
'Incorrect password, please try again.');
    }

    
// if we get here username and password are correct, register session var
    
$_POST['uname'] = stripslashes($_POST['uname']);
    
$_SESSION['username'] = $_POST['uname'];
    
$_SESSION['password'] = $_POST['passwd'];
    
$db_object->disconnect();
?>
here is my db table :
CREATE TABLE users (
id int(10) DEFAULT '1' NOT NULL auto_increment,
user_login varchar(40) DEFAULT '' NOT NULL,
user_password varchar(32) DEFAULT '' NOT NULL,
user_firstname varchar(50) DEFAULT '' NOT NULL,
user_lastname varchar(50) DEFAULT '' NOT NULL,
user_address varchar(100) DEFAULT '' NOT NULL,
user_city varchar(100) DEFAULT '' NOT NULL,
user_state varchar(100) DEFAULT '' NOT NULL,
user_zip varchar(50) DEFAULT '' NOT NULL,
user_phone varchar(50) DEFAULT '' NOT NULL,
user_email varchar(50) DEFAULT '' NOT NULL,
user_domains varchar(250) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
);
I can create users, but they cannot login. Any help would be greatly appreciated. Thank You.

login or register to post comments

asked for help too soon =)

Submitted by jce on September 1, 2002 - 12:24.

Sorry, I figured out my problem.. I did not change the $info variable to reflect my table field: user_password (duh)

login or register to post comments

Viewing variable content

Submitted by shotgun on September 13, 2002 - 08:40.

I find very convenient to sporadically use print_r(); to view variable content in different parts of my code. However, I sometimes forgot to precede it with print '<pre>'; and afterwards with print '</pre>'; so that the indentation and /n that print_r(); introduces displays correctly on the browsers. I created the function print_var(); to handle such needs:

print_var($var){
	print '<pre>';
	print_r($var);
	print '</pre>';
	return;
}

With this, you only need to specify print_var($variable) to view the contents of $variable

login or register to post comments

can't get db_connect.php or check_login.php to re

Submitted by solowookie on September 16, 2002 - 19:55.

I am unable to get db_connect.php or check_login.php to recognize my session variables. I have altered the above code, but only to take out the pear options, and use what I'm familiar with. I would like to convert over to pear later, but it is a large chunk for me to bite off right now. I am listing my login.phtml (the relevant sections)

session_start();<BR>
<BR>
session_register("username");<BR>
session_register("password");<BR>
require_once 'db_connect.php;<BR>

(this is the bottum of the login.phtml file I created)

<?PHP mysql_close($link)?><BR>
<BR>
DomIntCom main site<BR>
Login Successful<BR><BR>
<BR>
<BR>
<BR>
<BR>
<?PHP header("Refresh: 5;Location: home.html");?>


I included the db_connect.php's because I could not get these variables to recognize. I'm using zend studio, and when I add a watch as soon as the other pages are called through the require & include the $SESSION_['username & password'] are null.


db_connect.php
session_start();<BR>
$link = mysql_connect("localhost", "mysql", "xxxxxx")or die("Could not connect");<BR>
mysql_select_db("http_users") or die("Could not select database");<BR>
include'check_login.php';<BR>
session_register("link");<BR>

check_login.php
<BR>
session_start();<BR>
$username = $_SESSION['username'];<BR>
$password = $_SESSION['password'];<BR>
$sql = mysql_query("SELECT password FROM users WHERE username = '$username'") or die("Invalid Query");<BR>
$fetch_em = mysql_fetch_array($sql);<BR>
$numrows = mysql_num_rows($sql);<BR>
<BR>
if($numrows != "0" & $password == $fetch_em["password"]) <BR>
{$valid_user = 1;}<BR>
else <BR>
{$valid_user = 0;}<BR>

login or register to post comments

track_vars is better

Submitted by Martin Tsachev on September 17, 2002 - 10:44.

As I can see you're using PHP 4.1 or later. You also have track_vars on, the best option is to delete these session_register lines and replace all references to $username with $_SESSION['username'], apply the same for password.

PS. When you want to write < use &lt; instead. This is HTML after all ;-)

login or register to post comments

track_vars is better

Submitted by Martin Tsachev on September 17, 2002 - 12:08.

As I can see you're using PHP 4.1 or later. You also have track_vars on, the best option is to delete these session_register lines and replace all references to $username with $_SESSION['username'], apply the same for password.

PS. When you want to write < use &lt; instead. This is HTML after all ;-)

login or register to post comments

All Fine and Dandy

Submitted by PillFORM on September 24, 2002 - 11:25.

Well this is a great script for me to learn from, and I only have one question as of yet......

How do i get it to go to the page i was trying to access after i have logged in ?

In the previous artice it explained what to do, and did it flawless. But this time i am confussed as to what i am supposed to do.
I am fairly new to this and could use a hand.
thanx

Phil

login or register to post comments

Getting an Erro masage on db_connect.php

Submitted by Codek on October 8, 2002 - 04:47.

When i open db_connect of this article on the second textarea, i keep on getting this error masage: Fatal error: Undefined class name 'db' in ( my root directory) on line 12 (of this script). Can sombody help please? Here is the file i am opening:
<?php
require_once 'DB.php';    //require the PEAR::DB classes.

$db_engine 'mysql';
$db_user 'jester';
$db_pass 'password';
$db_host 'localhost';
$db_name 'database';

$datasource $db_engine.'://'.$db_user.':'.$db_pass.'@'.$db_host.'/'.$db_name;

$db_object DB::connect($datasourceTRUE);
/* assign database object in $db_object, if the connection fails $db_object will contain
the error message. */

if(DB::isError($db_object)) {
    die(
$db_object->getMessage());    // If $db_object contains an error print out the
}                            // error and exit.

$db_object->setFetchMode(DB_FETCHMODE_ASSOC);

include(
'check_login.php'); // we write this later on, ignore for now.
?>
You can Email me: ikead@hotmail.com
Thankxx...

login or register to post comments

i am sorry for the poor output of this file

Submitted by Codek on October 8, 2002 - 04:54.

it did not come out good but i hope u can understand my problem on the second textarea which give error: Undefined class 'db' on line 12.

login or register to post comments

Re: Getting an Erro masage on db_connect.php

Submitted by Martin Tsachev on October 8, 2002 - 05:15.

Do you have PEAR? If not download and install a copy.

login or register to post comments

Yes i am runing php version 4.2.1 and mysql

Submitted by Codek on October 8, 2002 - 05:25.

do i need to download and install since it seems that this version comes with Pear
Or do i need any configuration on this version of php- 4.2.1-win32

Thankx for ur reaction.

login or register to post comments

PHP and PEAR

Submitted by Martin Tsachev on October 8, 2002 - 05:30.

Your hosting service (if you use one) may have disallowed its use or have it misconfigured. If it's on your own computer edit php.ini and make sure it countains a line like include_path = ".;c:\www\php\" where c:\www\php is where PEAR is installed.

login or register to post comments

I have configured php.ini

Submitted by Codek on October 8, 2002 - 06:06.

i have configured php.ini to include the directory called Pear in php dir on my machine which looks like this: C:\php\pear and i stil get the same error. I also include two folders of pear which looks like this: C:\hph\pear\pear to php.ini and the problem is stil the same. i dont know what i am doing wrong... i appriciate u help thanks.

login or register to post comments

Re: I have configured php.ini

Submitted by Martin Tsachev on October 8, 2002 - 10:23.

Do you have any open_basedir restirictions?

Check that the following files are in the PEAR directory: PEAR.php, DB.php, DB/common.php, and DB/mysql.php.

If that doesn't work set the error_reporting to E_ALL to get more errors.

login or register to post comments

No open basedir

Submitted by Codek on October 8, 2002 - 11:47.

There is no open_basedir restrictions
PEAR.php, DB.php are in Pear dir
And common.php, mysql.php are also in the DB dir
error_reporting is allready on E_ALL

login or register to post comments

Yes it connects yaaaaaaa

Submitted by Codek on October 8, 2002 - 14:16.

It is now connecting to the database. Thank u very much for all ur help Shaggy
Incase this will help any one the mistake there was that i did not include the directory of Pear to php.ini include_path And even when i did that i did not refresh the server. After the server was refreshed the error was gone and connection was made.

login or register to post comments

Password Encryption Problem :(

Submitted by PillFORM on October 20, 2002 - 11:29.

I am having a problem with my login script..
I had it working fine, but I messed with and it wont work now. So i started over to simplify the whole thing

When i register a name and password it completes with out a problem, but when i try and login, it tells me i have an incorrect password, i know for sure I am typing it coorectly, and i assume it had been SET correctly when Registering since it is exactly how is was when i had it working. It seems like it is encrypting imporperly or unencrypting wrong. I am not sure. If anyone has had the same problem or can maybe help... PLEASE DO

Thnax, Phil
www.funkinfamily.com

www.funkinfamily.com/net/join.php

login or register to post comments

I FIGURED IT OUT :)

Submitted by PillFORM on October 20, 2002 - 11:54.

Nevermind.... I figured out my problem, i set the VARCHAR for Username and Password to 10 in my table.... i was unaware that encrypting things made a code much longer than the original data :) opps

Phil
www.funkinfamily.com

login or register to post comments

How do i SELECT session data from my DB

Submitted by PillFORM on October 21, 2002 - 21:53.

Well i have my user login and registration working great! But I am still quit new to this and am not sure how to reverse the process to pull data from my DB to create an editable User Profile page. Can some one please help me?

How would I make php echo $_SESSION['f_name'] work?

$get = $db_object->query("SELECT * FROM users_id WHERE username = '".$_POST['uname1']."'");

$data = $check->fetchRow(); $data['f_name'] = stripslashes($data['f_name']);

What am i doing? Thanx

Phil

login or register to post comments

The access keys for this page are: ALT (Control on a Mac) plus:

  • 1 links to the evolt.org home page.
  • plus 2 skips to the main content of the page.
  • plus 3 skips to login and registration.
  • plus 4 skips to the search form.
  • plus 5 links to site FAQs.
  • plus 6 skips to list of content categories in this site.
  • plus 7 skips to the index of other sites in the evolt network.
  • plus 9 links to the feedback page.
  • plus 0 will repeat this list.
evolt.orgEvolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.