Logo
Simple User Login
Online Now: 1

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Snippets Functions Classes

Home | PHP Resources | MySQL Zipbase | Forums

Snippet Code
This little tutorial shows new users how to make a simple user login with a login form and database query.

login_page.php


<form action="verify.php" method="post">
    User Name:<br>
    <input type="text" name="username"><br><br>
    Password:<br>
    <input type="password" name="password"><br><br>
    <input type="submit" name="submit" value="Login">
</form>

verify.php


<?php
if(isset($_POST['submit'])){
    
$dbHost "localhost";        //Location Of Database usually its localhost
    
$dbUser "xxxx";            //Database User Name
    
$dbPass "xxxxxx";            //Database Password
    
$dbDatabase "db_name";    //Database Name
    
    
$db mysql_connect($dbHost,$dbUser,$dbPass)or die("Error connecting to database.");
    
//Connect to the databasse
    
mysql_select_db($dbDatabase$db)or die("Couldn't select the database.");
    
//Selects the database
    
    /*
    The Above code can be in a different file, then you can place include'filename.php'; instead.
    */
    
    //Lets search the databse for the user name and password
    //Choose some sort of password encryption, I choose sha256
    //Password function (Not In all versions of MySQL).
    
$usr mysql_real_escape_string($_POST['username']);
    
$pas hash('sha256'mysql_real_escape_string($_POST['password']));
    
$sql mysql_query("SELECT * FROM users_table 
        WHERE username='$usr' AND
        password='$pas'
        LIMIT 1"
);
    if(
mysql_num_rows($sql) == 1){
        
$row mysql_fetch_array($sql);
        
session_start();
        
$_SESSION['username'] = $row['username'];
        
$_SESSION['fname'] = $row['first_name'];
        
$_SESSION['lname'] = $row['last_name'];
        
$_SESSION['logged'] = TRUE;
        
header("Location: users_page.php"); // Modify to go to the page you would like
        
exit;
    }else{
        
header("Location: login_page.php");
        exit;
    }
}else{    
//If the form button wasn't submitted go to the index page, or login page
    
header("Location: index.php");    
    exit;
}
?>

users_page.php


<?php
session_start
();
if(!
$_SESSION['logged']){
    
header("Location: login_page.php");
    exit;
}
echo 
'Welcome, '.$_SESSION['username'];
?> 
 
Snippet Comments

Add Your Comment

admin
2010-08-20 00:00:00
Thanks everyone for all your input! I have updated the snippet with everyones suggestions! If you have any more suggestions, please feel free to let me know! I am always listening.
admin
2010-08-20 00:00:00
To return to the index page after you login, you just need to modify the following 2 lines:

header(\"Location: login_page.php\");
exit;
Ebbsfleet
2010-07-17 00:00:00
Is there a way of returning to the index after you login? its a great script as building the login needed exact function I have had problems at first but this is the best exp so far! thanks margret
Anonymous
2010-05-04 00:00:00
Do not use this snippet, it is very poorly coded.
UK Software companies
2009-12-09 00:00:00
Interesting, Keep up the good work... Thanks for bringing this up
CasTex
2009-11-23 00:00:00
Good work, I wish this has no vulnerabilities.
custom software
2009-11-04 00:00:00
Its a great tutorial, Its all fixed and working perfectly, Keep up the good work,
Human_Bagel
2008-08-22 00:00:00
Yes, sir, there are huge SQL injection holes, and storing passes as plaintext is a BAD idea!

I agree with the previous poster, mysql_real_escape_strting() is the best way to prevent SQL injection.

Also, if using PHP5, I would strongly recommend using PHP's hash() function with SHA-512, Whirlpool, or Ripemd5-160. All of those hashes are 512 bits in length, compared to md5()s 40.

Correcting those two will fix the prominent security holes.

Cheers! Hope it helps!
Ryan
2008-08-21 00:00:00
Updated!
Anonymous
2008-08-20 00:00:00
(That was me, the latest Anonymous poster)

One *last* thing. You're saving the passwords as plain text. BAD idea, especially with the SQL injection problems you have. Someone with the right knowledge can easily steal all your user's passwords.

I'd recommend using md5() to has the passwords (at very least md5, though sha1 would be nicer).

Try this: And make sure you md5() the passwords when you insert them into the database initially.
Anonymous
2008-08-20 00:00:00
Oh a few more things, in regards to good coding: The following have variables in quotes. You don't need the quotes, in fact it makes your script slow (albeit only slightly slower). Also, again with my suggestion about error messages. Don't let the visitor know it couldn't connect to the database. They don't need to know this information. Log it for your own use (write to a file) and just tell them there is a problem with the website and to try again later. Would be better off as:
Bond
2008-08-20 00:00:00
1. addslashes() is not sufficient enough to prevent SQL injection. Use mysql_real_escape_string(). 2. You are not enclosing your values in quotes, this just means they need to have a space in their submission to inject SQL. 3. You should not ever echo out mysql_error() to an end user. Log it for your own purposes, but show the user a generic error message. Your query would be better off like this:
gravlund
2007-05-08 00:00:00
Hi!

I'm getting this error message:
Unknown column 'Gravlund' in 'where clause'

what is wrong?
Admin
2007-03-26 00:00:00
Are you placing any HTML or Text that will be sent to the source code in the verify.php page? If so, remove it, the user will never see this page.
Newbie!
2007-03-21 00:00:00
I got pass that error now i gettin errors wit tha sessions
Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at D:\websites\template_96\HTML\verify.php:9) in D:\websites\template_96\HTML\verify.php on line 38

Anonymous
2007-03-21 00:00:00
No i didn't...im that new.....am i suppose change them....im using ODBC
Newbiewebby
2007-03-12 00:00:00
When i run the login_page.php page it goes to the verify.php page and on that page i get Fatal error: Call to undefined function mysql_connect() in D:\websites\DE PHP\verify.php on line 16


Help Please
Newbie!
Admin
2007-03-20 00:00:00
Did you change these?
$dbUser = "xxxx"; //Database User Name
$dbPass = "xxxxxx"; //Database Password
$dbDatabase = "db_name"; //Database Name ?>
Admin
2007-02-12 00:00:00
Fixed. Thank You.
bob
2007-02-12 00:00:00
not putting an 'exit' after a header("Location: blahblah") request is not a wise move. headers used in this way are not honoured until the script has finished - so effectively, all code after it can still run

Add Your Comment

 
Snippet Tools
Rate this Snippet:

Rate the difficulty level:

Request Snippet Update


Suggested Difficulty Level: Professional
Current Score: 2.63
Total votes: 308
Total Views: 12658

Other top snippets by admin:

1. JPG to ASCII Converter
2. Add (th, st, nd, rd, th) to the end of a number
3. Dynamic Page Content From Links
4. AJAX Quickie
5. Simple Image CAPTCHA

Search

Input key terms:
User Panel

User name:

Password:

Register And Post Your Own Snippets

Snippets On Watch

1.  Auth Class with (2.83 of 87)

2.  Test Please Delete (2.83 of 30)

3.  Return all repeated (3.64 of 72)

4.  Convert an integer (3.3 of 71)

5.  URL Shortening for (2.75 of 52)

6.  Monthly Content Sorting (3 of 45)

7.  Show String Trimmed (2.97 of 65)

8.  Human readable file (2.01 of 70)

9.  Randomize array values (2.8 of 82)

10.  Create a recursive (3.35 of 55)

New Snippets

1.  Parse RFC822 date (4 of 1)

2.  Dynamic Image Uploading (5 of 1)

3.  Spam Filter (0 of 0)

4.  Is Multiple (0 of 0)

5.  Base64 Encode / (0 of 0)

6.  URL Encode / (0 of 0)

7.  temp openbills (0 of 0)

8.  Php Iban Validator (0 of 0)

9.  Mysql Table Builder (0 of 0)

10.  File size of (1.75 of 4)

11.  Mail from your (1 of 1)

12.  OddEven Class (0 of 0)

13.  Detect if a (1 of 1)

14.  MB CopyMCF-DIR :: (5 of 1)

15.  Upper/Lower Case Accented (0 of 0)

16.  Zodiac Signs (3 of 1)

17.  Really useful code (2.5 of 2)

18.  Calculate Central European (0 of 0)

19.  Email Attachment (4 of 1)

20.  ImageMagick Image Upload (0 of 0)

21.  convert plain html (2 of 2)

22.  Tag Builder (3.25 of 4)

23.  Get Inserted ID (4.33 of 3)

24.  Watermark An Image (3.33 of 3)

25.  Check Prime Numbers (1.5 of 8)

Home | Forum | Free PHP Web Hosting | Contact | Terms & Conditions |  
Donate
PHPSnips.com - ©2010