• (3 Pages)
  • +
  • 1
  • 2
  • 3

Basic Login Script with PHP A rudimentary login script tutorial aimed at those looking to learn ho Rate Topic: ***-- 2 Votes

#1 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Post icon  Posted 22 May 2008 - 09:54 AM

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.


<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.


<?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.


<?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.

Is This A Good Question/Topic? 2
  • +

Replies To: Basic Login Script with PHP

#2 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 23 June 2008 - 09:28 PM

I don't know what I was thinking when I wrote this. The following code

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



can be replaced with

$count = mysql_num_rows($result);



with the same effect. Either or.
Was This Post Helpful? 0
  • +
  • -

#3 chillyb  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 08-July 08

Posted 08 July 2008 - 10:00 AM

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)
Was This Post Helpful? 0
  • +
  • -

#4 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 08 July 2008 - 10:04 AM

View Postchillyb, on 8 Jul, 2008 - 01:00 PM, said:

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: 08 July 2008 - 10:06 AM

Was This Post Helpful? 2
  • +
  • -

#5 mocker  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 50
  • View blog
  • Posts: 466
  • Joined: 14-October 07

Posted 08 July 2008 - 11:43 AM

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.
Was This Post Helpful? 2
  • +
  • -

#6 woodjom  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 29
  • View blog
  • Posts: 549
  • Joined: 08-May 08

Posted 02 August 2008 - 08:10 AM

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 :^: :^:
Was This Post Helpful? 0
  • +
  • -

#7 Moshambi  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 8
  • View blog
  • Posts: 280
  • Joined: 20-November 07

Posted 14 August 2008 - 02:33 PM

ok well i tried this tutorial and i keep getting these errors:

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
Was This Post Helpful? 0
  • +
  • -

#8 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 14 August 2008 - 02:38 PM

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.


$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.
Was This Post Helpful? 0
  • +
  • -

#9 Moshambi  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 8
  • View blog
  • Posts: 280
  • Joined: 20-November 07

Posted 14 August 2008 - 02:48 PM

Ok cool that worked perfectly...thank you for your quick response time and good tutorial you have here!
Was This Post Helpful? 0
  • +
  • -

#10 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 21 August 2008 - 08:30 AM

I've been reading the forums and I realized I might not have been clear about requiring a conn.php file.

This code

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


$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.
Was This Post Helpful? 0
  • +
  • -

#11 pr4y  Icon User is offline

  • Location: 127.0.0.1
  • member icon

Reputation: 35
  • View blog
  • Posts: 621
  • Joined: 19-September 08

Posted 27 September 2008 - 07:50 PM

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!

^^ 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!
Was This Post Helpful? 0
  • +
  • -

#12 fallenOne09  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-October 08

Posted 09 October 2008 - 08:24 AM

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
Was This Post Helpful? 0
  • +
  • -

#13 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 09 October 2008 - 08:32 AM

View PostfallenOne09, on 9 Oct, 2008 - 11:24 AM, said:

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


Make sure you read the comments and make the changes to the script that I wrote about. The original script had some security issues that everyone kept talking about. It was only meant as a very basic example of how to accomplish something, and not for use in a live site. Specifically, make sure you replace stripslashes() with addslashes(), and use mysql_real_escape_string()

That being said, look in the comments before yours, and you'll see the answer to your question about the conn.php file.
Was This Post Helpful? 0
  • +
  • -

#14 fallenOne09  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 09-October 08

Posted 09 October 2008 - 08:38 AM

Im sorry about that!!! i tried all your suggestions but it still does not work in conn.php it still says no database selected!!
Plsss i really need your help!!!
Was This Post Helpful? 0
  • +
  • -

#15 akozlik  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 90
  • View blog
  • Posts: 797
  • Joined: 25-February 08

Posted 09 October 2008 - 08:40 AM

View PostfallenOne09, on 9 Oct, 2008 - 11:38 AM, said:

Im sorry about that!!! i tried all your suggestions but it still does not work in conn.php it still says no database selected!!
Plsss i really need your help!!!


Did you create the database at all? You won't be able to select a database unless you create it. Also, make sure that the conn.php holds your details, not mine. Start a new thread in the PHP section and I'll help you there. I don't want to bloat this thread.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3