Jump to content

[SOLVED] Redundant login check?


soycharliente

Recommended Posts

Is this double check necessary or is it just redundant? I've been using this code for ages now and never really noticed it.

 

<?php
if ($_POST["Submit"] == "Login")
{
foreach ($_POST as $key => $val) { $_POST[$key] = myEscape($val); }
$un = $_POST['Username'];
$pw = md5($_POST['Password']);
dbconnect();
$sql = "SELECT * FROM `users` WHERE `username`='{$un}' AND `password`='{$pw}'";
$result = mysql_query($sql) OR DIE ("Unable to validate login.");
if (mysql_num_rows($result) > 0)
{
	$r = mysql_fetch_assoc($result);
	$user = $r['username'];
	$pass = $r['password'];
	if ($un == $user && $pw == $pass) //THIS CHECK RIGHT HERE
	{
		// do stuff
	}
}
dbclose();
}
?>

Link to comment
https://forums.phpfreaks.com/topic/164544-solved-redundant-login-check/
Share on other sites

<?php
function myEscape($string)
{
dbconnect();
$new = get_magic_quotes_gpc() ? stripslashes($string) : $string;
$safe = mysql_real_escape_string($new);
dbclose();
return $safe;
}
?>

 

So I could just have this and it would work jsut the same?

<?php
if ($_POST["Submit"] == "Login")
{
   foreach ($_POST as $key => $val) { $_POST[$key] = myEscape($val); }
   $un = $_POST['Username'];
   $pw = md5($_POST['Password']);
   dbconnect();
   $sql = "SELECT * FROM `users` WHERE `username`='{$un}' AND `password`='{$pw}'";
   $result = mysql_query($sql) OR DIE ("Unable to validate login.");
   if (mysql_num_rows($result) > 0)
   {
      // do stuff
   }
   dbclose();
}
?>

 

That will work.

 

I recommend not opening and closing the database connection for each operation. Your code will run significantly faster if you just open a connection at the start of the script and close it at the end or let it be closed automatically when the script ends.

 

If you have 5 $_POST variables, the posted code is connecting - dbconnect(); and disconnecting - dbclose(); 6 times.

I sometimes run myEscape outside the dbconnect. I don't remember why. I had to do it that way because I had to be connected to run the function. I guess I should just move it inside  the dbconnect() and use it that way from now on.

 

That makes a lot of sense. Thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.