Nov 21, 2009

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

free web hosting
Open Discussion > MODERATED AREA > Tutorials

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

kiro
Start register code. Register.php
CODE

<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
//insert
mysql_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
CODE

<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>
<?php
if($action==login){
//check
if (!$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..

CODE

<?php
if (!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:

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! smile.gif

 

 

 


Comment/Reply (w/o sign-up)

rambo406
O.O are u sure that's all?

Comment/Reply (w/o sign-up)

maddog39
Yeah there could be an admin center to delete members and/or an IP banning tool. biggrin.gif

Comment/Reply (w/o sign-up)

(G)ChrisD
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


Comment/Reply (w/o sign-up)

xavier1280
QUOTE
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:

 

 

 


Comment/Reply (w/o sign-up)



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Similar Topics

Keywords : php, mysql, login, register, login, databases

  1. [phpbb] Member Last-visit Report Script
    for phpbb2 databases (0)
  2. To Automatically Run Command When Login / Logoff
    (3)
    In case that you need login and / or logoff to execute some commands. You could do this with GPO
    login / logoff function. Here is step: 1.) Choose Start Menu -> Run -> type in gpedit.msc 2.)
    Expand User -> Windows Settings ->Script ( Logon / Logoff ) 3.) Double-Click either one and a dialog
    displayed 4.) Click the add button and then browse the command files that you wish to executed. The
    Script Parameters allowed you to pass any extra parameters to the command or applications. Click OK
    button. 5.) You command now should displayed on Name / Parameters List Box. Click O....
  3. Simple Php Login And Registration System
    (19)
    Hello. This is my first web tutorial ever. This is basically a simple register and login script.
    Yes, I know it’s a bit rubbish but I’m quite new to PHP/MySQL. Here’s the register form. This can
    be any file extension you like. I’d recommend calling it register.html . CODE
    Register Register Username: Password: First Name:
    Last Name: Age: Now create a MySQL database. Then create a
    file that will be called CODE mysql-connect.php . Here is the file: CODE $co....
  4. Automatic Login
    in WinXP (6)
    Ever wanted to just turn on our computer and when you get back it's already on the desktop?
    (Rather then having to login at the welcome screen) Now some computer have this feature by default,
    but what if it gets broken, try this. On an Administrator account goto start >> Run, and type
    "control userpasswords2" (without the quotes) Uncheck the box that "Users must enter a Username and
    Password to use this computer", then press Ok. You will be prompted to enter a default user and
    their pasword, then next time you restart the computer it will automaticaly login to that....
  5. Backing Up And Restoring Mysql Databases
    (10)
    If you're an Administrator on a Forum, you probably know the importance of regular data backups.
    My Forum is always being hacked by someone and they always delete our SQL Databases. Well this
    tutorial is for all of you who want to protect your data and restore it if necessary! Okay, backing
    up your data is the first part. I use Cron Jobs in my cPanel to automate the backup process. Just
    use this code for backing up all your SQL Databases: CODE mysqldump -u root -psecret
    --all-databases > backup.sql OR if you wish to backup only a single database: CODE ....
  6. Simple Login In Visual Basic 6
    user interaction example trough login programm (9)
    First of all, I am NOT a programmer, this is something my friend taught me. It describes basic
    interaction with the user, while showing basic functionality of this simple programm. So, without
    further ado, we're off to the tutorial: First of all, start your visual basic, when prompted
    for new project, select Standard Exe . Next, we need to open code window, so we can start typing
    the program. This can be done in two ways, one is double clicking on the form, or selecting Code
    from View menu. If you double clicked on the form, you will see following text: CODE ....
  7. How To Put A Phpbb Login Box On Your Main Site.
    Code and .php included!!! (19)
    I have included my coded file with this... Ok here is the code. CODE // //Create login area,
    replace the phpBB2 in /phpBB2/login.php with your forum's //directory //   Prank Place
    Forum Index     Please enter your username and password to log in.        
                  Username:                   Password:      
                Log me on automatically each visit:                    
    I forgot my password         You can test this out on my....
  8. Complete Login And Registration System
    doesn't use mysql! (9)
    kLogin 0.1 QUOTE(readme.txt) Readme file to kLogin 0.1 To use the internet explorer fix:
    download the latest IE7 ZIP file
    (http://sourceforge.net/project/showfiles.php?group_id=109983&package_id=119707) Extract the ie7
    zip file to the root directory of your web server. Example, if you are using a unix/linux server,
    it's on "public_html/" or "home/public_html" Open kLogin.php file with your editor and edit the
    $info_text or $info_txt variable. Then, extract the kLogin.php file in to the root directory of
    your web server also. Just run kShoutBox.php If ....
  9. Multiple Admin Login (php)
    This is a script that doesnt requre SQL (3)
    first off make a login.html page Code: QUOTE Admin Login Username: Password:
    then make a check.php page Code: QUOTE $admin1 = "admin1"; // first
    admin username $adm_pass1 = "password1"; // first admin password $admin2 = "admin2"; // second
    admin username $adm_pass2 = "password2"; // second admin password if(($username == $admin1 &&
    $password == $adm_pass1) || ($username == $admin2 && $password == $adm_pass2)){ echo
    "Congratulations " . $_POST . " You may now proceed to the admin area !"; } else { echo "Userna....
  10. Php Simple Login Tutorial
    Learn how to make a simple login! (75)
    I have been quite busy lately, trying to design and code my site (far from done XD). And after
    having learned how to make a simple login, I will try to write my own tutorial, for you
    /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' /> the tutorial Step 1
    : The first step in designing a member system is to plan out exactly what you need. A common impulse
    among programmers is to jump right in and start coding. I'll be honest and admit that I'm
    guilty of this more so than anyone. However, since I'm in control of this conversation (y....
  11. Complete Login System
    With PHP + MYSQL (57)
    Its an complete login sistem made and tested by me and I think itwill be very usefull for people who
    are tryn to learn PHP. First, let's make register.php: CODE include("conn.php"); //
    create a file with all the database connections if($do_register){ // if the submit button were
    clicked if((!$name) || (!$email) || (!$age) || (!$login) || (!$password) || (!$password2)){ print
    "You can't let any fields in blank.\n"; // if the user did not put some field exit; } $name =
    stripslashes($name); $email = stripslashes($email); $age = stripslashes($age); $login = s....

    1. Looking for php, mysql, login, register, login, databases

Searching Video's for php, mysql, login, register, login, databases
See Also,
advertisement


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

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com