PHP MYSQL check if row data is the same as - php

I'm a little new to PHP and MYSQL. I'm creating an admin panel, in the MySQL database I have a column called admin.
I want it to check the column, So if admin has 0 on it, it will header to index.php but if it has 1 it will header to admin.php.
I would also like some help, For admin.php I want something like, if you were not on the database (checks if admin has 1 in the username), it will head somewhere else.
Admin.php code:
<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$uname = mysql_real_escape_string($_POST['uname']);
$admin = mysql_real_escape_string($_POST['admin']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE admin = '1'");
$row = mysql_fetch_array($res);
if ($row['admin'] == 1) {
header("Location: admin.php");
}
else {
echo 'Shithead';
}
}
?>

For a start you need to fetch the right row for the user. You are fetching only rows that are admins !!! Something like this.
$res=mysql_query("SELECT * FROM users WHERE uname='$uname' and pass='$pass'");
assuming that your db fields are called uname and pass.
You need to get this working and then ask a new question for the rest.

Related

Multi-user login trouble, also looking for good content on this topic

so i'm having trouble and i really have no idea why i'm having this issue because all looks well. But basically i'm trying create multiple user levels for a web page i'm making. For some reason only the regular user role is working at the moment. Basically I want admins to be led to a different user interface. If anyone knows any good content on how to make certain pages only available when a session is started that would be very helpful because that would be my next step after I solve this, also how to create a difference in regular user sessions and admin sessions if that makes sence... But back to my real problem, please tell me why admins arent being led to my admin.php page.. I'm posting the code below.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user = $_POST ['user'];
$pass = $_POST ['pass'];
$reg = '0';
$admin = '1';
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
//this query is for admin users **dont forget to change active to 1 within
db
$qa = "select * from users where username ='$user' and active = '0' and admin = '$admin'";
//this query is for regular users
$q = "select * from users where username ='$user' and active = '0' and admin
= '$reg'";
//these will run the querys above (a = admin)
$resulta = mysqli_query($conn, $qa);
$result = mysqli_query($conn, $q);
//will count rows and verify admin users
$numa = mysqli_num_rows($resulta);
$rowa = mysqli_fetch_array($resulta, MYSQLI_ASSOC);
//will count rows and verify regular users
$num = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($pass,$row['password']))
{
if ($num == 1) {
$_SESSION['username'] = $user;
header('location:index.php');
}
else if (password_verify($pass,$rowa['password']))
{
if ($numa == 1) {
$_SESSION['username'] = $user;
header('location:admin.php');
}
}
}
echo mysqli_error($conn);
?>
your code seems a little confusing to me, so I've sampled it down, instead of running two different queries, why not just one.
Look at this code below, this will help you transfer to admin page when admin logs in, and redirects you to regular page in case of all others.
All I am doing is checking the row value, instead of checking the count again.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user=mysqli_real_escape_string($conn,$_POST['username']);
$pass=mysqli_real_escape_string($conn,$_POST['password']);
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
$sql="select * from users where username ='$user' and active = '0'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($mypassword, $row["pass"])) {
$_SESSION['username']=$user;
if($row["admin"] == "1")
header("location: admin.php");
else if($row["admin"]=="0")
header("location: index.php");
}
else
echo mysqli_error($conn);
?>

How to access the username of the user that is logged in

I have made a web application. I have completed the registration and login. There are two user types that can register, student or professor.
I have a session running from the login time until logout. If you login as a user there are certain things you can do. One of them is close an appointment. This can be done from a radiobuton in a loginstudent.php (for example) page and submit button. This leads you to another .php page. On that page I have to use the username of the user that is logged in (in my case that would be the student) for a mysql query. I don't know how to access this.
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";
I think this is wrong.
edit
this is the complete login
<?php
session_start();
if (($_POST['submit'])) {
include_once 'dbh.php';
$username = $_POST['username'];
$password = $_POST['password'];
//check if empty
if (empty($username) || empty($password)) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=empty");
die;
exit();
} else {
$sql = "SELECT * FROM user WHERE username='$username';";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result); // tsekarei posa vrethikan
if ($resultCheck < 1) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
$hash_password_check = password_verify($password, $row['password']);
if ($hash_password_check == false) {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
} elseif ($hash_password_check == true) {
//login
if ($user_type=="student") {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['user_type'] = $row['user_type'];
header("Location: http://localhost/TexnologiaLogismikou/student.php?login=success");
die;
exit();
} else {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['user_type'] = $row['user_type'];
header("Location: http://localhost/TexnologiaLogismikou/professor.php?login=success");
die;
exit();
}
}
}
}
}
} else {
header("Location: http://localhost/TexnologiaLogismikou/index.php?login=error");
die;
exit();
}
then goes
<?php
include_once 'header.php';
?>
<script>
$(document).ready(function () {
$('#5').hide();
$("form input:radio").change(function () {
if ($(this).val() === "appointment") {
$("#5").show();
} else {
$("#5").hide();
}
});
});
</script>
<section class="main-container">
<div class="main-wrapper">
<form class="student-form" action="studentphp.php" method="POST">
<link href="style.css" rel="stylesheet" type="text/css"/>
<h4 id="9">Select your action:</h4><br>
<input type="radio" name="action" value="appointment">
<p id="8">Show your Appointments</p><br>
<input id="5" type="text" name="prof_last" placeholder="Professor Lastname">
<input id="6" type="radio" name="action" value="upload">
<p id="7">Upload a File</p><br>
<input type="submit" name="submit">
</form>
</div>
</section>
<?php
include_once 'footer.php';
?>
and this is the page i need the username
<?php
include_once 'header.php';
if (($_POST['submit'])) {
include_once 'dbh.php';
$prof_last = $_POST['prof_last'];
if (empty($prof_last)) {
header("Location: http://localhost/TexnologiaLogismikou/student.php?professorlastname=empty");
die;
exit();
} else {
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id=(SELECT user_id FROM user WHERE username=$username);";
mysqli_query($conn, $sql);
}
} else {
header("Location: http://localhost/TexnologiaLogismikou/student.php"); //se ksanapaei sto sign up
die;
exit();
}
?>
<?php
include_once 'footer.php';
The approach i think you should use is:
Firstly, i suppose that you have created some sort of 'user-roles' table to manage the different user access levels (for professor and for student).
After a user has logged in with their username and password, you can access their account details (their real name or username, whichever), and save this value in the session variable. It will look like:
$_SESSION["username"] = "some-user-name";
You can store other info here as well, such as the user's real name, like:
$_SESSION["display-name"] = "the user's name";
When the logged-in user navigates to the any other page, you can get their information from the session variable like this:
$username = $_SESSION['username'];
$displayName = $_SESSION['display-name'];
You can then do whatever you like with them.
After reading through the posted code, i think your goal is to help a student set up an appointment with a professor. And you would like to access the professor record in the database by matching it with the professor's last name. Correct me if i am wrong. If this is the case, then i advise you to change your approach slightly. Look at it like this. If a user logs in successfully (prof or student), store their user_id as well. It will help you later, like this:
$_SESSION["user-id"] = $row['id'] //or
$_SESSION["prof-id"] = $row['id'] //or
Secondly, when a student would want to set/close an appointment, i suggest that you:
Read all the professors' full names and database ids from the the student's department (or from the database table) into an html select tag, something like [select value=""][/select]
This will save you from using the 'last-name' as a matching field in the database. Someone might write 'johns' or 'Johns', or even 'Johns '. These are all the same to a human reader but are different to the database.
You can assign the value field in the select tag to the database id of the professor, with the corresponding professor name.
Something like [select value="1"] Prof. Jonathan Andrews[/select] , etc
That way, there is no need for a student to type (or even know) the last name of the professor. They would select the professor's name.
Lastly, when reading the appointments from the database, you can use the professor id from the select tag and the student id from the session variable. If your select tag is named 'prof-id', you can get the POSTed value with:
$profId = $_POST['prof-id'];
#get the student id from the session var
$studentId = $_SESSION['user-id']
$newQuery = "SELECT * FROM appointment WHERE prof_id = $profId AND student_id = $studentId";
Let me know if understand this and can continue from there. If you need the code, let me know.
well, if you store the username in the $_SESSION already, you can access it anywhere. Just make sure to call session_start() at the top of the PHP script every time you want to use it.
You state that you have login pages working, and sessions working.
A session is serverside storage tied to a connection. So the typical way to handle this (in simplest terms)
if (you accept that user logged in) {
// From the database row you used to check username/password
$_SESSION['userId'] = $row['user_id'];
} else {
//Login failed
}
Depending on how you wrote your login check sql statement you might have to adjust it to include the user_id for this to work.
Once this is working, anytime you need the user_id of the currently logged in user, you have it available in the session. For a secured site, this might be on nearly every request.
Now your sql statement is simpler:
$sql = "SELECT * FROM appointment WHERE prof_id=(SELECT user_id FROM user WHERE lastname='$prof_last') AND student_id={$_SESSION['userId']}";
Here's where I will admonish you that all your SQL statements should be using bound parameters rather than variables embedded in strings, but that is not the crux of your question.
Also you might be able to save yourself some time and code by storing an array to $_SESSION so that you don't need to set every user table variable individually.
You can do this:
$_SESSION['user'] = $row;
Then later you can reference:
echo $_SESSION['user']['username'];

PHP Multiple Restricted Access

I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)

Page protection for the Admin page not working

I have been trying to make a page protection for the Administrator page, and I can not get it to work. I am sure this would not have been a problem if I was not new to PHP coding, hehe.
So what I am trying to do is, when a normal user with the type '0' is trying to access the administrator page, index_admin.php, the user will get redirected to the normal user page, index.php. And if the user have the type '1', then the user/admin will stay on the page.
So here is the code I have been trying to get working. (This file is required in index_admin.php and it is called index_admin_check.php):
<?php
session_start();
?>
<?php
$vert = "localhost";
$brukarnamn = "root";
$passord = "";
$db_namn = "nettsidebunad";
$tbl_namn = "kunde_register";
// Connecting to the MySQL database.
mysql_connect("$vert", "$brukarnamn", "$passord") or die ("Kan dessverre ikkje koble til databasen.");
mysql_select_db("$db_namn") or die ("Kan ikkje finna den ynkjande databasen.");
?>
<?php
// *** Page protection *** \\
// Admin check. If `type` = 1, let the user (admin) stay on the site. If `type` = 0 kick the user (normal) off the site.
$sql = "SELECT `type` FROM $tbl_namn";
$res = mysql_query($sql);
$tell = mysql_num_rows($res);
if ($tell == 0) {
header ("location: index.php");
exit();
}
?>
Some of this text is in norwegian.
$vert = $host (in english)
$brukarnamn = $usernamn (in english)
$passord = $password (in english)
$db_namn = $db_name (in english)
$tbl_namn = $tbl_name (in english)
$sql = "SELECT `type` FROM $tbl_namn";
This SQL query will return a row for every user in your database. Using your method of simply checking whether the query returned a result or not, you need to select just the row for the current user, and then only if the user has type=1.
You need to make sure that:
The user has previously logged into the system using a username and password or some such
You have saved their details to the session.
If your user table has an ID column, and you saved the ID of the logged in user to the session as 'userid', you might use the query:
$sql = "SELECT `type` FROM $tbl_namn WHERE id = {$_SESSION['userid']} AND type = 1";
But of course that would be moot, because you would just have save the user's type in the session when you first logged them in, wouldn't you?
Well for what I can see, you don't actually check for user.
I will make some remarks to your code to make situation clear:
$sql = "SELECT `type` FROM $tbl_namn"; //Return all values of column "type" from table - instead you should search for specifyc user
$res = mysql_query($sql);
$tell = mysql_num_rows($res); //Count returned rows
So instead of finding out the user type, you get the count of registered users.
What you should do to search for user name and get user type for that name. So lets think of this table concept:
ID | name | type |
Now we can start our user check up. We will ask mysql for type of user "admin".
$name = $_POST["username"]; //username submited in POST HTML form
$name = mysql_real_escape_string($name); //Replace dangerous characters from name. This is important to avoid your database being hacked
$data = mysql_query("SELECT type FROM $tbl_namn WHERE name='$name'") or die(mysql_error()); //On failure, you will is if there is some error
$data=mysql_fetch_row($data); //Get actual data
if($data["type"]==0) {
header("HTTP/1.1 403 Acces Forbidden");
header("Location: forbidden.html"); //send user to page telling me he is not allowed to enter. As well you can use include here.
exit;
put this to login page:
<?php session_start();
if ($_POST['type'] = "1") {
Header('location: http://example.com/admin.php/');
$_SESSION['admin']; = "yes";
exit;
} else {
Header('location: http://example.com/user.php/');
$_SESSION['admin']; = "no";
exit;
}
//modify as needed
?>
and this one into admin.php filename can be any but extension needs to be .php:
<?php session_start():
if ($_SESSION['admin']; = "no") {
Header('location: http://example.com/user.php/');
exit;
}
//modify as needed
?>
and remember to put this in the very beggining of the file otherwise sessions won't work

This is my php for viewing user profile

My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>
than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli

Categories