Ok so I'm trying to pull some data from my SQL database and use it in an IF statement.
I have a database called DB_Default
and I have a table called Users
Inside Users I have all the normal columns such as id, username, password but I also have a column called isadmin.
I want to be able to do a mysql query through PHP selecting all users with the username $_SESSION[username] and isadmin = 1.
What I aim on doing is including a few navigation links for escalated privileged users only. So as the page that the code is going to be put into is for logged in users only I thought right, lets use the already defined username session i,e if my sessions username was set to Admin.
the statement should be
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
I have set $admin = "1"; so that it should only be able to return results if the user logged in has isadmin set to 1.
Instead I'm either having the navigation links show to any user regardless of their isadmin status or not at all.
To be honest the code is very messy as it's 5:40am and I haven't been coding for a while so quite rusty so I'm more than aware of how easy this should be of a fix.
I'm 99% sure it has to do with the fact I just set $admin = "1"; but for the life of me can't figure out where I've gone wrong. Going to give it a rest for today and come back tomorrow. Hopefully by then someone will have posted a resolution and obviously I'll vote up the best answer otherwise I'll give the code a lookover and see if I can't fix it myself!
Thanks!
UPDATE - Included code
<?php
$admin = 1;
$conn = mysql_connect("localhost","root","password");
mysql_select_db("DB_Default",$conn);
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["isadmin"] = $row[isadmin];
} else {
}
if($_SESSION["isadmin"] == '1'){
//has admin privs
} else {
//does not have admin privs
}
I have not yet set up the navigation links as I haven't gotten to that stage yet however the links would be inside the if statement admin links in the admin part and not in the non admin part.
My guess right now is going to be the following: You set the $_SESSION variable when you log in as Admin. After that the $_SESSION is never changed. Which pretty much means that if you log in as Admin and then re-log in as someone else, $_SESSION['isadmin'] will already be set to 1 thus providing full access. So what you will need to do is change the else part to:
if(is_array($row))
{ $_SESSION["isadmin"] = $row[isadmin]; }
else
{ $_SESSION['isadmin'] = 0; }
Related
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.
Logging in we of course have set the $_SESSION['username'] and $_SESSION['password'] as usual. However I am then trying to pack that into a variable for use around the site:
$logged = mysql_query("SELECT * FROM `users` WHERE `username`='$_SESSION['username']' AND password = '$_SESSION['password']'");
$logged = mysql_fetch_array($logged);
One previous setups, this has enabled me to then use $logged around the site for various reasons, such as calling the logged in users email to echo in a form,
However, this time, when using this method, it fails to echo anything. I have tried using the session username variable which works to echo the username, but then I tried using the session to echo the email and it didn't work.
If someone could help me pinpoint why this is, I'd be grateful.
It just doesn't seem to be pulling any information from the user as it should.
For me this just seems like an escape-thing. Try
$logged = mysql_query("SELECT * FROM users WHERE username='".$_SESSION['username']."' AND password = '".$_SESSION['password']."'");
$logged = mysql_fetch_array($logged);
Also make sure to call session_start(); before sending any headers/echoing anything if you weren't aware.
Off topic-tip
As long as this query isn't used in anything public, it's fine. But if you're gonna use this code for anything, be sure to slash your query variables. If not, and if my credentials are not validated nor hashed, you could do some nasty SQL injection by setting your password to be something like '; DELETE * FROM USERS;# as the query would then say SELECT * FROM users WHERE username='JohnDoe' AND password = ''; DELETE * FROM USERS;#'
for the usage of session
if(!session_id())
session_start();
the above session start is a must in every page.
use print_r($_SESSION); to check the session variables initialized..
once done (try using mysqli insted of mysql)
$sql='SELECT col1, col2, col3 FROM table1 WHERE condition';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$arr = $rs->fetch_all(MYSQLI_ASSOC);
}
foreach($arr as $row) {
echo $row['co1'];
}
comment your progress for further changes..
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.
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".
I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}