Jump to content
xisto Community
Sign in to follow this  
kiro

Php/mysql Login/register Tutorial for login with databases.

Recommended Posts

Start register code. Register.php

<form method=post action=register.php?action=register  name=s><table><tr><td>Username:</td><td><input type=text name=user></td></tr><tr><td>Email:</td><td><input type=text name=email></td></tr><tr><td>Pass:</td><td><input type=password name=pass></td></tr><tr><td>Verify Pass:</td><td><input type=password name=vpass></td></tr><tr><td colspan=2 align=center><input type=submit value=Register></td></tr></table></form><?php//Login to your database. Make the fields of course..mysql_connect("localhost","user","pass");mysql_select_db("database");//end//if registering, check fields.if ($action == register) {	if (!$user || !$pass || !$email || !$vpass) {  print "You must fill out all fields.";  exit;	}$dupe1 = mysql_num_rows(mysql_query("select * from table where user='$user'"));	if ($dupe1 > 0) {  print "Someone already has that username.";  exit;	}$dupe2 = mysql_num_rows(mysql_query("select * from table where email='$email'"));	if ($dupe2 > 0) {  print "Someone already has that email.";  exit;	}//check if passwords are the same	if ($pass != $vpass) {  print "The passwords do not match.";  exit;	}//end//insertmysql_query("insert into table (user, email, pass) values('$user','$email','$pass')");print "You are now registered. Login.";}?>


Now that you are done with register, make the login. Login.php
<form method=post action=Login.php?action=login><table><tr><td>Email:</td><td><input type=text name=email></td></tr><tr><td>Pass:</td><td><input type=password name=pass></td></tr><tr><td colspan=2 align=center><input type=submit value=Login></td></tr></form></table><?phpif($action==login){//checkif (!$email || !$pass) {	print "Please fill out all fields.";	exit;}$logres = mysql_num_rows(mysql_query("select * from table where user='$email' and pass='$pass'"));if ($logres <= 0) {	print "Login failed. If you have not already, please signup. Otherwise, check your spelling and login again.";	exit;} else {//logged in, register the session..	session_register("email");	session_register("pass");	print "You are now logged in..";}}?>

Now, this is members.php, it checks if the session is registered or not..

<?phpif (!session_is_registered("email") || !session_is_registered("pass")) {	print "You need to login to view this page!! ";	exit;}print "Content here";?>


Ok, we are done, if you do not know how to do the mysql for the pages, here is the sql code:

CREATE TABLE `table` (  `id` int(5) NOT NULL auto_increment,  `user` varchar(255) NOT NULL default '',  `email` varchar(255) NOT NULL default '',  `pass` varchar(255) NOT NULL default '',  PRIMARY KEY  (`id`)) TYPE=MyISAM AUTO_INCREMENT=1;


Thats it! :)

Share this post


Link to post
Share on other sites

Yeah there could be an admin center to delete members and/or an IP banning tool. :)

Share this post


Link to post
Share on other sites
Errors.Php/mysql Login/register

There are hundreds of errors in this script. The main ones being undefined variables. In register.Php you have used variables such as $user and $pass but in the php code you have not defined any of them. I had to go back through all of them and change the to $_POST[''] etc.

Also in register.Php you use the url parametre action=register but when you call that parametre you don't define what 'action' is. You should replace it with " if ($_GET['action'] == 'register') "

You should re-develope this entire script.

But thumbs up for effort.

Chris

Share this post


Link to post
Share on other sites

This is how I would had created PHP with MySQL Database. A Short Tutorial for everyone.

 

we will first create a login script. The login script will have a MYSQL table which it will reference to verify the existence of a user at login. It will also have various scripts that will help register a new user and retrieve forgotten passwords.

 

Login Script

 

The login script will have the following pages:

 

Login.php - Enables users to log in.

Logout.php - Enables logging out.

Register.php - Creates new users.

Password.php - Password recovery.

Messages.php - Handles error messages.

Let's create a table that will gather the following information about a user:

 

Username

Password>

Level

Admin - This will be the moderator of the system

Normal - Normal access rights


Date_joined

IP Address - Enables us to identify and ban users.

Email - Used for password recovery.

Isbanned - Enable us to ban users

Here's the table:

CREATE TABLE `user` (

`id` int(5) NOT NULL auto_increment,

`uname` varchar(98) NOT NULL default '',

`pw` varchar(98) NOT NULL default '',

`email` varchar(100) NOT NULL default '',

`date_joined` datetime NOT NULL default '0000-00-00 00:00:00',

`ip` varchar(20) NOT NULL default '',

`level` varchar(10) NOT NULL default '',

`isbanned` enum('yes','no') NOT NULL default 'no',

PRIMARY KEY (`id`)

) TYPE=MyISAM AUTO_INCREMENT=11 ;

 

As you can see from the table layout, the table gathers a lot of information about a user. The most significant item of them all is the "isbanned" field. This field is responsible for checking whether or not a user is banned. The "ip" field stores the IP address of the user, which will be used to reinforce the isbanned status of a user.

 

 

If you can simply just copy and paste the following code from above to php my admin and run the SQL.

 

2) Login.php

 

This file displays a form that requests your username and password and also gives you the options to register as a new user or recover your password if you've forgotten it. Once you've pressed the submit button the following code gets executed:

 

<?

session_start();

if(isset($_GET['reg'])){

$reg=$_GET['reg'];

}else{

$reg="";

}

if($reg==1){

$msg1="<font color="#FF0000"><b>Your details have been added,

please login</b></font>";

}elseif($reg==2){

$msg1="<font color="#FF0000"><b>You have been successfully

logged out.</b></font>";

}elseif($reg==3){

$msg1="<font color="#FF0000"><b>You have been redirected because you need to be logged on as administrator.</b></font>";

}

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

if( empty($_POST['uname']) && (empty($_POST['upass']))){

header( "Location:Messages.php?msg=1" );

exit();

}

//transfer to shorter var

$n=$_POST['uname'];

$p=$_POST['upass'];

//connect to db

include('config.php');

$query="select * from user where uname='$n' and pw='$p'";

if($result=mysql_query($query)){

$row=mysql_fetch_assoc($result);

//check each var

if($n !=$row['uname']){

header( "Location:Messages.php?msg=2" );

exit();

}

if($p !=$row['pw']){

header( "Location:Messages.php?msg=11" );

exit();

}

if($row['isbanned']=='yes'){

header( "Location:Messages.php?msg=12" );

exit();

}

}//ifresult

//put in session vars

$_SESSION['level'] = $row['level'];

$_SESSION['status'] = 'logged';

$_SESSION['username'] = $n;

//This takes you to the admin pages; change this to take you to

wherever you want it //to go.

header("location:../admin/main.php");

exit;

}?>

 

This script checks to see whether a user exists. If so, the username and password is compared with the information in the database. It also checks to see whether the user is banned. If all the checks are okay, the script puts the username in a session variable and then sends the user through to the appropriate page. If the user does not exist, the program goes to the messages page and displays an error message.

 

The script also checks the user's banned status. If a user is banned, then the script directs you to the Messages page. The submitted username and password is checked individually and then the appropriate action is taken. This enables the user to know exactly which of the two, username or password, is wrong.

 

3) Logout.php

 

Logs a user out with the following code:

 

<?

session_start();

if($_SESSION["status"]="logged") {

session_unset();

session_destroy();

header( "Location:login.php?reg=2" );

exit();

}

else{

if ($_SESSION["status"]="not logged") {

//the session variable isn't registered, the user shouldn't even

be on this page

header( "Location:login.php" );

exit();

}

}

?>

 

The 'header( "Location:login.php?reg=2" ); ' code sends a reg value of 2 to the login.php page, which informs the user that he/she has been logged out. To log out a user, we simply empty the session variables that have been filled at login. This is done by the session_unset() and session_destroy() functions.

 

4) Register.php

 

This script registers or adds a new user.

 

The following code does the job:

 

<?

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

//NEED TO CHECK IF FIELDS ARE FILLED IN

if( empty($_POST['name']) && (empty($_POST['email']))){

header("Location:Messages.php?msg=3");

exit();

}

if( empty($_POST['pw1']) && (empty($_POST['pw2']))){

header( "Location:Messages.php?msg=4" );

exit();

}

$name=$_POST['name'];

$email=$_POST['email'];

$pw1=$_POST['pw1'];

$pw2=$_POST['pw2'];

if("$pw1" !== "$pw2" ){

header( "Location:Messages.php?msg=5" );

exit();

}

$ip = $_SERVER['REMOTE_ADDR'];

if(empty($ip)){

header("location:Messages.php?msg=13");

exit();

}

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

$level=$_POST['select'];

}else{

$level="Normal";

}

//connect to the db server , check if uname exist

include('config.php');

$query=("Select * from user where uname='$name'");

$result= mysql_query($query);

$num=mysql_num_rows($result);

if ($num > 0) {//Username already exist

header( "Location:Messages.php?msg=6" );

exit();

}else{

//if username does not exist insert user details

$query=( "INSERT INTO user (uname, pw,email,date_joined,ip,level,isbanned) VALUES ('$name',password

('$pw1'),'$email',NOW(),'$ip','$level','no')");

if(!@mysql_query ($query)) {

echo mysql_error();

}else{

if(empty($_POST['select'])){

header("location:login.php?reg=1");

exit;

}else{

header("location:../admin/main.php");

exit;

}

}

}

mysql_close();

}?>

 

The script does three things:

 

Checks whether all the fields are filled in. If not, the program goes to the messages page where the appropriate error is displayed.

Checks whether the username already exists. If so, the program goes to the messages page where the appropriate error is displayed.

If the username does not exist, the script adds the user details and goes straight to the login page. Where the user can now login.

5) Password.php

 

This script sends the password that the user has forgotten to his/her email address.

 

Here's the password code:

 

<?

include("fns.php");

include "config.php";

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

//1. Check if form fields are filled in

if(!filledin($_POST)){

header( "Location:Messages.php?msg=7" );

exit();

}

$name=$_POST['name'];

$em=$_POST['mail'];

//2. Check if entered name exist

$query="Select pw from user where uname='$name'" or die(mysql_error());

$result= mysql_query($query);

if(mysql_num_rows($result)>0){

for ($i=0; $i<mysql_num_rows($result); $i++) {

$row = mysql_fetch_assoc($result);

$pass=$row['pw'];

$to="$emrn";

$from="From: Admin@jacquesnoah.co.ukrn";

$msg="Password:$passrn";

$msg .="Username:$namern";

$msg .="Please change your password as soon as you logonrn";

$subject="From Admin re:Your Login Passwordrn";

}

}else{

header( "Location:Messages.php?msg=8" );

exit();

}

//3. Send password to user

if(mail($to,$subject,$msg,$from)){

header( "Location:Messages.php?msg=9&email=<?php echo $em; ?>" );

exit();

//echo "Please click here to log";

}else{

header( "Location:Messages.php?msg=10");

exit();

}

}

?>

 

This code does three things:

 

Checks to see if all fields are filled in. Notice the use of the function called 'filledin()' in the line "if(!filledin($_POST)){}">. That function is declared in the functions script called "fns.php" which is included in at the top of the code. It just checks whether all posted variables contain something.

Checks to see if entered name exists. This provides us with extra security, by checking whether the username and email address exist.

Once all security checks have been passed, it sends the password.

I have tried and successfully able to run a effective login script. It can of course always be improved, but for now it is adequate, security wise.

 

Thanks.

Notice from jlhaslip:
Quited from http://forums.xisto.com/no_longer_exists/

Quote tags added


Edited by jlhaslip (see edit history)

Share this post


Link to post
Share on other sites
what about the included files ?Php/mysql Login/register

hey man,

thanks for the script... But what about the  " fns.Php  and  config.Php "  files included in the script ?

I just ran your script and it's no good without the included files, but you don't have them posted ! : (

I am trying to add this to my script... But I don't know what fns.Php or config.Php should have on them ?

can you post those two scripts as well ?

 

thanks

Jeff

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.