unsuccessful PHP code - php

Can anyone tell me why this code is not working?? Any silly mistakes I made?
The Problem:
There is a login page. In the Login page i type in the ID and password and click enter. Once i click enter it will run the next file which is login_now.php. In my database, I have 2 entries. First entry the position is manager and 2nd entry position is staff. Logging in with manager is very successful while logging in with staff is a total failure...failure as in it never do what it should do it just return me back to log in page.
This is the code that is in login_now.php and this is what it suppose to do when enter button is clicked:
$query = "select * from emp where EID = '$myeid' and PASS = '$mypassword'";
//run the query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
//found a record?
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welmanager.php'); //redirect user to index
}
elseif (mysql_num_rows($result) > 0 and $row['POSITION']=="staff")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welstaff.php'); //redirect user to index
}
else
{
header('Location: login.php'); //kick back to login
}
Let me know if more codes in the login.php should be shown here. Thanks in advance.

A minor error may locate in if condition.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
You have to use or condition rather than and,
if (mysql_num_rows($result) > 0 || $row['POSITION']=="manager")

Without wanting to jump on the bandwagon, the comments about session management being a solved problem are right - even if you chose not to use it, you can learn a lot from how they do it. Look at CakePHP, the Zend Framework, Symphony, even PEAR.
Secondly - SQL Injection! Even if this is not exposed to the wider internet, you can't necessarily guarantee that none of your staff are malicious.
Thirdly, it appears you store your passwords in plain text; this is a big nono. People often re-use their passports; someone who can steal your user records (using SQL Injection) can try those passwords on online banks etc. Read up on hashing passwords.
Fourthly, don't store the password in plaintext anywhere - but certainly not in the session object. You've already cover that...
The actual code looks syntactically okay, but there are some odd things.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
Doesn't make sense! If there are no results, logically the $row array should be empty.
You're also not really distinguishing between legit "there's no match for username/pwd" situations and bugs such as having STAFF rather than staff in the type column.
I'd refactor it as:
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)// no match!
{
header('Location: login.php'); //kick back to login
}
//Maybe put in a catch for more than 1 record too - that would be a data bug.
$_SESSION['eid'] = $myeid; //remember name as a session variable
switch($row['POSITION']){
case "manager":
header('Location: welmanager.php'); //redirect user to index
break;
case "staff":
header('Location: welstaff.php'); //redirect user to index
break;
default:
echo ("Found unknown staff type. Error.");
}
Now you can see whether your record really isn't found - i.e. the username/pwd combo didn't match - or whether the user profile isn't of type "staff".

Related

Having some issues on PHP login script

This code below is having a problem..
<?php
session_start();
include_once("databaseConnect.php"); // This creates $database by mysqli_connect().
if(isset($_SESSION['id'])){ // checking if user has logged in
$id = $_SESSION['id'];
$sql = "SELECT * FROM tableName WHERE id = '$id'";
$query = mysqli_query($database, $sql);
$row = mysqli_fetch_row($query);
$activated = $row[1]; // This is where I store permission for the user
if(!($activated == 2 || $activated == 3)){ // if the user has not enough permission:
header("Location: http://myWebsiteIndex.php");
}
// code for users
}else{
header("Location: http://myWebsiteIndex.php");
}
?>
I have a user who has 3 for $activated, so they should be able to access.
When a user logges in to my website, it sets $_SESSION['id'] to store the id of the user.
This session variable is used to check if the user is logged in.
However, when I run the code several time, sometimes it works and sometimes it doesn't. Sometimes, it will run the '// code for users' part, and sometimes it will just redirect to my 'http://myWebsiteIndex.php'.
How would I fix this??
First, try changing the headers to different redirects. What part of the conditional is failing? If the $_SESSION['id'] is not properly set it will redirect to the same url as it will redirect to when the user does not have proper permissions. Changing one of them will show you what part is executed when you encounter the behaviour.
Second, the comment from Barth is helpful. The if(!($activated == 2 || $activated == 2)) evaluation seems incorrect. You are evalutaing for (not) 2 or 2.
Third, take note of your session data and compare when the redirect happens to when it does not.

Check values on mysql table and select ones that are set to "1"

I looked all over. I cannot figure this out.
<?php
session_start();
if (!empty($_POST[username]))
{
require_once("connect.php");
// Check if he has the right info.
$query = mysql_query("SELECT * FROM members
WHERE username = '$_POST[username]'
AND password = '$_POST[password]'")
or die ("Error - Couldn't login user.");
$row = mysql_fetch_array($query)
or die ("Error - Couldn't login user.");
if (!empty($row[username])) // he got it.
{
$_SESSION[username] = $row[username];
echo "Welcome $_POST[username]! You've been successfully logged in.";
exit();
}
else // bad info.
{
echo "Error - Couldn't login user.<br /><br />
Please try again.";
exit();
}
if($isadmin["admin"]==1)
{
echo $admin;
}
else
{
}
}
$admin = <<<XYZ
<div id="admintab">
Admin ยป
<div id="admin">
ADMIN PANEL
<div id="exitadmin">
</div>
<div id="artistline" />
</div>
</div>
XYZ;
?>
I do know that the $admin value is working. I have tested it. Basically, I have a register system. By default, it sets your admin value to '0'. But let's say i want to add an admin. I change the '0' to a '1' via mysql. I want to know how to make php find users with their admin value set to '1' that are in the database (row name: admin), and display the admin panel to them only.
Why have you used
if($isadmin["admin"]==1)
as you have
$row = mysql_fetch_array($query)
so convert
if($isadmin["admin"]==1)
to
if($row["admin"]==1)
you should check the value before insert and select the data and also use
mysql_real_escape_string($_POST['username'])
so that sql injection not apply
You need to change if($isadmin["admin"]==1) to if($row['admin'] == 1) -- you can leave out the == 1 part if 1 & 0 are the only answers as 1 will always be true and 0 will be false.
Obligitarily, I need to mention that storing passwords in your database in plain text is a bad idea, you should be at the very least hashing them before you store them. Something like $password = hash('sha256', $salt.$_POST['password']) at the registration and login stages.
I should also point out that you shouldn't feed naked values into your database with a query, you don't need to worry about password if you're hashing it, but you do if you're not and you need to do username anyway otherwise anyone can run SQL queries in your database:
$username = mysql_real_escape_string($_POST['username'])
Firstly, I am obligated to point out that not filtering $_POST (and $_GET and $_COOKIE and so on) is very dangerous, because of SQL injection. Secondly, the variable $isadmin doesn't magically exist until you've defined it.
I would suggest designing a more capable user group system, but just to answer the question, the variable you want to check is $row["is_admin"], given that is_admin is a valid column in the table. Also, you don't need to do if ($row["is_admin"] == 1) - 1 evaluates to TRUE in PHP.

One login script, two tables

I have a website for my school I am designing.
I am struggling how to work this for my script, but there are two sections to the website. If a teacher logs in, from the table lesson_teachers, it should redirect them to lesson.php. If a student logs in, from the table users, it redirects them to home.php.
I think the select query for the teachers table may be something like this:
SELECT id FROM lesson_teachers WHERE username='$user_login' AND password='$md5password_login' LIMIT 1
I am trying to fit that select statement into my login script below, so that people with usernames and passwords in both tables can log into one script.
if (isset($_POST["user_login"]) && isset($_POST["password_login"])) {
$user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters
$password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters
$md5password_login = md5($password_login);
$sql = mysql_query("SELECT id FROM users WHERE username='$user_login' AND password='$md5password_login' LIMIT 1"); // query the person
//Check for their existance
$userCount = mysql_num_rows($sql); //Count the number of rows returned
if ($userCount == 1) {
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
exit("<meta http-equiv=\"refresh\" content=\"0\">");
} else {
echo 'That information is incorrect, try again';
exit();
}
}
Your user table should either have a roles relation or at least a tinyint 1 field (0 for student, 1 for teacher) in your user table so you don't have to use 2 tables to achieve this.
Pretending I agreed with the query, this is what it might look like:
SELECT id, level FROM users WHERE username='$user_login' AND password='$md5password_login' LIMIT 1
where level is 0 for student, 1 for teacher. Any data relevant to either student or teacher on its own could be stored in a relation table.
Then you could say:
if($row['level'] == 1)
{
header('Location: /teacher-url');
exit;
}
else
{
header('Location: /student-url');
exit;
}
Now for the extra nuggets:
Please don't use this method for comparing passwords. You could basically login as another user accidentally or by happenstance if you were trying to hack since it strips characters. So "pa_s$sw==0ord" turns into "password"
Just run a sha1 (or better) encryption comparison on the posted input versus the stored sha1 encrypted password in the DB. That's the best real comparison to user passwords vs input.
And storing a password in $_SESSION just plain makes no sense. Why would you ever use it like this? Perhaps if you tell we can point you in a better direction.
And as Elias said, use PDO or mysqli. They will sanitize correctly amid the many many other reasons to use them over mysql_ functions.
I should add that we are all aware of how to actually answer your question. We know you want to know HOW to do it with what you've got. But we refuse. Because this habit should be cleaned before it becomes a nightmare. Not trying to be deliberately rude or anything, but a well planned database structure and use of PDO or mysqli will save you tons of time in both database and code. Look into relation tables, the concept of "roles" and sanitizing user input. From that you can construct the user system in a way that makes sense.
Firstly, you will only find 1 match per user/password pair,
so instead of
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
you can simply do
$row = mysql_fetch_array($sql);
$id = $row["id"];
As for the teach/student redirect, you will need a hidden variable in the login from to identity type= teacher or student
then based on this variable, you can do
if ($type=='student')
header('location:home.php');
if ($type=='teacher')
header('location:lession.php');
after setting your session variables.

Keep a given ID in URL upon successful login

if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.

Creating an Admin product system in PHP - Authentication error

I'm creating an e-commerce website. I am working on an admin page that lets the "store manager" log in to do things like add or remove products. In my database, I created a table called admin, with these fields:
id
password
time_last_logged_in
I inserted a row for my store manager, I can see the username and password so I know the person exists in the database, but when I try to log in it echoes out the error below.
admin_login.php
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 1) { // evaluate the count
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
**echo 'That information is incorrect, try again Click Here';**
exit();
}
}
?>
I use a connect_test.php script to verify that it's connecting to the database and that there's no problem connecting.
index.php
<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: admin_login.php");
exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "../scripts/connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM admin WHERE id='$managerID' AND username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$existCount = mysql_num_rows($sql); // count the row nums
if ($existCount == 0) { // evaluate the count
echo "Your login session data is not on record in the database.";
exit();
}
?>
Why might my code return That information is incorrect, try again Click Here'; instead of a successful validation?
The Problem(s?)
The way I see it, there are several problems with your code. I'll try to address each one and tell you how to solve each issue.
Issue #1: You are using REGEX To strip your code.
There are much better alternatives, the best of which is prepared statements which you should obviously use. Sadly, mysql_* functions don't support it. Which get's me to the next issue:
Issue #2: You are using mysql_* functions.
You shouldn't be using functions like mysql_query() and mysql_num_rows(), instead, consider moving to a better and more secure alternative, such as MySQLi (Good) or PDO (Awesome).
Issue #2.5: You are not using prepared statements.
A Prepared statement is automatically escaped and any malicious code or characters is render useless, same goes for SQL injections. You should use a better database handler that supports it (See Issue #2).
Issue #3: You are testing specifically.
You seem to test only if the row count is equal to exactly one. But what if there are (by accident) 2? Instead of testing what should be, test for what should not be:
if ($existCount != 0) { ...
Issue #4: You are not selecting the correct fields.
You only select the id field in your query, where instead you should be selecting all of the relevant fields (like username and password), in order to receive information.
Issue #5: You are not using secure storing.
If someone were to steal your database, they would have easy access to all your passwords. Consider using an encrypting method like sha1().
Issue #6: You are not testing for errors.
Errors can and will occur, you should test for them, with mysql_query() you should probably do something like
mysql_query("SELECT....") or die(mysql_error());
In PDO that would be something like
if (!$stmt->execute()) { throw new Exception("Execution failed.` . var_export($stmt->errorInfo(), true)); }
Try to correct those, and tell us if your problem persists.
Good luck :)
Try doing:
$sql = mysql_query("SELECT ... LIMIT 1") or die(mysql_error());
Your code assumes the query succeeds, which is very bad form. Always check for error conditions. You may have failed to connect to the database. perhaps your DB is malformed and you've got 2 or more records with the same username/password combo, etc...
I'm new to PHP myself, but I noticed that your select statement in the first code sample above selects only the id. That might be the problem. You should change it to select * and see if that makes any difference.
Good luck

Categories