Getting all info of the logged in user? PHP - php

HI
Could I fetch ALL the info from the user when he/she login and store it in sessions instead of having this piece of code on top of all pages to get username, email etc of the logged in user?
$userq = mysql_query("SELECT * FROM users WHERE id = {$_SESSION['id']}");
$auth_user = mysql_fetch_assoc($userq);
Login.PHP
$sql = mysql_query("SELECT id FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['id'] = mysql_result($result, 0, 'id');
header("Location: index.php");
}

Yes you (probably) could.
A couple of things to consider, though :
you might want to keep in session only what you need (to not have a giant session file with lots of useless data)
if the user updates his profile, you'll have to store the new data both in database, and in session -- which means a bit more works on the "edit profile" page.
if some other user (like an admin) edits a user's profile, you won't be able to change the session data of that user, and the updates will be loaded from database into the session only the next time the user logs in.
if this is something that happens frequently, you might want to refresh the data from databse every couple of minutes (but it's rarely the case on a "normal" website)

yeah, instead of getting just the id in the query, you get everything:
$sql = mysql_query("SELECT * FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['userdata'] = mysql_result($result, 0);
header("Location: index.php");
}

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

Session variables don't update on every page

On my website, there is a function for logging in and logging out. Upon login, I set the session variables pass (which is hashed password), uid which is the ID of the user logged in and loggedIn (boolean):
$hashedpass = **hashed pass**;
$_SESSION['pass'] = $hashedpass or die("Fel 2");
$_SESSION['uid'] = $uid or die("Fel 3");
$_SESSION['loggedIn'] = true or die("Fel 4");
header("Location:indexloggedin.php");
On every page, I check if the visitor is logged in by
Checking the status of $_SESSION['loggedIn'],
Searching the database for the user with the ID $_SESSION['uid'],
Checking if the hashed password in the database matches the hashed password in the session variable:
$sespass = $_SESSION['pass'];
$sesid = $_SESSION['uid'];
$sql2 = "SELECT * FROM `users` WHERE `id` = '$sesid'";
$result2 = mysqli_query($db_conx, $sql2);
$numrows2 = mysqli_num_rows($result2);
if ($numrows2 != 1) {
$userOk = false;
}
while ($row = mysqli_fetch_array($result2,MYSQLI_ASSOC)) {
$dbpass = $row['pass'];
}
if ($sespass != $dbpass) {
$userOk = false;
} else {
$userOk = true;
}
My problem is that this seems to be working on some pages, while it doesn't work at others. For example, when I log in, I am instantly logged in to the homepage, but not to the profile page. However, after a few reloads, I am logged in to the profile page as well. The same thing happens when logging out.
For testing purposes, I tried to var_dump the password variables as well as the userOk status on the index page, and this is where I noticed something interesting. When I log out, the password variables are set to be empty, and $userOk is false, according to what that is shown at index.php?msg=loggedout. But when I remove the ?msg=loggedout (and only leave index.php), the password variables are back to their previous value, and I am no longer logged out... After a few reloads, I am once again logged out.
Why is my session variables not working as expected? It feels like as if it takes time for them to update, which is very weird. I have tried with caching disabled (both through headers and through the Cache setting in my browser).
Just tell me if you need more info.
You have initialization session_start() on every Site?
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
After contacting my hosting provider, it was actually a hosting issue. It is now resolved!
Thanks,
Jacob

How do I make the Login page identify the type of users?

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();
}
}

unsuccessful PHP code

Can anyone tell me why this code is not working?? Any silly mistakes I made?
The Problem:
There is a login page. In the Login page i type in the ID and password and click enter. Once i click enter it will run the next file which is login_now.php. In my database, I have 2 entries. First entry the position is manager and 2nd entry position is staff. Logging in with manager is very successful while logging in with staff is a total failure...failure as in it never do what it should do it just return me back to log in page.
This is the code that is in login_now.php and this is what it suppose to do when enter button is clicked:
$query = "select * from emp where EID = '$myeid' and PASS = '$mypassword'";
//run the query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
//found a record?
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welmanager.php'); //redirect user to index
}
elseif (mysql_num_rows($result) > 0 and $row['POSITION']=="staff")
{
$_SESSION['eid'] = $myeid; //remember name as a session variable
$_SESSION['password'] = $mypassword; //remember password as a session variable
header('Location: welstaff.php'); //redirect user to index
}
else
{
header('Location: login.php'); //kick back to login
}
Let me know if more codes in the login.php should be shown here. Thanks in advance.
A minor error may locate in if condition.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
You have to use or condition rather than and,
if (mysql_num_rows($result) > 0 || $row['POSITION']=="manager")
Without wanting to jump on the bandwagon, the comments about session management being a solved problem are right - even if you chose not to use it, you can learn a lot from how they do it. Look at CakePHP, the Zend Framework, Symphony, even PEAR.
Secondly - SQL Injection! Even if this is not exposed to the wider internet, you can't necessarily guarantee that none of your staff are malicious.
Thirdly, it appears you store your passwords in plain text; this is a big nono. People often re-use their passports; someone who can steal your user records (using SQL Injection) can try those passwords on online banks etc. Read up on hashing passwords.
Fourthly, don't store the password in plaintext anywhere - but certainly not in the session object. You've already cover that...
The actual code looks syntactically okay, but there are some odd things.
if (mysql_num_rows($result) > 0 and $row['POSITION']=="manager")
Doesn't make sense! If there are no results, logically the $row array should be empty.
You're also not really distinguishing between legit "there's no match for username/pwd" situations and bugs such as having STAFF rather than staff in the type column.
I'd refactor it as:
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)// no match!
{
header('Location: login.php'); //kick back to login
}
//Maybe put in a catch for more than 1 record too - that would be a data bug.
$_SESSION['eid'] = $myeid; //remember name as a session variable
switch($row['POSITION']){
case "manager":
header('Location: welmanager.php'); //redirect user to index
break;
case "staff":
header('Location: welstaff.php'); //redirect user to index
break;
default:
echo ("Found unknown staff type. Error.");
}
Now you can see whether your record really isn't found - i.e. the username/pwd combo didn't match - or whether the user profile isn't of type "staff".

Sessions?? How can I display a the users row?

I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}

Categories