Admin Page Access - php

I have a page which only admins can access once they click a link. If the logged in user is a standard user then they should not be able to access the page. However, when a standard user tries to access the admin page they have access to the page.
I would appreciate a pair of second eyes to see if they can spot anything wrong with the code which would make the functionality work as intended.
Thanks
<?php
if(check_login() && isAdmin()) {
echo 'welcome administrator';
} else {
header('Location: login.php');
exit;
}
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID ='" . $_SESSION['sess_uid'] . "'";
$mainaccess = $conn->query($sql);
print_r($mainaccess);
if(!$mainaccess){
echo $conn->error;
}
if ($mainaccess -> userLevel == 0) {
return true;
} else {
return false;
}
}
function check_login () {
if(isset($_SESSION['sess_uid']) && $_SESSION['sess_uid'] != '') {
return true;
} else {
false;
return;
}
}
?>

The issue is that you are selecting from the database users where they have admin access already ie
SELECT `userID` FROM `usertable` WHERE `userLevel` = 0
So you are always showing anyone as an admin. The query needs to be changed to check specifically if the logged in user is an admin. So changing the query to something like so
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
Where $_SESSION['sess_uid'] is the userID
We have to remove both the userLevel check, as this is irrelevant when selecting the user, we also have to change from SELECT userID, to SELECT *, as if you only select the userID, you will not have the userLevel in your array and the line
$mainaccess -> 'userLevel' == 0
Will not work. By selecting everything you ensure all attributes can be accessed, ie
$mainaccess -> 'userLevel'
$mainaccess -> 'userID'
Update
The correct way to access the table data will be using either
Object (this is the method you will use)
$mainaccess -> 'userLevel'// Incorrect
$mainaccess->userLevel //correct
Array
$mainaccess -> 'userLevel'// Incorrect
$mainaccess['userLevel'] //correct
Please change this line
You query is also incorrect please use this block of code as your sql query is not pulling in the right info.
function isAdmin()
{
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT * FROM `usertable` WHERE userID = $_SESSION['sess_uid']";
if($result = $mainaccess = $conn->query($sql))
{
while($obj = $result->fetch_object())
{
$user = $obj;
}
}
if ($user->userLevel == 0)
{
return true;
}
else
{
return false;
}
}

You really need something like:
function isAdmin() {
$conn = mysqli_connect("localhost", "root", "dbpass", "dbname") or die ('Could not connect to database!');
$sql = "SELECT `userID` FROM `usertable` WHERE `userLevel` = 0 AND userID ='" . $_SESSION['sess_uid'] . "'";
As I said in the comments, you are looking for ANYONE with admin access, but you really want to know whether THIS user has admin access, therefore you have to validate what user you are trying to figure out has access. I just put the code together above, thinking you are storing the userID in the session (as per your later code) but you may need to change this

Your approach is wrong. The link should only be shown to logged in admins.
Try something like this test code.
<?php
session_start();
$_SESSION['admin'] = 0;//set only by logging in
$html ="Test<br>";//page html
if ($_SESSION['admin']== 0) {
$html .="<a href=\"adminpage.php\" >Admin</a>";
}
echo $html;
?>
Modify to suit your requirements.

Related

store MySQL SELECT result in php variable using Prepared statements

I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

How to detect whether users have accepted terms?

Basically I am writing a PHP and MYSQL script that will check whether a user has accepted the terms and conditions or not. In the databse every current user that has signed up is set to "unaccepted". When they log in the first page that they are directed to should have a scirpt on it that detects whether or not the status of the tos column in the users table is set to "accepted" or "unaccepted". If it is accepted they can continue, and if it is not they they will be forced to go to a page and accept them before they can continue to use the rest of my site. This is the code so far but it doesn't seem to be working. Any suggestions help.
<?php
$username=$_SESSION['username'];
$connect = mysql_connect('**', '**', '**', '**');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('**'))
{
die('Could not select database: ' . mysql_error());
}
$toschecker = mysql_query("SELECT `tos` FROM `users` WHERE `username` = '$username'");
if (!$toschecker)
{
die('Could not query:' . mysql_error());
}
mysql_close($connect);
$unaccepted='unaccepted';
if ($toschecker === $unaccepted)
{
header('Location: accepttos.php');
}
?>
For some reason this isn't directing them to the accepttos.php page. Thanks in advance.
Change MySQL to MySQLi. Explanations are in the comments.
<?php
$username = $_SESSION['username'];
$connect = mysqli_connect('Host', 'Username', 'Password', 'Database');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$toschecker = mysqli_query($connect,"SELECT `tos` FROM `users` WHERE `username` = '$username'"); /* SELECT TOS COLUMN */
while ($row = mysqli_fetch_array($toschecker))
{
$tos = $row['tos']; /* STORE TO A VARIABLE THE FETCHED TOS */
}
$unaccepted = 'unaccepted';
if ($tos == $unaccepted) /* COMPARE THE TOS VARIABLE IF UNACCEPTED */
{
header('Location: accepttos.php');
}
else {
header('Location: acceptedTOS.php'); /* IF TOS IS ACCEPTED. CHANGE THE LOCATION */
}
mysqli_close($connect);
?>
$toschecker is a resource , try the following under the mysql_query line to see the result of your query, which you can use to redirect accepttos.php etc..
if( $row = mysql_fetch_assoc($toschecker)) {
var_export($row['tos']);
}
You need to access the information in the fields of your database. Here is an example.
$toschecker = mysql_query($sql);
$row = mysql_fetch_array($toschecker);
$tos = $row['tos'];
if($tos == 'accepted'){
// go to regular page
}else {
// go to accept terms page
}

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

PHP MySQL query output

I am trying to do a query in which i can see if username and password can match. If it matches, then I will go to the administrator pages. The problem Im having is that i think that the query is not giving me the right results. The database table is called admin, and it has adminame and passadmin. The user im entering IS in the database. The password is encrypted.
<?php
$f_user = $_POST['f_user'];
$f_pass = $_POST['f_pass'];
$status = authenticate($f_user, $f_pass);
if ($status == 1)
{
include("../connections/config.php");
session_start();
//session_register("SESSION_UNAME");
$_SESSION['SESSION_UNAME'] = $f_user;
$SESSION_UNAME = $f_user;
header("Location: unoadmin.php");
exit();
}
else
{
$mensa= "Información Incorrecta...Inténtelo de Nuevo";
header("Location: register.php?mensa=$mensa");
exit();
}
function authenticate($user, $pass)
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query = "SELECT * from admin WHERE adminame = '$f_user'";
mysql_select_db($db);
$result = mysql_query($query, $connection) or die ("Error in query: $query. " . mysql_error());
$num_results = mysql_num_rows($result);
if ($num_results == 1)
{
for($i=0; $i < $num_results; $i++)
{
$row = mysql_fetch_array($result);
$pas = $row["passadmin"];
}
if(crypt($pass,$pas) == $pas)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
?>
Can someone tell me what is the error? It is leading me to "Información incorrecta. Intentelo de nuevo" or in english "Wrong information. Try again"
It is a bit of a guess, but your authenticate function returns false (error message)
I am not sure what happens in the include, it suggests inclusion of database settings.
You are using 2 different vars for the username: is:
function authenticate($user, $pass) // <-- you pass $user
{
include("../connections/config.php");
$connection = mysql_connect($mach,$userna,$paso) or die ("Unable to connect!");
$query =
"SELECT * from admin WHERE adminame = '$f_user'"; // <-- you use $f_user
Perhaps not a real answer, but it was to long for a comment.
A simple solution of this question is to put your user name and password in variables and match it with database, If result have greater than 1 value than it will go to admin page. For example
$myusername=addslashes($_POST['username']);
$mypassword=addslashes($_POST['password']);
$sql="SELECT * FROM admin WHERE username='$myusername' and password=md5('$mypassword')";
$query = mysql_query($sql);
$row = mysql_num_rows($query);
if($row>0) {
header("location:administrator.php");
}
else {
echo"Please check username and password";
}
From your code you have either:
no such entry in your DB with the username you provided
the password is wrong
Furthermore you should check your code for SQL injections!
Please take time to read article below,
Best Way to prevent SQL Injection in PHP

Categories