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

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'];

Related

how to display user information in php?

I am trying to figure out how to display user information after they've logged in. I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users. I am also having trouble grabbing the header.
here's my code for login.php
<?php
session_start();
require 'dbh.php';
$username = $_POST['uname'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM registeredusers WHERE UserName = '$username'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$hashed_Password = $row['Password'];
$Dehash = password_verify($password,$hashed_Password);
if($Dehash == 0){
echo "username or password is incorrect";
exit();
} else{
$sql = "SELECT * FROM registeredusers WHERE UserName='$username' AND Password='$hashed_Password'";
$result = mysqli_query($connection,$sql);
if (!$row=mysqli_fetch_assoc($result)){
echo "Your User Name or Password is incorrect";
}
else {
$userid = $row['id'];
$_SESSION['UserName'] = $row['UserName'];
header("Location: userhomepage.php?user_id=".$userid);
}
}
?>
The following code redirects to userhomepage.php and the user ID is in the url can someone also tell me how do I grab the user ID from the url? I only started coding in PHP a week ago I am fairly new so if guys have any pointers for me that would be great.
I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users.
You should create a single page that displays user information based on session... you don't want to have to hand-make a new page every time a user signs up!
how do I grab the user ID from the url
echo $_GET["user_id"];

PHP MYSQL check if row data is the same as

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.

Get user info from mysql database

i am making my own php game. So far i have made almost everything. Now to finish it, i need to get id from user who is logged in. I'm not so familiar with the functions and sessions. Please help.
This is what i made so far:
In my index page people login. then they are redirected to this.
So $_POST['username'] is where user type his user name in index.
<?php
$username = $_POST['username'];
include("Files/config.php");
$connect = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if($connect) {
if(mysql_select_db(DB_NAME)) {
$sql = mysql_query("SELECT * FROM users WHERE `username`='$username'") or die(mysql_error());
$gatherinfo = mysql_fetch_array($sql);
global $getid;
$getid = $gatherinfo['id'];
echo $getid;
function getuid() {
$_SESSION['getuid'] = $getid;
echo $getid;
}
}
}
else{ echo "Can not connect";}
?>
I searched other scripts for this, i found on one it says just $session->uid and it shows his id from mysql.
In mysql database i have table users with info about them
Id, username, password (password is hashed), email,...
Please help me if you can :D
At the beginning of index file (where your user logging in) start named session (be careful to avoid echo or print any values before session_start:
<?php //index.php
session_name('SAMPLESESSION');
session_start();
then when you will get the logged User ID, write this value to the session variable, like this:
.....
$_SESSION['uid'] = $getid;
.....
in the script you was redirected by your index file start session with the same name and get your user ID:
<?php //redirectedfromindex.php
session_name('SAMPLESESSION');
session_start();
echo $_SESSION['uid'];
....
If I right understand you, these that you need.

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

Check if user is admin or normal user? PHP $_session and MYSQL

I want to show different content if a user is admin(2), or noarmal user(1). Login works fine, but i don't know hot to check if a user have 'usertype' 1 or 2? I want to use PHP $_SESSION.
This is my login form:
<!-- Log in -->
<form method="post" action="authentication.php">
<input type="text" name="userid" placeholder="E-mail" required/>
<input type="password" name="password" placeholder="Password" required/><br>
<button type="submit" name="submit" class="btn">Log in</button>
</form>
This is my authentication.php:
session_start();
if(isset($_POST['userid']) && isset($_POST['password'])){
$userid = $_POST['userid'];
$password = $_POST['password'];
$dbc = mysqli_connect('localhost', 'root', '', 'news');
if(!$dbc){
echo "Cannot connect to database";
exit;
}
$query = "SELECT * FROM users_tbl WHERE email = '$userid' AND password = sha1('$password')";
$result = $dbc->query($query);
if($result->num_rows)
{
$_SESSION['valid_user'] = $userid;
}
$dbc->close();
}
if(isset($_SESSION['valid_user'])){
header("location:prefs.php");
}else{
header("location:login.php");
echo 'Error';
}
This is what i have tried:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('news');
$sql = "SELECT users_tbl.usertype FROM users_tbl";
$result = mysql_query($sql);
$user = mysql_fetch_array($result);
$_SESSION['user'] = $user['user'];
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['user']['usertype'] == 2)
{?>
<h1>Only admin stuff</h1>
<$? }//Endif user is admin(2) ?>
Maybe instead of doing the query for everytime to check if a user is admin, i could save a $_SESSION['usertype'], and then use this to check if a user is 2, for admin, maybe when a user is loggin in? But i do not know how to do this. I'm quite new at this.
try this
if($_SESSION['usertype'] == 2)
{
//do stuff here
}
if ($_SESSION['usertype']) == 1)
{
//do stuff here
}
edit :
if you dont want write so many stuff and you want just include admin stuff inside this one of users just do this
if ($_SESSION['usertype']) == 1 or $_SESSION['usertype']) == 2)
{
//do stuff here for them both admin and users
if($_SESSION['usertype'] == 2 )
{
//do extra stuff here for only admin
}
}
I realize that this is an old question, however I have spent the last week searching the internet looking for an answer to this question as I have had a similar issue. "echo_Me" had the answer, but I see some incorrect syntax. After toying around with it on a localserver, this is what I did.
if($_SESSION['usertype']) == 1 or $_SESSION['usertype']) ==2)
//> start end < end < < end
{
//do stuff here for them both admin and users
if($_SESSION['usertype'] == 2)
{
//Do other stuff for usertype 2
}
}
You have more End Parenthesis then you do start ones.
I set all of the session variables I need when I run the login script for my website. So if I need a session variable, here is how I would handle it:
if($_SESSION['user']['usertype'] == 1 OR $_SESSION['user']['usertype'] == 2) { ?>
// Do Stuff for normal user and admin
<?php } if($_SESSION['user']['usertype'] == 2) { ?>
// DO Stuff for admin only
<?php } ?>
As you can see, the first if statement only has one set of parenthesis. And really, you can remove some of the php code, and just do regular html/css markup then the if statement for usertype of 2 for stuff for admin.
<!-- HTML Markup for both Admin and Regular Users Goes Here above if statement -->
<?php if($_SESSION['user']['usertype'] == 2 { ?>
// Markup for Admin only
<?php } ?>
Also, I would recommend not having the password set in the session variables. In that code, you may have it not do that, I am just unfamiliar with mysqli as I use PDO.
You can save your user type with session variable
Once logged in you need to check with db with the user type for 1 or 2 and store that variable with session variable like $_SESSION['user_type'].
So based on that you can track.
Try to add a column with user type to that table.
Check the value of that column while fetching data from the table. If the value is admin, show the text otherwise not.

Categories