• (2 Pages)
  • +
  • 1
  • 2

User Authentication With Member-Only Pages Rate Topic: ***** 3 Votes

#1 danielair  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 22
  • View blog
  • Posts: 118
  • Joined: 12-July 09

Posted 25 July 2010 - 03:47 PM

Okay guys we're making a simple user authentication thing. This will allow you have have users for your website. Then you can also have member-only pages but simply adding one like of cause to those pages. Pretty cool huh, ok lets get started here.

First off you'll need your MySQL database. Mine only has 5 columns but you can have more if you want to. This bit of cause will create a database, "userauth", then create 5 columns named "ID" for the user count, "UID" for the user's unique id number, "Username" for the user's username, "Email" for their email, and "Password" for the password. Heres the SQL code to use.
CREATE DATABASE `userauth` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `userauth`;

CREATE TABLE `users` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `UID` int(11) NOT NULL,
  `Username` text NOT NULL,
  `Email` text NOT NULL,
  `Password` text NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;



Now for the "sql.php". Really all this code does to connect to the databse. First will will create the variables for your MySQL server and user information, then it will connect to the server. Next it will select the database, in this case "userauth". This code get used in "log.php" and "reg.php" to access the database. Here it is
<?php
	//sql.php
	$server = "localhost"; //Your MySQL Server
	$user = "root"; //Your MySQL username
	$pass = "redere"; //Password

	$conn = mysql_connect($server, $user, $pass); //Connect to ther serve
	$db = mysql_select_db("userauth", $conn); //Select the database

	if(!$db) { //If it can't select the database
		echo "There was an error, sorry :(/>"; //Show an error message
		exit(); //Cancel any more PHP scripts
	}
?>




Next you want your login page, I named mine "login.php". First it checks for errors and shows them just in cause the user had been redirected back to this page due to an error loggin in. Then it has a field of username, password, a submit button, and a link to register. When the user hits "Login" it will go to "log.php" to execute the login.
<?php
	//login.php
	session_start(); //Start the session
	if(isset($_SESSION['ERRMSG']) && is_array($_SESSION['ERRMSG']) && count($_SESSION['ERRMSG']) >0 ) { //If the error session exists
		$err = "<table>"; //Start a table
		foreach($_SESSION['ERRMSG'] as $msg) { //Get each error
			$err .= "<tr><td>" . $msg . "</td></tr>"; //Write them to a variable
		}
		$err .= "</table>"; //Close the table
		unset($_SESSION['ERRMSG']); //Delete the session
	}
?>
<html>
	<head>
		<title>My Login Form</title>
	</head>
	<body>
		<form action='log.php' method='post'>
			<table align="center">
				<tr>
					<td><?php echo $err; ?></td>
				</tr>
				<tr>
					<td>Username</td>
					<td><input type='text' name='username'></td>
				</tr>
				<tr>
					<td>Password</td>
					<td><input type='password' name='password'></td>
				</tr>
				<tr>
					<td><input type='submit' value='Login'></td>
					<td><a href="register.php">Register</a></td>
				</tr>
			</table>
		</form>
	</body>
</html>



Next up, we'll do the script to login, mine is called "log.php", this one has a function that will clean the input to remove SQL injections that mess up your script. First it'll get the input from the form and fix it up then make sure it's right if it is it sends you to the members page if not, it sets the errors in a seesion to be read by the login page and send you there. Here it is.
<?php
	include("sql.php"); //Connect to SQL

	session_start(); //Start session for writing

	function Fix($str) { //Clean the fields
		$str = trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}

	$errmsg = array(); //Array to store errors
	
	$errflag = false; //Error flag

	$username = Fix($_POST['username']); //Username
	$password = Fix($_POST['password']); //Password

	//Check Username
	if($username == '') {
		$errmsg[] = 'Username missing'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Check Password
	if($password == '') {
		$errmsg[] = 'Password missing'; //Error
		$errflag = true; //Set flag so it says theres an error
	}


	//If there are input validations, redirect back to the registration form
	if($errflag) {
		$_SESSION['ERRMSG'] = $errmsg; //Write errors
		session_write_close(); //Close session
		header("location: login.php"); //Rediect
		exit(); //Block scripts
	}

	//Create SELECT query
	$qry = "SELECT * FROM `users` WHERE `Username` = '$username' AND `Password` = '" . md5($password) . "'";
	$result = mysql_query($qry);
	
	//Check whether the query was successful or not
	if(mysql_num_rows($result) == 1) {
		while($row = mysql_fetch_assoc($result)) {
			$_SESSION['UID'] = $row['UID']; //Retrieve the UID from the database and put it into a session
			$_SESSION['USERNAME'] = $username; //Set the username as a session
			session_write_close(); //Close the session
			header("location: member.php"); //Redirect
		}
	} else {
		$_SESSION['ERRMSG'] = "Invalid username or password"; //Error
		session_write_close(); //Close the session
		header("location: login.php"); //Rediect
		exit(); //Block scripts
	}
?>



Now for the register page, mine is "register.php". Almost the same thing as the login page only with more fields. And instead of a register link, this one has a link, back to login.php, to click if you already have an account.
<?php
	//register.php
	session_start(); //Start the session
	if(isset($_SESSION['ERRMSG']) && is_array($_SESSION['ERRMSG']) && count($_SESSION['ERRMSG']) >0 ) { //If the error session exists
		$err = "<table>"; //Start a table
		foreach($_SESSION['ERRMSG'] as $msg) { //Get each error
			$err .= "<tr><td>" . $msg . "</td></tr>"; //Write them to a variable
		}
		$err .= "</table>"; //Close the table
		unset($_SESSION['ERRMSG']); //Delete the session
	}
?>
<html>
	<head>
		<title>My Register Form</title>
	</head>
	<body>
		<form action='reg.php' method='post'>
			<table align="center">
				<tr>
					<td><?php echo $err; ?></td>
				</tr>
				<tr>
					<td>Username</td>
					<td><input type='text' name='username'></td>
				</tr>
				<tr>
					<td>Email</td>
					<td><input type='text' name='email'></td>
				</tr>
				<tr>
					<td>Password</td>
					<td><input type='password' name='password'></td>
				</tr>
				<tr>
					<td>Repeat Password</td>
					<td><input type='password' name='rpassword'></td>
				</tr>
				<tr>
					<td><input type='submit' value='Register'></td>
					<td><a href="login.php">I have an account</a></td>
				</tr>
			</table>
		</form>
	</body>
</html>



Next up is the register script, "reg.php". First this will include "sql.php" to connect to to database. Next it uses the same function that the login script uses to clean the input fields. Then it sets the variables for the errors that might occur. Then it will create another function to generate a unique id that has never been udes before. Next it retrieve the values from the register form and then cheack each one. These are pretty simple the only really special two are for the email, which makes sure it in the right format, and for the password and rpassword that makes sure that they are the same. Now the script will check to see if the username has been used before, if so it returns an error. And then it checks to see if the errflas is true, if so then it set an error session and returns to the register form. And lasty and most importantly the code to actually add the user into the database, the is pretty simple. The SQL code just syays which rows to insert data into, then the actual data. If it works then it writes a success message, if not it it shows an error.
<?php
	//reg.php
	include("sql.php"); //Connect to SQL

	session_start(); //Start session for writing

	function Fix($str) { //Clean the fields
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}

	$errmsg = array(); //Array to store errors
	
	$errflag = false; //Error flag

	$UID = "12323543534523453451465685454"; //Unique ID
	$username = Fix($_POST['username']); //Username
	$email = $_POST['email']; //Email
	$password = Fix($_POST['password']); //Password
	$rpassword = Fix($_POST['rpassword']); //Repeted Password

	//Check Username
	if($username == '') {
		$errmsg[] = 'Username missing'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Check Email
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) { //Make sure email is in the format: me@hi.com
		$errmsg[] = 'Invalid Email'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Check Password
	if($password == '') {
		$errmsg[] = 'Password missing'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Check Repeated Password
	if($rpassword == '') {
		$errmsg[] = 'Repeated password missing'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Make sure passwords match
	if(strcmp($password, $rpassword) != 0 ) {
		$errmsg[] = 'Passwords do not match'; //Error
		$errflag = true; //Set flag so it says theres an error
	}

	//Make sure username is availible
	if($username != '') {
		$qry = "SELECT * FROM `users` WHERE `Username` = '$username'"; //MySQL query
		$result = mysql_query($qry);
		if($result) {
			if(mysql_num_rows($result) > 0) { //If username is in use
				$errmsg[] = 'Username already in use'; //Create error
				$errflag = true; //Set flag so it says theres an error
			}
			mysql_free_result($result);
		}
	}

	//If there are input validations, redirect back to the registration form
	if($errflag) {
		$_SESSION['ERRMSG'] = $errmsg; //Write errors
		session_write_close(); //Close session
		header("location: register.php"); //Rediect
		exit(); //Block scripts
	}

	//Create INSERT query
	$qry = "INSERT INTO `userauth`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES('$UID','$username','$email','" . md5($password) . "')";
	$result = mysql_query($qry);
	
	//Check whether the query was successful or not
	if($result) {
		echo "Thank you for registering, " . $username . ". Please login <a href=\"login.php\">Here</a>";
		exit();
	} else {
		die("There was an error, try again later");
	}
?>



Now we'll do the logout script to log the user out, duh. Really simple first starts the session for using the sessions, then destorys them UID and USERNAME sessions, then redirects back to the login page.
<?php
	session_start();

	unset($_SESSION['UID']);
	unset($_SESSION['USERNAME']);
	header("location: login.php");
?>



Lastly, "auth.php", the script you can use to make member-only pages, this simply checks to see if the session is set then checks it against the username and if it's a match then allows the user to view the page, if not they'll be asked to login. And just incase someone tried to hack the site by creating one of the sessions then it destorys both anyway.
<?php
	include("sql.php");
	session_start();

	function Destroy() {
		unset($_SESSION['UID']);
		unset($_SESSION['USERNAME']);
		header("location: login.php");
	}

	if(isset($_SESSION['UID']) && isset($_SESSION['USERNAME'])) {
		$UID = $_SESSION['UID'];
		$username = $_SESSION['USERNAME'];
		$qry = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID' AND `Username` = '$username'");
		if(mysql_num_rows($qry) != 1) { Destroy(); }
	} else { Destroy(); }
?>



You can use this code like I have here on "member.php".
<?php include("auth.php"); ?>
You are allowed here. <a href="logout.php">Logout (<?php echo $_SESSION['USERNAME']; ?>)</a>



To make any page you want only accesible to members just use this one line of PHP
<?php include("auth.php"); ?>



And there you have it, a working login system with member-only pages, enjoy!

Hope you like it,
Daniel

Attached File(s)



Is This A Good Question/Topic? 2
  • +

Replies To: User Authentication With Member-Only Pages

#2 danielair  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 22
  • View blog
  • Posts: 118
  • Joined: 12-July 09

Posted 18 August 2010 - 04:44 PM

Hey guys I noticed I made a mistake in my code and just wanted to correct that. The problem was in the "reg.php" file I forgot to write the function to generate a new UniqueID for each user. This could cause a huge error if you try to adapt this code for a later use and would give all the users the same UniqueID and that'd be bad. So lets just fix this now.

In "reg.php" change
	$UID = "12323543534523453451465685454"; //Unique ID



Into
	function UniqueID() {
		$UID = uniqid(); //Create unique ID
		$check = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID'");
		if(mysql_num_rows($check) > 0) { //Check if it exists
			UniqueID(); //Redo the function
		} else {
			return $UID; //return the uniqueid
		}
	}

	$UID = UniqueID(); //Unique ID



Hope that helps you out, I've attached the updated ZIP folder for your convenience.

Thanks for reading,
Daniel

Attached File(s)


Was This Post Helpful? 2
  • +
  • -

#3 Guest_TTWP*


Reputation:

Posted 01 February 2011 - 12:11 AM

View Postdanielair, on 18 August 2010 - 04:44 PM, said:

Hey guys I noticed I made a mistake in my code and just wanted to correct that. The problem was in the "reg.php" file I forgot to write the function to generate a new UniqueID for each user. This could cause a huge error if you try to adapt this code for a later use and would give all the users the same UniqueID and that'd be bad. So lets just fix this now.

In "reg.php" change
	$UID = "12323543534523453451465685454"; //Unique ID



Into
	function UniqueID() {
		$UID = uniqid(); //Create unique ID
		$check = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID'");
		if(mysql_num_rows($check) > 0) { //Check if it exists
			UniqueID(); //Redo the function
		} else {
			return $UID; //return the uniqueid
		}
	}

	$UID = UniqueID(); //Unique ID



Hope that helps you out, I've attached the updated ZIP folder for your convenience.

Thanks for reading,
Daniel



Great code!!! Where does the logout code go?
Was This Post Helpful? 0

#4 hknz  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 14-May 11

Posted 28 June 2011 - 04:02 AM

Thanks danielair,
This is a great Tutorial on PHP logon's.

The Tutorial was very useful and I was able to use this in a project I have just recently made.
There was a few issues I came across and I think some of these are to do with the fact I was testing this on the latest PHP (5.3.5)

I found the following issues with some of the code:

1. UID only works for the first user than loops and errors out saying it took longer than 30seconds to complete.
To get it working I just NULL'ed it for now.

2. Notice: Undefined variable: err in 'login.php' @ line 20 - I needed to put a global var into the php code to stop it from having errors 'global $err;'
and also on register.php @ line 20

3. reg.php line 41 -- eregi is not supported in php5.3 and needs to be changed to preg_match

4. log.php @ line 55 -- the error message for 'Invalid username or password' doesn't seem to work so changed around some of the code and this is what worked for me:
else {
		$errmsg[] = 'Invalid username or password';
		$_SESSION['ERRMSG'] = $errmsg;
		session_write_close();
		header("location: login.php");
		exit();
	}




Hope these fixes help someone else out in the future.

Hagen.

This post has been edited by hknz: 28 June 2011 - 04:03 AM

Was This Post Helpful? 1
  • +
  • -

#5 dbeaird727  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 238
  • Joined: 13-December 10

Posted 12 September 2011 - 10:53 PM

Would changing the database table to utf8 have any affect on the existing code? And would not changing it affect a user logging in or registering on my site?
Was This Post Helpful? 0
  • +
  • -

#6 Easyslider01  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 20-September 11

Posted 20 September 2011 - 03:04 PM

View Posthknz, on 28 June 2011 - 04:02 AM, said:

Thanks danielair,
This is a great Tutorial on PHP logon's.

The Tutorial was very useful and I was able to use this in a project I have just recently made.
There was a few issues I came across and I think some of these are to do with the fact I was testing this on the latest PHP (5.3.5)

I found the following issues with some of the code:

1. UID only works for the first user than loops and errors out saying it took longer than 30seconds to complete.
To get it working I just NULL'ed it for now.

2. Notice: Undefined variable: err in 'login.php' @ line 20 - I needed to put a global var into the php code to stop it from having errors 'global $err;'
and also on register.php @ line 20

3. reg.php line 41 -- eregi is not supported in php5.3 and needs to be changed to preg_match

4. log.php @ line 55 -- the error message for 'Invalid username or password' doesn't seem to work so changed around some of the code and this is what worked for me:
else {
		$errmsg[] = 'Invalid username or password';
		$_SESSION['ERRMSG'] = $errmsg;
		session_write_close();
		header("location: login.php");
		exit();
	}




Hope these fixes help someone else out in the future.

Hagen.


How did you add the global variable to your code? Do you think this will solve the problem I am having with not being able to login in to the member page?

I can register just fine, but every time I enter the username and password I just get the login page.
Was This Post Helpful? 0
  • +
  • -

#7 hknz  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 14-May 11

Posted 06 October 2011 - 05:58 AM

View Postdbeaird727, on 12 September 2011 - 10:53 PM, said:

Would changing the database table to utf8 have any affect on the existing code? And would not changing it affect a user logging in or registering on my site?

From what I understand,
This depends on if you:
1. Already have data in a database and then switch it to utf8
2. or start a new database with utf8

If you already have data in a database: You have to dump the data then Import the dump.
Read more here: utf8_dump

The only way I can see it affecting the user logging in or registering will be if you change the:
DB name, Table name or column names and don't reflect those changes in your website PHP code.

Wider reading: Book

I'm not a DB expert and personally I used Latin1 when I set up my DB for this project because I'm familiar with that collation.

Hagen.

This post has been edited by hknz: 06 October 2011 - 06:00 AM

Was This Post Helpful? 0
  • +
  • -

#8 hknz  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 7
  • Joined: 14-May 11

Posted 06 October 2011 - 06:21 AM

View PostEasyslider01, on 20 September 2011 - 03:04 PM, said:

How did you add the global variable to your code? Do you think this will solve the problem I am having with not being able to login in to the member page?

I can register just fine, but every time I enter the username and password I just get the login page.

This is the syntax that I used for adding the Global variable:
<?php global $err; echo $err; ?>
The variable $err; is only there to display the error messages that get tripped, when a user incorrectly logs in or registers. -- I don't think that will fix your log-in issues. (But give it a try)

I have included an attachment that is a 'flow diagram' of how the restricted pages work for this tutorial.
It might help you to work out which file you need to investigate further.
Attached File  site_map.pdf (38.92K)
Number of downloads: 488

If you're still having problems and can't work out why its not going, the next step I would probably have to see your code.

Hagen.

This post has been edited by hknz: 06 October 2011 - 06:30 AM

Was This Post Helpful? 1
  • +
  • -

#9 syafiq92  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-February 12

Posted 14 February 2012 - 08:12 PM

Why I cannot register new user? I can only register once, then when I register another user the page display "The connection was reset The connection to the server was reset while the page was loading."
Was This Post Helpful? 0
  • +
  • -

#10 rosepetalpowder  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 65
  • Joined: 28-February 12

Posted 02 April 2012 - 08:10 PM

amazing tutorial.just wht i needed.
Was This Post Helpful? 0
  • +
  • -

#11 mynowrose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 02-November 12

Posted 02 November 2012 - 04:51 AM

how to solve problem i don't php

how to solve problem i don't php

i have attached screenshot
Was This Post Helpful? 0
  • +
  • -

#12 m1a9r8k3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-December 12

Posted 18 December 2012 - 11:37 AM

View Posthknz, on 28 June 2011 - 04:02 AM, said:

1. UID only works for the first user than loops and errors out saying it took longer than 30seconds to complete.
To get it working I just NULL'ed it for now.


I think I know what the problem is:
The uniqid() php function generates random ID's that always look like these: (have tested it in php)

50d0b63dcddb1
50d0b6861162e
50d0b68d9d948

So the first time it inserts an ID like that into the int(UID) column in the database it uses only the number 50 (cause after that it's not int anymore). The next time it generates the same kind of number with 50 always as the first two numbers, therefore when it checks if the ID already exists it will evaluate "true" and enter an infinite loop..

At the moment i'm searching for a solution.. If I find it i'll post it.. if someone else has the solution already, it would be very kind to share it with us.. =)
Was This Post Helpful? 0
  • +
  • -

#13 m1a9r8k3  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-December 12

Posted 18 December 2012 - 11:59 AM

In the end I used rand() instead of uniqid()..

function UniqueID() {
		$UID = rand(); //Create unique ID
		$check = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID'");
		if(mysql_num_rows($check) > 0) { //Check if it exists
			UniqueID(); //Redo the function
		} else {
			return $UID; //return the uniqueid
		}
	}


Was This Post Helpful? 0
  • +
  • -

#14 tommythetimmy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 26-February 14

Posted 26 February 2014 - 02:30 AM

View Postdanielair, on 18 August 2010 - 04:44 PM, said:

Hey guys I noticed I made a mistake in my code and just wanted to correct that. The problem was in the "reg.php" file I forgot to write the function to generate a new UniqueID for each user. This could cause a huge error if you try to adapt this code for a later use and would give all the users the same UniqueID and that'd be bad. So lets just fix this now.

In "reg.php" change
	$UID = "12323543534523453451465685454"; //Unique ID



Into
	function UniqueID() {
		$UID = uniqid(); //Create unique ID
		$check = mysql_query("SELECT * FROM `users` WHERE `UID` = '$UID'");
		if(mysql_num_rows($check) > 0) { //Check if it exists
			UniqueID(); //Redo the function
		} else {
			return $UID; //return the uniqueid
		}
	}

	$UID = UniqueID(); //Unique ID



Hope that helps you out, I've attached the updated ZIP folder for your convenience.

Thanks for reading,
Daniel


Dear, Danielair,

Thank you for such incredible code for me to use,

There is 1 (one) question I would like to ask about,

For example I am protecting test.php page, then it redirect me to login.php login page and

if I am authenticated, it will go to member.php member page,

How do I get back to the original page that the user want to access automatically?

Thank you,
Tommy
Was This Post Helpful? 0
  • +
  • -

#15 grizrule  Icon User is offline

  • D.I.C Head

Reputation: 9
  • View blog
  • Posts: 88
  • Joined: 29-December 13

Posted 01 March 2014 - 02:19 PM

Wow! Thanks for this tutorial, this was just what I was looking for.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2