Jul 27, 2008

Php Simple Login Tutorial - Learn how to make a simple login!

Free Web Hosting, No Ads > CONTRIBUTE > Tutorials
Pages: 1, 2, 3, 4, 5, 6, 7

free web hosting

Php Simple Login Tutorial - Learn how to make a simple login!

HmmZ
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

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 (yes!), you'll have it all planned out by reading through this before you even see any code.

What will you need to start?
First of all, you need a server that supports a CGI or Server-side language. For this tutorial, it's PHP. I won't be directing any attention to any other language at this time, so although the concepts will be similar, the code will be entirely different than something you might use in Perl or ASP. As a side note, it is possible to perform a member system simply using JavaScript, but it would not be remotely secure because JavaScript is client-side (thus able to be viewed by anyone), and even if you had a one-way encryption script it would not be feasible because of the pain of hard-coding usernames and encrypted passwords into the HTML document.

Second, at least for our purposes, you need a database. Preferably MySQL. PHP and MySQL go hand-in-hand, so a lot of servers tend to match the two up. Thus, since we're talking PHP, we may as well talk MySQL.

Third, you will need 4 blank PHP web pages entitled: register.php, login.php, members.php, and logout.php. After you have these pages created and open, we're ready to start.

Step 2: Database

If we want to design a members system, we'll need a database. So all we need to do in this step is to create the table we will use to manage the user's login information. Note that the schema we use here is quite simple, and is only simplified to help you see how it works.

CODE
Name the table "dbUsers." It will need 4 fields:

[I]Name             Type                 Addition[/I]
id                  int(10)              Primary Key, AUTO_INCREMENT
username            varchar(16)          Unique
password            char(16)          
email               varchar(25)


Once you've made the database table, you're ready to design and code the registration page.

Create a File to Connect to your Database

Create a new file and name it dbConfig.php. This file will contain the PHP code that will connect to the MySQL database, and select the correct database. Make sure you have added users to your MySQL database with read/write or admin access, then place this type of code into the dbConfig.php file:

CODE
<?
// Replace the variable values below
// with your specific database information.
$host = "localhost";
$user = "UserName";
$pass = "Password";
$db   = "dbName";

// This part sets up the connection to the
// database (so you don't need to reopen the connection
// again on the same page).
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo "Error connecting to database.\n";
}

// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>


Step 3: Register

register.php

On your registration page, you need to create a web form that will allow the user to plugin a username, password, and their e-mail address. Then, also on your page, add code that runs only when information has been passed via the form. Finally, display a "Registration Successful!" message to the user.

CODE
<?php

// dbConfig.php is a file that contains your
// database connection information. This
// tutorial assumes a connection is made from
// this existing file.
include ("dbConfig.php");


//Input vaildation and the dbase code
if ( $_GET["op"] == "reg" )
 {
 $bInputFlag = false;
 foreach ( $_POST as $field )
  {
  if ($field == "")
   {
   $bInputFlag = false;
   }
  else
   {
   $bInputFlag = true;
   }
  }
 // If we had problems with the input, exit with error
 if ($bInputFlag == false)
  {
  die( "Problem with your registration info. "
   ."Please go back and try again.");
  }

 // Fields are clear, add user to database
 //  Setup query
 $q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
  ."VALUES ('".$_POST["username"]."', "
  ."PASSWORD('".$_POST["password"]."'), "
  ."'".$_POST["email"]."')";
 //  Run query
 $r = mysql_query($q);
 
 // Make sure query inserted user successfully
 if ( !mysql_insert_id() )
  {
  die("Error: User not added to database.");
  }
 else
  {
  // Redirect to thank you page.
  Header("Location: register.php?op=thanks");
  }
 } // end if


//The thank you page
elseif ( $_GET["op"] == "thanks" )
 {
 echo "<h2>Thanks for registering!</h2>";
 }
 
//The web form for input ability
else
 {
 echo "<form action=\"?op=reg\" method=\"POST\">\n";
 echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
 echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16\"><br />\n";
 echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
 echo "<input type=\"submit\">\n";
 echo "</form>\n";
 }
// EOF
?>


Step 4: Login

login.php

Now in PHP, first we need to check the username and password against the information stored in the database. Since when the user registered, we encrypted their password using the MySQL PASSWORD() function, we re-encrypt the password the user supplied in the login form and cross-check this with the existing value in the dBase. If login information is O.K., then we need to use sessions to store the user's ID so they can access member-only content.

CODE
<?php
session_start();
// dBase file
include "dbConfig.php";

if ($_GET["op"] == "login")
 {
 if (!$_POST["username"] || !$_POST["password"])
  {
  die("You need to provide a username and password.");
  }
 
 // Create query
 $q = "SELECT * FROM `dbUsers` "
  ."WHERE `username`='".$_POST["username"]."' "
  ."AND `password`=PASSWORD('".$_POST["password"]."') "
  ."LIMIT 1";
 // Run query
 $r = mysql_query($q);

 if ( $obj = @mysql_fetch_object($r) )
  {
  // Login good, create session variables
  $_SESSION["valid_id"] = $obj->id;
  $_SESSION["valid_user"] = $_POST["username"];
  $_SESSION["valid_time"] = time();

  // Redirect to member page
  Header("Location: members.php");
  }
 else
  {
  // Login not successful
  die("Sorry, could not log you in. Wrong login information.");
  }
 }
else
 {
//If all went right the Web form appears and users can log in
 echo "<form action=\"?op=login\" method=\"POST\">";
 echo "Username: <input name=\"username\" size=\"15\"><br />";
 echo "Password: <input type=\"password\" name=\"password\" size=\"8\"><br />";
 echo "<input type=\"submit\" value=\"Login\">";
 echo "</form>";
 }
?>


Step 5: Members Area

members.php

Now that the user has logged in successfully, and has his id, username, and login stored in session variables, we can start working with member-only content. A major thing to remember is that any page you want to carry session data over to you must declare a session_start(); at the top of your code.

CODE
<?php
session_start();

if (!$_SESSION["valid_user"])
{
// User not logged in, redirect to login page
Header("Location: login.php");
}

// Member only content
// ...
// ...
// ...

// Display Member information
echo "<p>User ID: " . $_SESSION["valid_id"];
echo "<p>Username: " . $_SESSION["valid_user"];
echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);

// Display logout link
echo "<p><a href=\"logout.php\">Click here to logout!</a></p>";
?>


Step 6: Logout

logout.php

Ah, although it would be nice if our user's never left our web sites, we should give them to opportunity to log out and destroy the session variables if they so choose. It's quite easy to do, and you can just copy and paste this one.

CODE
<?php
session_start();
session_unset();

session_destroy();
// Logged out, return home.
Header("Location: index.php");
?>


That's about it!. I used many simple examples hoping that you will learn how the internal systems work so you can expand on them and design a system that's just right for your needs. Have fun! ph34r.gif

 

 

 


Reply

Dragonfly
Thanks, I have both php and MySQL installed in my laptop. I think that steps you've mentioned here are easy to follow and easy to understand. I'm beginner in PHP and have been following closely any topic related to php.

Hope I can implement the above code and make use of it in the future. I should start testing it in my local computer. Thanks.

Reply

HmmZ
Thanks for the positive feedback, I haven't implemented, nor tested the code myself (just checked to see if it actually showed up), so if any problems persist, tell me about it, so I can adjust the code hoping it could fix it, if there is a flaw and you know the solution, replying with both the flaw and the solution is always welcome of course smile.gif

Reply

bjrn
If someone is planning on implementing something like this here on their Trap17 account, I suggest you use Pear. When you have people logging into things on your site, you want to make sure that there is no possibility of sql injection. Pear's DB prepared statement function prevents SQL injection attacks. It's very handy.

Something like this could work
CODE
require_once("PEAR.php");
require_once("DB.php");
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');
$data = array($_POST['username'], $_POST['password'], $_POST['email']);
$conn->execute($preparedstatement, $data);

Please note that I haven't tested this code, it should work, but there might be some stupid typo somewhere. smile.gif

 

 

 


Reply

karlo
QUOTE(bjrn @ Mar 4 2005, 06:33 AM)
If someone is planning on implementing something like this here on their Trap17 account, I suggest you use Pear. When you have people logging into things on your site, you want to make sure that there is no possibility of sql injection. Pear's DB prepared statement function prevents SQL injection attacks. It's very handy.

Something like this could work
CODE
require_once("PEAR.php");
require_once("DB.php");
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');
$data = array($_POST['username'], $_POST['password'], $_POST['email']);
$conn->execute($preparedstatement, $data);

Please note that I haven't tested this code, it should work, but there might be some stupid typo somewhere. smile.gif
*


What are those? $conn->execute? How can I use "Classes"? how can I create my own? Where to use them? what's pear? do you know a tutorial for the classes/objects and pear? I thought to fetch the results, you must use a loop function. why did you only use "if" function?

Reply

mahesh2k
That was an exceelnt login tutorial from you,i m looking for some of tutorials like this.anyway can you explain me
code below
CODE
echo "<p>User ID: " . $_SESSION["valid_id"];
echo "<p>Username: " . $_SESSION["valid_user"];
echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);

code end

pls explain

Reply

HmmZ
Ouch, a double post smile.gif

as for the code, the login script uses sessions, to store user id's and info to be able to show some stats of the user next time he logs on.

Besides that it looks nice, it also has a security feature, when a user sees the last logged in time, he can see if someone else has been on his account.

Hope that helped you explain?smile.gif

Reply

bjrn
I'll try to explain the code

This imports the PEAR things to your script, PEAR.php and DB.php are standard scripts, available to everyone. Not something you have to upload or make yourself.
CODE
require_once("PEAR.php");
require_once("DB.php");


This makes sure you get a nice error message in case things go wrong
CODE
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");


This makes an connection object. You have to substitute 'dbuser' for your db username, same for dbpassword and dbname. I just put them there to show what goes where. Oh, and if you are connecting to a DB on another server you of course have to replace 'localhost' with the server ip.
CODE
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");


Now you can use your connection object. This piece calls the prepare() function in the connection object and stores the resulting statement.
CODE
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');


This is an array with values, the values will replace the '?'s in the preparedstatament.
CODE
$data = array($_POST['username'], $_POST['password'], $_POST['email']);


And finally you call the execute() function the the connection object has with the prepared statement and the array of values as parameters.
CODE
$conn->execute($preparedstatement, $data);



I don't really know much about PEAR. What I know I've learned from the official PEAR site and from Googling for specific bits.

Reply

HmmZ
Why is PEAR needed with this script, i don't think ive ever even heard of PEAR blink.gif

The thing is, the script should most likely work without the PEAR thing won't it? If so, why make it more more difficult, it's supposed to be a "simple" login system, I'm currently working on my own complete membersystem, with pms and such, but I will probably keep it to myself, something has to be unique about my future community wink.gif

Reply

NotoriousZach
Hey thanks for the great tutorial....I made mine where only people I have verified can see it......To do that I just added a feild in the database

On the new feild
CODE
Name = verified
default=0


In login.php add this

CODE
."AND `verified`=1 "


In between

CODE
."AND `password`=PASSWORD('".$_POST["password"]."') "


AND

CODE
."LIMIT 1";


Hope you guys enjoy....And thanks again for the great script.

Reply

Latest Entries

Sefru
QUOTE(d0n0t.p4n1c @ Jul 1 2007, 05:43 PM) *
Everything except the login worked for me here. It says "Sorry, could not log you in. Wrong login information." when I try to login, even when I KNOW I'm using the right username/password combo. Any help?

I'm having exactly the same problem. I'm 100% that I'm writing them right, I have tried to register and login many times but everytime when I try to login it just says that I have wrong login information. I have checked my database and every user I have registered is there.

Reply

games4u
I had been breaking my head on this, not to implement it on my site. Actually one of my friends challenged me to create such a code. And this was really helpful. I hope you wouldn't mind if I copied it wink.gif

Thank you...

Reply

Kennethzzz
QUOTE(flashy @ Apr 25 2008, 06:11 PM) *
Ahh - i know your problem, it happens in cookies too - when you send
CODE
SESSION_START()


You need to place it before everything else in your page - so like
CODE
<?php
blablabla
?>
<html>...


Like that - hope it helps wink.gif


Tried doing that, but error remains.

Reply

flashy
QUOTE(Kennethzzz @ Apr 25 2008, 07:36 AM) *
Hi, i'm new to php. Actually i was handed with a school project which is to create a e-commerce site. However i have no basic knowledge on php. Right now i'm actually trying to create a login/register page. I tried out your tutorial in the 1st page of this thread but ends up with errors here and there. So if you could provide me with more understanding on these coding, i'll be gratful.

1) I keep getting this error when trying to register... kept trying.. but all it came out was "Error: User not added to database."

2) I have tried creating a user n pass in the database (mysql) and then went on to tried to login.. but all i get was "Sorry, could not log you in. Wrong login information."

And also on top of the login box n password box, there are a few error message:

3) On the members page as well:

4) Logout page display:
Notice from rvalkass:

Quotes added around error messages.


Ahh - i know your problem, it happens in cookies too - when you send
CODE
SESSION_START()


You need to place it before everything else in your page - so like
CODE
<?php
blablabla
?>
<html>...


Like that - hope it helps wink.gif

Reply

flashy
ahh - thats how you use sessions, i have been using cookies to use to login scripts - no other tutorial gives me info on how to use SESSIONS, great tut, all i really needed to know was the sessions lol. Thanks smile.gif

Reply



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*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Pages: 1, 2, 3, 4, 5, 6, 7
Recent Queries:-
  1. php login script tutorial - 0.68 hr back. (1)
  2. create simple login - 2.57 hr back. (1)
  3. how to make a php login - 4.48 hr back. (1)
  4. php admin log in tutorial - 7.28 hr back. (1)
  5. php login tutorials - 8.60 hr back. (1)
  6. php tutorial login - 10.97 hr back. (1)
  7. "login by php tutorial" - 16.49 hr back. (1)
  8. php login tutorial - 0.32 hr back. (4)
  9. php simple login - 18.29 hr back. (1)
  10. how to make a login script - 23.16 hr back. (1)
  11. how to make a login page form - 24.00 hr back. (1)
  12. how to make a login page - 24.07 hr back. (1)
  13. simple php login tutorial - 24.73 hr back. (1)
  14. how to make login page with php - 25.27 hr back. (1)
Similar Topics

Keywords : php, simple, login, learn, make, simple, login

  1. To Automatically Run Command When Login / Logoff
    (3)
  2. Simple Php Login And Registration System
    (10)
    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
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html
    xmlns="http://www.w3.org/1999/xhtml"> <head> <meta
    http-equiv="Content-Type" content="text/ht....
  3. Flatfile User Login/signup
    Uses text files only (compatable with forums and message system) (24)
    With this tutorial, you will learn how to create a textfile login script. This user membership
    script is for use also with my forums and message system scripts. I will also give you the scripts
    to make it so that people can change their profiles. Ok, The first thing we need to do is make the
    database. To do this, create a blank text file called 'userdata.txt' , make sure it is ALL
    LOWER-CASE. Edit this file and put
    '**username|##|password|##|email|##|rank|##|userid|##|name|##|picture**'. This will not be
    used, however it will give you an idea of how the....
  4. Automatic Login
    in WinXP (5)
    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. Simple Login In Visual Basic 6
    user interaction example trough login programm (6)
    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 ....
  6. How To Put A Phpbb Login Box On Your Main Site.
    Code and .php included!!! (18)
    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 // <form
    action="/phpBB2/login.php" method="post" target="_top"> <table
    width="25%" cellspacing="2" cellpadding="2" border="0"
    align="center">  <tr> <td align="left"
    class="nav"><a href="/phpBB2/index.php" class="nav">Prank Place
    Forum Index</a></td>....
  7. Php/mysql Login/register
    Tutorial for login with databases. (2)
    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 ....
  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 kShoutBo....
  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 . " ....
  10. Complete Login System
    With PHP + MYSQL (56)
    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....

    1. Looking for php, simple, login, learn, make, simple, login

Searching Video's for php, simple, login, learn, make, simple, login
advertisement



Php Simple Login Tutorial - Learn how to make a simple login!



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE