Loans - Ali Aboutaam - MySpace Layouts - Online Loans - Farming

PDA

View Full Version : Sql injection


candle21428
Nov 2nd 2006, 11:38 pm
Hi there,

I have bought the following code from a programmer a couple of months ago and I realized the code may lead to very serious sql injection problem (I am a newbie, so not very sure about that).

Here is the form on my admin page:
<form method="POST" action="login.php">
<tr>
<td width="100%" colspan="2">
<p align="center"><b>Login Here</b></td>
</tr>
<tr>
<td width="100%">User Name </td>
<td width="50%">
<input type="text" name="user" size="20" class="text"></td>
</tr>
<tr>
<td width="100%">Password</td>
<td width="50%">
<input type="password" name="pw" size="20" class="text">

and here is the code on the login.php

session_start();

$Sql="Select * from admin where username='$user' and password='$pw'";
$result=mysql_query($Sql,$conn);
$lo=mysql_num_rows($result);
if($lo >=1){
session_register("whosin_admin");
$whosin_admin=$un;
header("Location: home.php");
}else{
header("Location: index.php?err=1");
}
?>

It seems that there is no filter to prevent sql injection at all. What should I do to make this login process secure?

I have read a few articles on google and some said that it would be useful to use "mysql_escape_string" for the input, but what is a proper way of using it?

Questions:

1) Do I simply use mysql_escape_string($user) instead of $user?
2) Is there any other code I could add to make it more secure?
3) People always said that it is better to turn the global register off. Is session_start(); or all those session variable considered to be global register? How can I transfer data between pages if I don't use session?
4) Is there any other web sites where I can learn more about the web site security?

Thx in advance.

edD
Nov 3rd 2006, 9:29 am
Things that could come from the user(in this case) or could be tampered with should pretty much never be used in a DB query as-is.
Here's how you could escape the two values before using them in the query.


<?php

session_start();

$escUser = mysql_real_escape_string($_POST['user'], $conn);
$escPw = mysql_real_escape_string($_POST['pw'], $conn);

$Sql="Select * from admin where username='$escUser' and password='$escPw'";

if (!$result = mysql_query($Sql, $conn) )
{
// handle query error;
}

if(mysql_num_rows($result) >=1)
{
// where's $un coming from? Don't rely on register globals...use $_POST or $_GET
// Also $_SESSION is better than session_register()
$_SESSION['whosin_admin'] = $un;

header("Location: home.php");
}
else
{
header("Location: index.php?err=1");
}

// should call exit after sending Location header
exit;

?>

It would also be helpful to write a validation function to validate $user and $pw, to make sure that they match a general pattern before even going on to the DB part.

Good PHP security site:
http://shiflett.org/articles/security-corner-apr2004