Welcome to Dream.In.Code
Getting Help is Easy!

Join 132,486 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,197 people online right now. Registration is fast and FREE... Join Now!




Basic Login Script with PHP

2 Pages V  1 2 >  
Reply to this topicStart new topic

> Basic Login Script with PHP, A rudimentary login script tutorial aimed at those looking to learn ho

Rating  4
akozlik
Group Icon



post 22 May, 2008 - 08:54 AM
Post #1


First, I accidently posted this to PHP Programming Help, and then realized I put it in the wrong forum. It's now been submitted to tutorials for review. Sorry about that.

This tutorial will attempt to teach you how to build a rudimentary login system for your site. It's assumed that you understand MySQL concepts, as well as session variables and form handling.

To begin, you will need to create a new table in your database named 'users'. In this database create three new fields 'id' (primary key), 'username', 'password'. You can add more fields as you need them later. For now we're just going to worry about checking for an existing username and password combination.

Next, create your html page with the login form. Below is a quick sample of a form you can build.

CODE


<form action="checkLogin.php" method="post">
     <table>
          <tr>
               <td>Username: </td>
               </td><input type="text" name="user"></td>
          </tr>
          <tr>
               <td>Password: </td>
               <td><input type="password" name="pass"></td>
          </tr>
     </table>
</form>


Please notice that we are using the POST method for the form. This is to ensure that the username and password aren't passed as URL parameters, which is a security flaw for obvious reasons.

Next we'll code our checkLogin.php page. This page is going to select all the rows with matching username and password combinations. There should only be one row that does so, which is our valid row. I'm not going to cover data integrity here, but you'll definitely want to sanitze your data from SQL injection. Keeping in the theme of my tutorials though, I only want to focus on the task at hand.

CODE


<?php
// checkLogin.php

session_start(); // Start a new session
require('conn.php'); // Holds all of our database connection information

// Get the data passed from the form
$username = $_POST['user'];
$password = $_POST['password'];

// Do some basic sanitizing
$username = stripslashes($username);
$password = stripslashes($password);

$sql = "select * from users where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );

$count = 0;

while ($line = mysql_fetch_assoc($result)) {
     $count++;
}

if ($count == 1) {
     $_SESSION['loggedIn'] = "true";
     header("Location: loginSuccess.php"); // This is wherever you want to redirect the user to
} else {
     $_SESSION['loggedIn'] = "false";
     header("Location: loginFailed.php"); // Wherever you want the user to go when they fail the login
}

?>


You may want to consider posting the form to PHP_SELF for basic error handling, or you can pass error messages through the url parameter, it's up to you. As I said, this is just a rudimentary example of how to set up a basic user login script. From here, if you want to check and see if a user is logged in, just put the following at the top of a page.

CODE


<?php
session_start();
if ($_SESSION['loggedIn'] != "true") {
     header("Location: http://www.whatever.com/login.php");
}

?>


Naturally there are many different ways to achieve the same thing in PHP. This script is great for basic logins, but may not be what you need for something more complex. Adapt it to your needs or just use it as a place to begin learning. Hope everything is clear with the instructions. As usual, questions and comments are more than welcome. Take care.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

akozlik
Group Icon



post 23 Jun, 2008 - 08:28 PM
Post #2
I don't know what I was thinking when I wrote this. The following code

php

while ($line = mysql_fetch_assoc($result)) {
$count++;
}


can be replaced with

php

$count = mysql_num_rows($result);


with the same effect. Either or.
Go to the top of the page
+Quote Post

chillyb
*



post 8 Jul, 2008 - 09:00 AM
Post #3
don't use this -- as it can easily be a victim to SQL injection. You must make sure any quotes are escaped (and he goes as far as getting rid of PHP trying to protect you by stripping them away)
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 8 Jul, 2008 - 09:04 AM
Post #4
QUOTE(chillyb @ 8 Jul, 2008 - 01:00 PM) *

don't use this -- as it can easily be a victim to SQL injection. You must make sure any quotes are escaped (and he goes as far as getting rid of PHP trying to protect you by stripping them away)



I plainly state in the tutorial:

QUOTE

I'm not going to cover data integrity here, but you'll definitely want to sanitze your data from SQL injection. Keeping in the theme of my tutorials though, I only want to focus on the task at hand.


NOTE: Use mysql_real_escape_string() instead of stripslashes().

The purpose of this tutorial was for a basic understanding of one login technique. I made sure to note that you should research data santization. There's a great tutorial on DIC for just that.

This post has been edited by akozlik: 8 Jul, 2008 - 09:06 AM
Go to the top of the page
+Quote Post

mocker
Group Icon



post 8 Jul, 2008 - 10:43 AM
Post #5
Nooooo.. no offense, but 'simple login scripts' are one of the reasons php gets a lot of hate. PHP provides an easy starting point for amateur and hobby programmers, which is by itself not a bad thing. However, the level of programmers that would use this tutorial are not going to know much about security, and are probably not going to know what you mean just by stating 'I'm not going to cover data integrity here'.

Honestly, posting insecure simple login scripts as a tutorial just hurts beginning programmers. Unless for some reason you don't care about people accessing your script, your hosting account and your database, this is bad. A login script CAN be done easily, but a SECURE login script has several more layers to it.

1. Storing passwords as plain text is BAD. One security flaw or vulnerability and the intruder will know the passwords to ALL your users accounts. While not only bad for your server, they may also use that login elsewhere, which can mean your users other accounts are now vulnerable just because they trusted you to make a secure login system. The easiest way to secure this is to only store the md5 hash of the password, and instead of checking the password, check the md5 hash of the submitted password to the hash that is stored in the database.

MySQL injection was already mentioned. There is no excuse to get lax on checking for that, unless again, for some reason you could care less about your database and hosting account.


Another vulnerabilty here, which is slightly more obscure and uncommon, is guessing session IDs, or session hijacking (http://en.wikipedia.org/wiki/Session_hijacking) . A way to help prevent this is to store the IP of the login and the session ID, and then make sure all subsequent requests with that ID are coming from there.


Helping people out with tutorials is great, but security should not be an afterthought. As a web hosting server admin I used to have to constantly clean up hacked up accounts because someone thought they'd learn how to program and found something like this and just copy pasted, then a little later their account was hacked and had 50 hack scripts running from it.
Go to the top of the page
+Quote Post

woodjom
*



post 2 Aug, 2008 - 07:10 AM
Post #6
Dude chill out.....BEGINNERS GUIDE....quit jacking on the Mod dude....I am using the script template he supplied and am supplying sql injection measures.....I personally think this quite a good code snip....but albeit you might want to put the legal mumbo jumbo in HUGE BOLD LETTERS. Advising that any user of this code needs to do more research on SQL injections and the preventative measures

2 THUMBS WAY UP on the snippet icon_up.gif icon_up.gif
Go to the top of the page
+Quote Post

Moshambi
**



post 14 Aug, 2008 - 01:33 PM
Post #7
ok well i tried this tutorial and i keep getting these errors:

CODE

Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\Documents and Settings\mosh.AZN-0604362DF83\Desktop\xampp-win32-1.6.7\xampp\htdocs\checkLogin.php on line 16

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\Documents and Settings\mosh.AZN-0604362DF83\Desktop\xampp-win32-1.6.7\xampp\htdocs\checkLogin.php on line 16
Access denied for user 'ODBC'@'localhost' (using password: NO)


I have no idea how to connect to my database...im guessing thats what the problem is...but any help is appreciated.

Thanks
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 14 Aug, 2008 - 01:38 PM
Post #8
Yeah that error means you're using the wrong username and password. If you're using XAMPP I believe the default username is root and the password is blank.

php


$username = "root";
$password = "";
$host = "localhost";

$database = "your database name"

$conn = mysql_connect($host, $username, $password) or die ( "Could not connect: " . mysql_error() );

$database = mysql_select_db($database, $conn) or die ("Could not select database: " . mysql_error() );



That should connect you. Just adapt it for your needs.
Go to the top of the page
+Quote Post

Moshambi
**



post 14 Aug, 2008 - 01:48 PM
Post #9
Ok cool that worked perfectly...thank you for your quick response time and good tutorial you have here!
Go to the top of the page
+Quote Post

akozlik
Group Icon



post 21 Aug, 2008 - 07:30 AM
Post #10
I've been reading the forums and I realized I might not have been clear about requiring a conn.php file.

This code

php

require("conn.php");


Will run a PHP script named conn.php. This is basically your database connections file that will be used across the many pages you develop. Put the following in a file and save it as conn.php

php


$host = "hostname"; // Change this to your host name. It may be localhost
$username = "username"; // Changes this to your database username
$password = "password"; // Changes this to your database password
$database = "database_name"; // Change this to your database name

$conn = mysql_connect($host, $username, $password) or die ( mysql_error() );

$database = mysql_select_db($database, $conn) or die ( mysql_error() );



That will connect you to your database. Hope that clears some issues up.
Go to the top of the page
+Quote Post

pr4y
Group Icon



post 27 Sep, 2008 - 06:50 PM
Post #11
Despite the hate from some other people, I actually found this script helpful. Obviously someone that doesn't know anything about PHP wouldn't be able to use this script in a practical sense for the simple reason that they would have nothing to do with it.

Example:

Script kiddie comes along and finds CUT + PASTE tutorial on a login form. Thinks to himself... HEY I could create a forum from this script! Let me just copy and paste this THEN code an entire forum architecture from scratch!

whatsthat.gif Not going to happen. This tutorial is nice and basic enough so that learning PHP coders can fill in the blanks. You know, cross the t's and dot the i's ?


Nice tutorial, a good starting point for beginning programmers interested in web development!
Go to the top of the page
+Quote Post

fallenOne09
*



post 9 Oct, 2008 - 07:24 AM
Post #12
Thank you for posting your code it was a great help to me!!!
but what is the things that you should put in conn.php because it returns no database selected.???
plsss help me
Go to the top of the page
+Quote Post


2 Pages V  1 2 >
Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/22/08 03:43PM

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month