/* Login Functions */
function login($usr, $pass) {
	$sql = "SELECT * FROM users WHERE usrNAME = '$usr' AND usrPASS = '$pass'";
	$query = mysql_query($sql);
	$row = mysql_fetch_assoc($query);
	
	if (mysql_num_rows($query) == 1) {
                // in here is what it should do if successful 
	} else {
		// in here is what it should do if faild
	}
}

// header
<?php 
if (($_POST['submit'])){
	login($_POST['username'], $_POST['password']);
}
?>

// somewhere in the body section
<?php
        if($_SESSION['loged'] == "false") {
                echo '
                    <div class="loginfailed" align="center">Login Failed!</div>
                ';	
            }
        ?>
        <form action="#" method="POST">
          Username:<br />
          <input name="username" type="text" tabindex="1" maxlength="45" class="inputbox" /><br />
          Password:<br />
          <input name="password" type="password" tabindex="2" maxlength="55" class="inputbox" /><br />
          <div align="center"><input type="submit" name="submit" value="Login" tabindex="3" class="inputbutton" /></div>
        </form>

Recommended Answers

All 18 Replies

Besides the immediately glaring issues I see:

  • The session isn't started in your code example e.g. session_start() isn't called.
  • $_POST is not defined when you just load the form.

That query is also extremely vulnerable to SQL injection.
If you take the query: $sql = "SELECT * FROM users WHERE usrNAME = '$usr' AND usrPASS = '$pass'"; And a user submits admin'; /* into the user field and whatever they want for the password. This would make the resulting query SELECT * FROM users WHERE usrNAME = 'admin'; /*' AND usrPASS = 'none' That would effectively search for a user with the username "admin" and the /* would start a multi line comment that just ignores the rest of the query including the check for the password.

Now normally you'd have the obscurity of the attacker not being able to see the query you're running but if you do some reading on SQL injection you'll begin to understand what an attacker will look for and how they will go about attacking your inputs.

To reduce this you should look into using at the minimum sprintf to set specific variable types. As well as escaping quotes etc. e.g. mysql_real_escape_string (varies depending on your extension of choice)

If you wanted to take it a step further and I highly suggest it, start using prepared statements to handle this scenario.

thanks for the quick reply,

Ill edit my code.. I just i took this code form a larger project and didn't think of copying those little things...

Thanks, whould you show me how to make it ignore the '; /* part to just use the admin part...

This is also used in another project like i sed but now that you told me somethings please help me...

Thanks,
Marais

-Marais

Personally I like PDO because the code is portable across all databases that PDO supports. There is more info on PDO prepared statements: http://www.php.net/manual/en/pdo.prepare.php

<?php

/**
 * Takes a user's credentials and queries the database to ensure the user is
 * a valid user and is allowed to access our system.
 *
 * @param PDO $dbh
 * @param string $usr
 * @param string $pass
 */
function login( PDO $dbh, $usr, $pass) {
	$sql = "SELECT * FROM users WHERE usrNAME = :user AND usrPASS = :pass";
	$sth = $dbh->prepare( $sql );
	$sth->execute( array(':user' => $usr, ':pass' => $pass));
	
	$rowset = $sth->fetchAll();
	if( count($rowset) == 1 ){
		// Logged in
	} else {
		// Not logged in
	}
}

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

login($dbh, $_POST['username'], $_POST['password']);

If you don't have PDO available to you, you can also use MySQLi which also supports prepared statements: http://www.php.net/manual/en/mysqli.prepare.php It uses a very similar syntax too.

I hope this helps, I'm more than happy to expand on it as necessary.

thanks, could you please expand on it i dont know what a PDO is so can you please give me code which uses mysqli... Im kinda new to php!

Thanks,
Marais

Hang on i got it working but now i want to get the record id to a session variable:
eg:

<?php $_SESSION['id'] = $row['id']; ?>

Is this possible? And is session the best way to save the id for use trough out my site?

Thanks,
Marais

Sessions is really the only way to persist data over multiple requests in php. So yes in my opinion sessions would be the best way to use it over multiple requests.

Thanks!
From the query you gave me could you please tell me how i can add the id record to the session{'id'] thanks.

Thanks,
Marais

-marases

Assuming you're using the PDO code I posted.

To iterate over the results of the query, the variable $rowset would contain a multidimensional array.

In theory your query should only return 0 or 1 rows, and to ensure this it should probably have a LIMIT 1 added to the end of it.

$sql = "SELECT * FROM users WHERE usrNAME = :user AND usrPASS = :pass LIMIT 1";

With that being said, to iterate over the results its just a matter of:

if( count( $rowset ) == 1 ){
     //We only have exactly 1 row returned.
     $_SESSION['id'] = $row[0]['id'];
}

If you need to iterate over multiple rows:

if( count( $rowset ) ){
    foreach( $rowset as $row ){
         //Do something for each row
         // echo $row['columnName'];
    }
}

-evstevemd

While I think session hijacking/fixation is a concern in the grand scheme of things, the sql injection that was present in this example initially was far easier to exploit even at a novice level. Regardless a nice link with a very easy to follow explanation of the topic and a way to reduce the risk.

thanks guys this code worked!

Whould you please explain to me what a PDO is?

Thanks,
Marais

hey guys i have little problem... That code:

$_SESSION['id'] = $row[0]['id'];

did not work i think i know what the problem is; is it the $row because i cant see where its coming from...

Thanks,
Marais

That would be my fault.

if( count( $rowset ) == 1 ){
     //We only have exactly 1 row returned.
     $row = $rowset[0];
     $_SESSION['id'] = $row['id'];
}

That should fix it.

thanks, this worked.. THANK YOU SO MUCH! Sorry im still learning PHP!

Hey guys, im having so much troubles... PDO is not yet installed on my host whould there be another option and can i get code from somewhere?

I tested my site on xampp with php 5.3.3 and phpmyadmin 3.3.7 installed and it worked but my host has a bit older version.

Thanks,
Marais

That is a shame PDO is not installed on your hosting server.
You have a couple options:

  1. MySQLI w/Prepared Statements
  2. MySQLi wo/Prepared Statements
  3. MySQL w/mysql_real_escape_string

Personally I favor MySQLi over MySQL.

Look at the following php.net manual pages:
http://www.php.net/manual/en/book.mysqli.php
http://www.php.net/manual/en/mysqli.connect.php
http://www.php.net/manual/en/mysqli.prepare.php
http://www.php.net/manual/en/class.mysqli-stmt.php

There are enough complete examples there that you should be able to port that small section of code to MySQLi with little effort.

Essentially your process will be:

  1. Connect to the database server
  2. prepare the statement (if you're using prepared statements still)
  3. execute the statement/query
  4. iterate over the results

Hows this i customized??

Is mysql any different to myqsli?

Here is my code:

<?php
session_start();

define('ROOT', $_SERVER["SITE_HTMLROOT"].'/');

define('db_user', 'username');
define('db_pass', 'password');
define('db_name', 'database name');

function openMysql(){
	mysql_connect("127.0.0.1", db_user, db_pass) or die("Could not connect to the server: " . mysql_error());
	mysql_select_db(db_name);	
}

openMysql();

class loginsystem {
	function mss($value) {
		return mysql_real_escape_string(trim(strip_tags($value)));	
	}

	function prepare($value) {
		return mysql_query($value);	
	}
	function execute($value) {
		return mysql_fetch_array($value);	
	}
}

function login($usr, $pass) {
	$loginsystem = new loginsystem;
	$username = $loginsystem->mss($usr);
	$password = $loginsystem->mss($pass);

	
	$sql = "SELECT * FROM users WHERE `username` = '".$username."' AND `password` = '".$password."' LIMIT 1";
	$query = $loginsystem->prepare($sql);
	$row = $loginsystem->execute($query);
	
	if(mysql_num_rows($query) == 1 ){
		$_SESSION['familyid'] = $row['Family_Code'];
		$_SESSION['loggedin'] = true;
		print "<meta http-equiv=\"refresh\" content=\"0;URL=".ROOT."membersarea/index.php\">";
	} else {
		$_SESSION['loggedin'] = false;
		print "<meta http-equiv=\"refresh\" content=\"0;URL=".ROOT."index.php\">";
		echo "<script type='text/javascript'>alert('Please try again!')</script>";

	}
}
	
login($_POST['username'], $_POST['password']);
?>

Thanks,
Marais

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.