PHP code allows logging in without correct password - php

I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.

This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)

just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.

I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php

Related

Log in script accepts anything but the one it is based off of works fine. Why?

I'm trying to make two visually similar web environments. One is supposed to be secure and the other one isn't. I figure doing things right AND wrong and having examples will help me while I'm still learning. Right now I'm doing the log in forms but while the more secure code works right, the insecure code is literally accepting everything, even blank inputs! I can't tell what the difference is that is making this happen.
This is from the more secure log in page.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = safe_input($_POST['loguser']);
$logpass = md5($_POST['logpass']);
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
display:
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}
setcookie('testsiteUser',$loguser,time()+3600);
setcookie('testsitePass',$logpass,time()+3600);
echo ('<h2 id="greenborder">Hello, <a id="purpleborder"
href="userpage.php">'.$loguser.'</a>!</h2>
<img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
And then after the logform: marker is the log in form. There is more code above comment about the user logging in. Let me know if anyone wants to see it. I don't know if it's relevant.
This works! If I log into this with the wrong user name or password, it'll say so. If I log in right, it'll say so.
This is the code from the more insecure version.
// The user is logging in
} else if (isset($_POST['logsubmit'])) {
// collects value from login form
$loguser = /*safe_input*/($_POST['loguser']);
$logpass = md5($_POST['logpass']);
/*
//This section needs encryption
$logcheck1 = mysqli_query($con,"SELECT * FROM users WHERE username ='$loguser'");
$logcheck2 = mysqli_num_rows($logcheck1);
if ($logcheck2 == 0) {
echo ('There is no record of that username being currently active');
goto logform;
}
while ($logcheck3 = mysqli_fetch_array($logcheck1)) {
if ($logpass != $logcheck3['password']) {
echo ('Incorrect password used.');
goto logform;
}
}
*/
$logcheck = mysqli_query($con,"SELECT * FROM users WHERE username = '$loguser' AND password = '$logpass'");
mysqli_free_result($logcheck);
if ($logcheck == 0){
echo ('Incorrect username or password');
goto logform;
}
//display:
/*$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$loguser'");*/
/*$userpic = $_SESSION["loguser"];
$user = mysqli_query($con,"SELECT profile_pic FROM users WHERE username ='$userpic'");
while ($data = mysqli_fetch_array($user)) {
if ($data['profile_pic'] != NULL) {
$pic = $data['profile_pic'];
} else {
$pic = "img/blank_profile.png";
}
}*/
$_SESSION["loguser"] = $loguser;
echo ('<h2 id="greenborder">Hello, <a id="purpleborder" href="userpage.php">'.$_SESSION["loguser"].'</a>!<h2><p><img class="profile_bar" src="'.$pic.'">');
?>
<p>
<form action="<?php echo ($_SERVER['PHP_SELF'])?>" method="POST">
<input type="submit" name="logout" value="Log Out">
</form></p>
<?php
} else {
logform:
A lot of this is commented out because I started by copying this from the safer code which was made first. This logs in no matter what, and whatever I put into the user name input is displayed as the account name. I don't even know if the database is being queried.
I THINK that the 2nd version is somehow passing the goto login, but I can't see why it would work in the first version but not the second version. Or if I'm missing something else completely! I'm comparing both of these side by side, trying to make sure all the brackets have mates, but I'm still learning PHP. I know goto is awful and putrid and nobody likes it, but I feel like I'm using just how it's displayed in the online PHP manual where it comes out of an if, while, and for statement.
http://php.net/manual/en/control-structures.goto.php#example-162
I'm still building both of these so I realize there may be some big flaws in the first version that aren't present in the second version. I'm really just hung up on this one thing for now. Can anyone see whatever it is I'm missing here?
Sorry if the question is too long or I committed some other faux pas. This is my first question.
Your issue is because your second "less secure" option isn't checking the number of rows.
In your second script, you have:
$logcheck = mysqli_query(....
and then you try to check it
if($logcheck == 0) {..
That's completely wrong, it'll only ever return a mysqli resource or false. Also that mysqli_free_result(); might be causing issues (as stated in the comments by onegun). Comment it out and see what happens.
Another Note
You should be careful when using goto, especially if an error were to occur, you wouldn't be able to trace it to its origin and it's actually bad coding practice to rely on it.

Adding a 'check username' to registration form PHP

Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.

PHP Select Value & Redirect With If Statement

I'm trying to create a php scipt that checks if members are verified as they land on a page. If they are not they get redierected to login with an error message & instructions. So on the page I have this code:
<?php
if (loggedin()) {
$check_active = "SELECT active FROM members WHERE username == '$username'";
$active = mysql_query($check_active);
if ($active < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}
}
?>
It is redirecting the user back to the login page but it doing it whether they are active or not. The values for active members are 0(not verified) & 1(verified). Is htere something wrong in the script I'm using?
Thank You
You'll need to handle the $active result and put it into a PHP variable/array. $active as it is in your code is simply a resource (see here) Try this:
$active = mysql_query($check_active); // run query and return resource
$row = mysql_fetch_assoc($active); // put resource data into php array
if ($row['active'] < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}
Please don't use old mysql, use mysqli_ or read topic on http://php.net/manual/en/function.mysql-query.php.
Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
You aren't fetching the data correctly after the query.
Right after you do the the mysql_query function. Try this:
$output = mysql_fetch_assoc($active);
$active_result = $ouput['active'];
Don't know if it might work.
And add a little more security for SQL injection there.
And use MySQLi instead since you aren't keen on preventing SQL injection yourself.

how to get the session id

please help i have the following php code for my login session but i am trying to get the $_session['user_id'] instead of the $_session['email']. i tried print_f function to see what i can use but user_id array says 0 which cannot be right unless i read it wrong.
session_start();
$email = strip_tags($_POST['login']);
$pass = strip_tags($_POST['password']);
if ($email&&$password) {
$connect = mysql_connect("xammp","root"," ") or die (" ");
mysql_select_db("dbrun") or die ("db not found");
$query = mysql_query("SELECT email,pass FROM members WHERE login='$email'");
$numrows = mysql_num_rows($query);
if ($numrows!=0) {
// login code password check
while ($row = mysql_fetch_assoc($query)) {
$dbemail = $row['login'];
$dbpass = $row['password'];
}
// check to see if they match!
if ($login==$dbemail&&$password==$dbpass) {
echo "welcome <a href='member.php'>click to enter</a>";
$_SESSION['login']=$email;
} else {
echo (login_fail.php);
}
} else {
die ("user don't exist!");
}
//use if needed ==> echo $numrows;
} else {
die ("Please enter a valid login");
}
i am trying to get the $_session['user_id'] instead how can get this to use instead of $_session['email']. tried using $_session['user_id'] but instead i got undefined error msg.
Well, you don't define $_session['user_id'] anywhere in this script, so it's no surprise that it's not defined. You have to assign it a value before you can refer to it.
Also, note that there all kinds of security problems with this code.
You're running your MySQL connection as the root user. This is NOT a good idea.
You're trusting user input, which opens your script up to a SQL injection attack. Stripping HTML tags from the user input does not make it safe. Suppose that I came to your site, and filled in the "email" field with this:
bob#example.com'; GRANT ALL PRIVILEGES ON *.* TO 'evil_bob' IDENTIFIED BY '0wned_joo';
As currently written, your script would happily run its query as normal, and also create an account called "evil_bob" with full privileges to all the information in all of the databases on your server.
To avoid this, NEVER assume that user input is safe. Validate it. And to be extra sure, don't stick variables straight into SQL you've written. Use bound parameters instead. There are a few cases where it's hard to avoid -- for example, if you need to specify the name of a column rather than a piece of data, a bound parameter will not help and you'll have to do it some other way. However, for any piece of data you're using as part of a query, bind it.

Log.php returning 'Invalid User' from MySQL database

I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.

Categories