Ask access_level from database - php

I have code, which should use access levels, but from the database my code is not requesting the access level and I do not get into my "admin.php"
Can you help?
Login page is here:
Login-Page
Credentials: test / test
I want to let users login into my page, which is access for recruiters of me. So I can create users, they see my CV and others. Therefor it is neccessary to set user levels like "1" for admin.php "2" for admin2.php and so on.
Here's the check.php which is a form from the index.php
<?php
session_start();
require_once("inc/config.inc.php");
require_once("inc/functions.inc.php");
$error_msg = "";
if(isset($_POST['uname']) && isset($_POST['pwd'])) {
$email = $_POST['uname'];
$passwort = $_POST['pwd'];
$statement = $pdo->prepare("SELECT * FROM users WHERE email = :uname");
$result = $statement->execute(array('uname' => $email));
$user = $statement->fetch();
//Überprüfung des Passworts
if ($user !== false && password_verify($passwort, $user['pwd'])) {
$_SESSION['userid'] = $user['id'];
$access_level = $user['access_level'];
$_SESSION['access_level'] = $access_level;
//Möchte der Nutzer angemeldet beleiben?
if(isset($_POST['angemeldet_bleiben'])) {
$identifier = random_string();
$securitytoken = random_string();
$insert = $pdo->prepare("INSERT INTO securitytokens (user_id, access_level, identifier, securitytoken) VALUES (:user_id, :access_level, :identifier, :securitytoken)");
$insert->execute(array('user_id' => $user['id'], 'access_level' => $access_level, 'identifier' => $identifier, 'securitytoken' => sha1($securitytoken)));
setcookie("identifier",$identifier,time()+(3600*24*365)); //Valid for 1 year
setcookie("securitytoken",$securitytoken,time()+(3600*24*365)); //Valid for 1 year
}
if ($access_level==0){
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
}
else{
header("Location:index.php?err=1");
}
} else {
$error_msg = "E-Mail oder Passwort war ungültig<br><br>";
}
$email_value = "";
if(isset($_POST['email']))
$email_value = htmlentities($_POST['email']);
?>
The problem was here in line
<?php
$statement = $pdo->prepare("SELECT * FROM users WHERE email = :uname");
there's no table named "email" - so it's not possible to get a true request.
I changed it to:
<?php
$statement = $pdo->prepare("SELECT * FROM users WHERE uname = :uname");
After that, my page gives me the output:
Hello This is admin page.
Thanks at all of you for your help! :)

May be your mistake is here.
$access_level = ['access_level'];.
it should be like
$access_level = $user['access_level'];.
and I don't get your situation.
other mistake is may be here.
if(isset($_POST['angemeldet_bleiben'])) {
$identifier = random_string();
$securitytoken = random_string(); //remaining code....
}
else if ($access_level==0){
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
don't you think it should be like.
if ($access_level==0){ //removed else.
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
because if first if condition worked then it skips all other else if statements.

Did you check print_r($user)? What is returned? What datatype has your column "access_level" in your database?
Maybe you have to check $access_level=='0', if it is type string.

Related

Why is my else condition being executed twice?

I went through this login system with multi-users. It's working fine since it doesn't allow my status_id users '2' to login (inactive status), but when this happens I get the echo message twice on screen.
What am I doing wrong?
I want to validate both user/password, user_type (admin/user) and user_status (1-active, 2-inactive).
<?php
include 'database/connect.php';
if (isset($_POST["submit"])) {
$email = $_POST["txtemail"];
$pass = $_POST["txtpass"];
$query = mysqli_query($con, "SELECT user_email,user_password,user_type_id, status_id FROM user");
while ($row = mysqli_fetch_array($query)) {
$db_email = $row["user_email"];
$db_pass = $row["user_password"];
$db_type = $row["user_type_id"];
$db_user_status = $row['status_id'];
if ($email == $db_email && $pass == $db_pass && $db_user_status == '1') {
session_start();
$_SESSION["email"] = $db_email;
$_SESSION["type"] = $db_type;
if ($_SESSION["type"] == '1') {
header("Location:admin/home_admin.php");
} else {
header("Location:user/home_user.php");
}
} else {
echo "Ups. Algo de errado aconteceu.";
}
}
}
Looking at your code, if the conditions specified inside the loop fails then the else will execute.
So if your user table holds 3 records and all 3 records doesn't satisfy the condition specified it will execute else statement and 3 times.
This might be the reason.
Well it looks like you are looping through every user inside your user table, so the posted email and password can only be right for one user and for the rest of them your program will go through the else statement

Select data based on admin and level who is logged in, but it displays data from another level

I am currently making a login system with multilevel. I have table 'admin' includes 'level' field. I want to make admin redirect to page based on 'level' field on 'admin' table. If level is 1 will redirect to SIPP-Litbang/admin.php page, then if level is 2 will redirect to SIPP-Litbang/admin-pp-sipp-litbang.php.
The first step, I make method on class.admin.php page, here are the codes:
public function login($email, $password)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM admin WHERE email_admin = :email AND pass_admin = MD5(:pass)
LIMIT 1");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':pass', $password,PDO::PARAM_STR);
$stmt->execute();
$adminRow = $stmt->fetch();
if ($stmt->rowCount() == 1) {
$_SESSION['is_logged_in'] = true;
$_SESSION['adminSession'] = $adminRow['id_admin'];
$_SESSION['levelSession'] = $adminRow['level'];
return true;
} else {
return false;
}
}
catch(PDOException $e)
{
return FALSE;
}
}
public function cekSession(){
if (isset($_SESSION['adminSession'])&&$_SESSION['levelSession']==1) {
header('Location: \SIPP-Litbang\admin.php');
return true;
}
elseif (isset($_SESSION['adminSession'])&&$_SESSION['levelSession']==2) {
header('Location: \SIPP-Litbang\admin-pp-sipp-litbang.php');
return true;
}
}
And loginadmin.php page:
<?php
session_start();
include_once ('class.admin.php');
$admin = new Admin();
if (isset($_POST['login'])){
$user = trim(strip_tags($_POST['email']));
$pass = trim(strip_tags($_POST['pass']));
if ($admin->login($user, $pass)){
}
else {
echo "GAGAL LOGIN! Email atau Password Salah";
}
}
Login process has worked, for example admin with level 2 will header to SIPP-Litbang/admin-pp-sipp-litbang?modul=beranda. Then I want to display details of admin level 2, here are the codes from admin-pp-sipp-litbang.php page:
<?php
session_start();
require_once 'class.admin.php';
$user = new ADMIN();
$admin_level = isset($_SESSION['levelSession']);
$admin_id = isset($_SESSION['adminSession']);
$stmt = $user->runQuery("SELECT * FROM admin WHERE id_admin=:admin_id AND level=:level");
$stmt->bindParam(":admin_id",$admin_id);
$stmt->bindParam(":level",$admin_level);
$stmt->execute();
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
I try to echo the name of admin with level 2, but It just displayed name of admin with level 1 . Am I missing something?
$admin_level = isset($_SESSION['levelSession']);
$admin_id = isset($_SESSION['adminSession']);
isset() returns true\false; in your case 'true' is being cast to 1, which explains the results you see.
what i assume you want here is::
if(isset($_SESSION['levelSession'])){
$admin_level =$_SESSION['levelSession'];
}
if(isset($_SESSION['adminSession'])){
$admin_id = $_SESSION['adminSession'];
}

depending on condition show error message in php

i have code like this
<?php
require('../config.php');
require_once($CFG->dirroot . '/user/editlib.php');
$errorMessage = '';
$successMessage = '';
if(isset($_SESSION['successMessage']))
{
$successMessage = $_SESSION['successMessage'];
unset($_SESSION['successMessage']);
}
if (isset($_POST['register'])) {
if(!preg_match("/^(?=.*[0-9])(?=.*[a-z])(\S+)$/i", $_POST['password']))
{
$errorMessage="don't allow spaces";
}
$errors = array();
$data = array();
$chk_sql = "SELECT * FROM {user} u where username = ?";
if (!empty($chk_sql) ) {
$errorMessage='Username already taken';
}
if(!$chk_username = $DB->get_record_sql($chk_sql, array($_POST['username'])) )
{
$secret = $_POST['secret'];
$access_code_sql = "SELECT * FROM {accesscode} WHERE random_no= ? and status=1";
if($chk_secret = $DB->get_record_sql($access_code_sql, array($secret)) )
{
if ( $chk_secret->used >= $chk_secret->number ) {
$errorMessage = "your access code limit completed..";
}
else
{
$cadminid = $chk_secret->cadmin_id;
$clientid = $chk_secret->clientid;
$DB->execute("UPDATE {accesscode} SET used = used+1 WHERE random_no = '$secret'");
$insert_record = new stdClass();
$insert_record->firstname = $_POST['firstname'];
$insert_record->lastname = $_POST['lastname'];
$insert_record->username = $_POST['username'];
$insert_record->secret = $secret;
$insert_record->password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$insert_record->timecreated = time();
$insert_record->maildigest = $cadminid;
$insert_record->maildisplay = $clientid;
$insert_record->idnumber = 1;
$insert_record->mnethostid = 1;
$insert_record->confirmed = 1;
$insert_record->email = $_POST['email'];
if($result = $DB->insert_record('user', $insert_record))
{
$_SESSION['successMessage'] = "record created successfully";
header('Location: register.php');
}
else
$errorMessage = "error! can you please try again";
}
}
else
$errorMessage = "your access code is wrong..";
}
}
?>
so i want to write condition like another if condition
if ( $chk_secret->status='0' ) {
$errorMessage = "your access code deactivated..";
}
if not they can register
i tried..but i didn't get idea where i have to add that if..
before i have condition like if number>used it will show some error message like your accesscode limit completed
can anyone help me..
thanks in advance..
= is for value assignment
== is compare two operands
so you need to change
if ( $chk_secret->status='0' ) {
to
if ( $chk_secret->status=='0' ) {
UPDATE:
your query SELECT * FROM {accesscode} WHERE random_no= ? and status=1
which means it going to return only status == 1
you can check with number of rows returned is ZERO then through status zero error message.
Or else
Get rows only based on random_no exists and then check status key

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 */

PHP/MySQL - Validating Usernames with Exceptions for Additional Characters

I've created an athletic league website with dynamic schedules and standings using PHP and MySQL. One of the basic functions of the website is for schools to select a game on the schedule that's already been played and log-in to report the score. You can see an example of the score reporting page below:
http://www.parochialathleticleague.org/report_score.html?league=test_league&game_id=5&away_team=St.%20Polycarp&home_team=St.%20Columban
After several months of work, everything seems to be working just right. However, I realized one important oversight this morning, just before the schedules for the new season are about to go live:
Some of our schools have multiple teams in each division because they have extra students. So, for example, there may be a St. Barbara AND a St. Barbara #2 participating in the same league and/or division. Sometimes, there are as many as three of four teams from the larger schools.
This is a problem because the validation code that I've written checks the school usernames to make sure they match the master school user accounts in the MySQL database before being allowed to report a score. Therefore, St. Barbara would not be authorized to report a score for their St. Barbara #2 team, even though they belong to the same school! I don't want to create separate user accounts for every team belonging to that school, so I need to modify the code in some way. I would like St. Barbara to be able to log-in with the same username for all of their different teams, regardless of whether or not there are additional characters at the end (if that makes sense).
Here's the function from my script that validates the username (school) to make sure they're one of the two teams participating in the game in question:
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
Next, here's the function that later validates that the username and password match one of the records in the database:
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}
Is there anyway to add an "addendum", so to speak, to the code that would make an exception for schools that have multiple teams? Sort of like:
elseif ($_POST['school'] == $_POST['away_team'] **MINUS ADDITIONAL INTEGERS AT THE END** || $_POST['school'] == $_POST['home_team'] **MINUS ADDITIONAL INTEGERS AT THE END**) {
$validate = 'true';
}
Sorry for the whole long spiel. Just wanted to make sure I explained it properly! Any thoughts? Your feedback is much appreciated.
EDIT - Here's the entire script for those that were interested:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Validate the school:
if (empty($_POST['school'])) {
echo "You forgot to enter your school.<br>";
$validate = 'false';
} elseif ($_POST['school'] != $_POST['away_team'] && $_POST['school'] != $_POST['home_team']) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
} else {
$school = mysqli_real_escape_string($db, trim($_POST['school']));
$validate = 'true';
}
// Validate the password:
if (empty($_POST['pass'])) {
echo "You forgot to enter your password.<br>";
$validate = 'false';
} else {
$pass = mysqli_real_escape_string($db, trim($_POST['pass']));
$validate = 'true';
}
// Validate the away score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_confirm = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
// Validate the home score:
if (!isset($_POST['away_score'])) {
echo "You forgot to enter the home score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['$home_score']) && $_POST['$home_score'] < 0 ) {
echo "You entered an invalid score for the home team.<br>";
$validate = 'false';
} else {
$home_score_confirm = mysqli_real_escape_string($db, trim($_POST['home_score']));
$validate = 'true';
}
// Determine the winner and loser, and set variables:
if ($_POST['away_score'] > $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['away_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['home_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$tie = 'no';
} else if ($_POST['away_score'] < $_POST['home_score']) {
$winner = mysqli_real_escape_string($db, trim($_POST['home_team']));
$winner_score = mysqli_real_escape_string($db, trim($_POST['home_score']));
$loser = mysqli_real_escape_string($db, trim($_POST['away_team']));
$loser_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
$tie = 'no';
} else if ($_POST['away_score'] == $_POST['home_score']) {
$tie = 'yes';
$tie1 = mysqli_real_escape_string($db, trim($_POST['away_team']));
$tie2 = mysqli_real_escape_string($db, trim($_POST['home_team']));
$tie_score = mysqli_real_escape_string($db, trim($_POST['away_score']));
}
// Declare remaining hidden inputs as variables:
$league = mysqli_real_escape_string($db, $_POST['league']);
$game_id = mysqli_real_escape_string($db, $_POST['game_id']);
// If all conditions are met, process the form:
if ($validate != 'false') {
$q1 = "SELECT school_id FROM user_schools WHERE (school_name='$school' AND pass='$pass')";
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// Get the game ID:
$q2 = "SELECT $game_id FROM $league";
$r2 = mysqli_query($db, $q2);
// Get the row for the game ID:
$row = mysqli_fetch_array($r2, MYSQLI_NUM);
// Perform an UPDATE query to modify the game scores:
$q3 = "UPDATE $league SET home_score='$home_score_confirm', away_score='$away_score_confirm' WHERE game_id=$row[0]";
$r3 = mysqli_query($db, $q3);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the winning team in the standings:
$q4 = "SELECT school_id FROM test_league_standings WHERE school_name='$winner'";
$r4 = mysqli_query($db, $q4);
// Get the row for the school:
$row2 = mysqli_fetch_array($r4, MYSQLI_NUM);
$q5 = "UPDATE test_league_standings SET games=games + 1, win=win + 1, pts_for=pts_for + '$winner_score', pts_against=pts_against + '$loser_score' WHERE school_id=$row2[0]";
$r5 = mysqli_query($db, $q5);
$q6 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row2[0]";
$r6 = mysqli_query($db, $q6);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
// Update the losing team in the standings:
$q7 = "SELECT school_id FROM test_league_standings WHERE school_name='$loser'";
$r7 = mysqli_query($db, $q7);
// Get the row for the school:
$row3 = mysqli_fetch_array($r7, MYSQLI_NUM);
$q8 = "UPDATE test_league_standings SET games=games + 1, loss=loss+1, pts_for=pts_for + '$loser_score', pts_against=pts_against + '$winner_score' WHERE school_id=$row3[0]";
$r8 = mysqli_query($db, $q8);
$q9 = "UPDATE test_league_standings SET pct=(win / games), avg_for=(pts_for / games), avg_against=(pts_against / games) WHERE school_id=$row3[0]";
$r9 = mysqli_query($db, $q9);
if (mysqli_affected_rows($db) == 1) {
$confirm = 'true';
} else {
$confirm = 'false';
}
if ($confirm != 'false') {
header("Location: schedules_test.html?league=" . $league);
} else {
echo "The scores could not be reported due to a system error. Apologies for the inconvenience. If this problem continues, please contact us directly.";
}
} else {
echo "Your school and password combination do not match those on file for this game.";
}
}
mysqli_close($db);
?>
For the moment I'm going to assume that you're validating that $_POST['away_team'] and $_POST['home_team'] are valid and correct.
If you just want to check that $_POST['away_team'] begins with the string $_POST['school'], you can use the strpos function:
elseif (strpos($_POST['away_team'], $_POST['school']) === 0 || strpos($_POST['home_team'], $_POST['school'])) {
echo "Your school does not match one of the two on file for this game.<br>";
$validate = 'false';
}
I'd like to assent to tadman's comment about SQL injection. Even if you aren't willing to rewrite your application to take advantage of the superior methods of injecting data into queries, you absolutely should escape your data when you run your query. Do not escape it anywhere else. If you do, eventually you will forget to escape it and it won't be as obvious as it should be. For example:
if ($validate != 'false') {
$q1 = sprintf(
"SELECT school_id FROM user_schools WHERE (school_name='%s' AND pass='%s')",
mysqli_real_escape_string($_POST['school']),
mysqli_real_escape_string($_POST['pass'])
);
$r1 = mysqli_query($db, $q1);
$num = mysqli_num_rows($r1);
if ($num == 1) {
// ***a whole bunch of other stuff that I'm omitting because it's not relevant
}
}

Categories