Hope all is well!
I am trying to code my login.php so that it redirects to consumerView.php for a member and admin.php for employee/admin. I have written the following php code but I keep getting redirected to consumerView.php even though the role of the login info is for an employee. Could someone provide any insight to get this working please?
The SQL query works, I tested it in phpmyadmin.
Disclaimer: I am new to php.
// SELECT query
$query1 = "SELECT u.id, u.email, u.pass password, r.name role
FROM users u INNER JOIN role r ON r.id = u.ro_fk
WHERE email = ? AND u.pass = ? ;";
if(r.name == 'member'){
header("Location: consumerView.php");}
else
{header("Location: admin.php");}
die();
} else {
//If the username/password doesn't matche a user in our database
// Display an error message and the login form
echo "Failed to login";
}
} else {
echo "failed to prepare the SQL";
}
}
?>
You have got result in $myrow.
$myrow = $result->fetch_assoc();
//Create a session variable that holds the user's id
$_SESSION['id'] = $myrow['id'];
//Redirect the browser to the profile editing page and kill this page.
if($myrow['name'] == 'member'){ // <- You need to change this line to check user is member or not.
header("Location: consumerView.php");
}
else{
header("Location: admin.php");
}
Replace
if(r.name == 'member')
with
if($myrow['name'] == 'member')
Ok, just to be precise I will elaborate my comment here:
You have
if (r.name == 'member') {
header("Location: consumerView.php");
}
First of all, you dont have variable r assigned anywhere. Even if you did, it should be $r in php. Then, you are accesing it's property but in php it is done by -> not by dot. So you should obtain your user from $result, and then do something like (or however it will be stored, var_dump your $result to be sure how is it stored)
if ($user->name === 'member') {
header("Location: consumerView.php");
}
Or you can access it from $myrow = $result->fetch_assoc() if you want, but then you need to access it like array so probably it would be something like $myrow['name'];
Related
I having a difficulty on Log-in procedure. The username & password are both correct based on the database. The name of the fields on the database are also correct. I'm using PDO. When I click the log-in, I'm always redirecting to the else bracket. Please help me,thank you.
<?php
session_start();
include 'config.php';
if ($_POST) {
$user = $_POST['user'];
$pass = md5($_POST['pass']);
$query = "SELECT * FROM useraccounts WHERE USER_NAME=? AND USER_PASSWORD=?";
$stmt = $conn->prepare($query);
$stmt -> bindParam(1,$user);
$stmt -> bindParam(2,$pass);
$stmt -> execute();
$num = $stmt->rowCount();
if ($num>0) {
session_start();
$_SESSION['user']=$user;
$_SESSION['active']=true;
header('location:frontpage.php'); //Must be the destination
echo "SUCCESS";
}
else{
header('location:login.php'); // <-- I'm always directing here
echo "FAILED";
}
}
else{
header('location:login.php');
echo "FAILED";
}
If you are getting redirected to the login.php page, please keep in mind the following:
1) Unless you access that page with a POST request, you will always get the login.page. You have an if statement that looks like this:
if ($_POST) {
So if you access the page directly from the browser, you are redirected straight to the login.php page.
2) If you are getting redirected from the second else statement like you stated with your comment "<-- I'm always directing here" then your query is not returning any result. Your query looks fine. So check the credentials you are passing. Make sure it matches that of the database.
Is your html form using POST or GET in the method attribute. it should be using POST otherwise your database checking code will not be run
looking for some advice on my current setup and if there is a better approach (this is my first attempt at building an app like this) but I am at a point where I need user roles, only two so user and admin.
I have a users table and a groups table and also a join table which takes the ID from the users table and the Id from the groups table and I can allocate which group the user belongs too.
I am wanting to set a way to do a couple of things, prevent 'users' accessing the admin area by typing in the url /admin/index.php and also show a link on the index page if they are an admin and not see it it if they are a normal user.
Here is my code to demonstrate that I can show the users role title but struggling at this point:
<?php
$user = $_SESSION['user'];
try{
$results = $dbh->query("SELECT *
FROM groups
INNER JOIN user_group_link_table
ON groups.id = user_group_link_table.group_id
WHERE user_group_link_table.user_id = $user");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$group = $results->fetchAll(PDO::FETCH_ASSOC);
foreach($group as $groups){
echo
$groups["name"]
// show a link to admins that user do not see?
;}
?>
I am wondering if my approach is totally wrong?
UPDATE
<?
include('session.php');
if (!isset($_SESSION['user'])) {
header("Location: index.php");
}
if(!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
// This could be an include file for all admin pages
$isAdmin = false;
foreach($group as $groups){
if($groups['name'] === 'admin'){
$isAdmin = true;
break;
}
}
if(!$isAdmin){
header('Location: index.php'); // or some other arbitrary location
die();
}
?>
And I get this error:
Notice: Undefined variable: group in /Applications/MAMP/htdocs/dashboardr v3.2.3/admin/header.php on line 12
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/dashboardr v3.2.3/admin/header.php on line 12
I am wanting to set a way to do a couple of things, prevent 'users' accessing the admin area by typing in the url /admin/index.php and also show a link on the index page if they are an admin and not see it it if they are a normal user.
I'll give you a solution that'll work in your current setup; It's not the way to go, but i'll get the job done for now. If you're worried about the user being in a specific role, you're better off specifying that role in your query rather than iterating through all their potential roles.
// This could be an include file for all admin pages
$isAdmin = false;
foreach($group as $groups){
if($groups['name'] === 'admin'){
$isAdmin = true;
break;
}
}
if(!$isAdmin){
header('Location: index.php'); // or some other arbitrary location
die;
}
You'll want to place this at the top of the page, before you spit out any kind of HTML.
I am using html, PHP and MySQL(phpmyadmin). This might be a very simple question but I am a beginner so this is very new to me. My system has has 4 types of users.
Lets say user type 1 has a username Tom, user type 2 has a username Alice, user type 3 has a username Mike and user type 4 has a username Mary.
I want the Login page to identify which type of user it is when the username is written. For instance, if it is Tom, I want the system to identify that he is user type 1 and redirect him to a specific page. Likewise if it is Alice, her user type should be identified and she should be redirected to another page. Not the same page as user type 1.
Please let me know of the simplest ways this could be achieved. Thank you so much in advance.
This is what I have done so far. But it is not working. Please let me know what I have to do.
if (isset($_POST['username'])) {
$username = $_POST ['username'];
$password = $_POST ['password'];
$usertype = $_POST ['user_type'];
$sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."' LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
if ($username ['user_type'] == admin) {
header('location: localhost/adminhomepage.php');
}
else if ($username ['user_type'] == po) {
header('location: localhost/pohomepage.php');
}
else if ($username ['user_type'] == pw) {
header('location: localhost/pwhomepage.php');
}
else if ($username ['user_type'] == ps) {
header('location: localhost/pshomepage.php');
}
else{
echo "error determining user type!";
exit();
}
}
else {
echo "Invalid login information. Please try again.";
exit();
}
}
Try this, create a separate column like role in mysql.Based on the usertype put values in that column like if usertype 1=role is 1 ,usertype 2=role is two...
On particular login based on value in column name role,redirect user to the with respective page.
Thanks
Add a new column in your database for user type. It usually makes sense to create the column with a default value unless they will always be unique.
/*/your SQL query/*/
//if you need to validate type throughout the site, setup sessions as #Rasclatt suggested//
if ($user['type'] == 1) {
header('location: http://domain.com/page1.html');
}else if ($user['type'] == 2) {
header('location: http://domain.com/page2.html');
}else if ($user['type'] == 3) {
header('location: http://domain.com/page3.html');
}else if ($user['type'] == 4) {
header('location: http://domain.com/page4.html');
}else{
echo "error determining user type!";
exit;
}
add a column in your user table named user_type.
add user type while user registration.
after that while log in you can check by your query which user type is logging in.
and if you want to show your user type on next page, you can store user_type in session.
feel free to ask any further problems.
I hope this can help you.
First of all you need a MySQL skills to get what you want, because the user type/role depends on different MySQL table's.
for example...
In almost every website you notice that there is a admin, user and also some has their one sub admin or many. All have their different rights and when they try to login then each one redirect to their specified page, like user will be redirected to home page, admin's will redirect to admin panel index etc..
Now you need to create different table for each user in MySQL and assign them different rights, or you can also create different column based on Boolean values like 0 for some action and 1 for some action...
Hope it will help you...
EDIT: This is based on your last code addition edit
// Needs to be at the top of every page
// This is used to recall your user status
session_start();
if (isset($_POST['username'])) {
// You need to sanitize this or you have a potential security issue
$username = mysql_real_escape_string($_POST ['username']);
// You should not be storing in plain text. You should have this encrypted
// You should store it with PHP's latest encryption functions or at least do
// a salt + hash.....but at least do a hash
// hash("sha512", $_POST['password']);
$password = mysql_real_escape_string($_POST['password']);
// I am not sure of the relevance of this field
$usertype = $_POST['user_type'];
$sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."' LIMIT 1";
// You should be using mysqli_ or PDO with prepared statements
$query = mysql_query($sql);
// You need to fetch the results. All you have done is check if user exists
if (mysql_num_rows($query) == 1) {
// Fetch results
$user = mysql_fetch_assoc($query);
// You should set results to a session for later checking
$_SESSION['user_type'] = $user['user_type'];
$_SESSION['username'] = $user['username'];
// You have to quote the checks or they are invalid
if ($_SESSION['user_type'] == 'admin') {
header('location: localhost/adminhomepage.php');
}
else if ($_SESSION['user_type'] == 'po') {
header('location: localhost/pohomepage.php');
}
else if ($_SESSION['user_type'] == 'pw') {
header('location: localhost/pwhomepage.php');
}
else if ($_SESSION['user_type'] == 'ps') {
header('location: localhost/pshomepage.php');
}
else{
echo "error determining user type!";
exit();
}
}
else {
echo "Invalid login information. Please try again.";
exit();
}
}
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
Hi I made a login for a website.
I made a successful one using 1 account table in a database.
Now I made another table for another account. Both tables are different in attributes that is why I separated them.
I am having a hard time log-in the second one in by using this algorithim.
The inputted login and password come from another page using a HTML Form.
<?php
//Start session
session_start();
//Include database connection details
require_once("config.php");
require("clean.php");
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Sanitize the POST values
$login = clean($_POST['login']);
$password = clean($_POST['password']);
//Input Validations
if($login == '') {
$errmsg_arr[] = 'Login ID missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
//If there are input validations, redirect back to the login form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: login-form.php");
exit();
}
//Create query for patient
$qry="SELECT * FROM user_info WHERE login='$login' AND password='".md5($password)."'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful User
session_regenerate_id();
$user_info = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $user_info['ID_NO'];
$_SESSION['SESS_FIRST_NAME'] = $user_info['FNAME'];
$_SESSION['SESS_admin'] = $user_info['admin'];
$_SESSION['SESS_itResult'] = $user_info['itResult'];
//print "Login a success!";
session_write_close();
header("location: member-index.php");
exit();
}
else {
//Create query for
$qry="SELECT * FROM specialist_info WHERE spec_username='$login' AND spec_password='".md5($password)."'";
$result2=mysql_query($qry);
//Check whether the query was successful or not
if($result2) {
if(mysql_num_rows($result2) == 1) {
//Login Successful User
session_regenerate_id();
$specialist_info = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $specialist_info['spec_id'];
$_SESSION['SESS_FIRST_NAME'] = $specialist_info['name'];
$_SESSION['SESS_admin'] = 1;
//print "Login a success!";
session_write_close();
header("location: member-index.php");
exit();
}
else {
//Login failed
header("location: login-failed.php");
exit();
}
}
}
}
else {
die("Query failed");
}
}
?>
I was able to log-in the first(meaning there is connection between PHP and MySQL) account however I could not in the second.
From what i follow, I could not get in this one. "if(mysql_num_rows($result2) == 1)"
I know there is data in the second table in the database because i checked it(there is MD5 yes).
Maybe my logic is wrong. Suggestions? :D Thanks!
I'm not sure about the code (will review later) but you could try refactoring your tables so you have a separate table that contains user attributes, this allows you to be dynamic with your attributes so you don't have to create a different table every time you have a different type of user.
EDIT:
Try:
var_dump(mysql_num_rows($result2)) if this shows the return value is false something is wrong with the query, otherwise it doesn't match any rows.
Now I made another table for another account. Both tables are different in attributes that is why I separated them.
No.
They're both for the same purpose - You should be using a single table, and if you can't accomodate the differences between the 2 types of entities within a single table efficiently add 1 or 2 tables with a 1:1 non-oblig relationship.
But leaving that for now, even with this messy and potentially dangerous structure, you don't need 2 queries and all that code:
SELECT 'std' AS src, id_no, fname, admin, itResult
FROM user_info
WHERE login='$login'
AND password='".md5($password)."'
UNION
SELECT 'ext' AS src, spec_id AS id_no, name AS fname, 1 AS admin, NULL AS iResult
FROM specialist_info
WHERE spec_username='$login'
AND spec_password='".md5($password)
Obviously this breaks if you've got the same username/password in both - but really
if(mysql_num_rows($result) == 1) {
is redundant anyway - you only need to check
if ($row=mysql_fetch_assoc($result)) {
A lot of the code you've posted is irrelevant to the problem you've described - but the total absence of comments / logging / debugging provides us with little means of working out whats going on. The 2 combined strongly suggest that you've not bothered to clean out the irrelevant bits before poasting it here. Had you maybe included some debugging / logging functionality you might have been able to work it out yourself.