Displaying data connected to the logged in user - php

I'm building a website where users log in and then are redirected to another page. I want to display their usernames and profile pictures in the top bar, but my code doesn't work.
I use the code below, which now that I think of it obviously couldn't work, bacause it will always display the first username and picture in the database. But I don't know how to fix that so that it displays the username and picture of the user who have logged in.
HTML and PHP
<?php
mysql_select_db($database_connection, $connection);
$query_user = "SELECT username, profilepic FROM user";
$user = mysql_query($query_user, $connection) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);
?>
<div id="top">
<img src="images/<?php echo $row_user['profilepic']; ?>">
<?php echo $row_user['username']; ?></a>
</div>
EDIT
Login script
<?php
if (isset($_REQUEST['login'])){
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = "SELECT * FROM `username` WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header('Location: content.php');
}else{
echo "Invalid Login Credentials.";
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
header('Location: content.php');
}
?>

store the usename in session after login code like this
<?php
session_start();
.......
//your php login code which validates the username and password ...
.......
//then here
$_SESSION['valid_user']=$username;//$username is who is logged in
now in the above use this session value like this
session_start();
$query_user = "SELECT username, profilepic FROM user where username=".$_SESSION['valid_user'];//or
$user = mysql_query($query_user, $connection) or die(mysql_error());
$row_user = mysql_fetch_assoc($user);
$totalRows_user = mysql_num_rows($user);

HTTP is a stateless protocol.
That means (for our discussion) that the server doesn't know that you are the same guy who logged in in the previous transaction he handled. Therefore you need to identify yourself each time.
This is accomplished with sessions. Session identifier is a unique string that identifies a specific client. In every request the client makes the session identifier is included either as a GET, POST or COOKIE variable.
It is unproductive and dangerous to send each and every time the user name and password to the server. What you should do instead is:
Check the username and password that the user sends to your php script. If the credentials are correct execute
session_start();
Then you should store the session identifier (which is a random string) returned from
session_id();
in a database table that has two columns. The first column is for your random string and the second for storing the primary key value of the row from your users table that holds the data of the user that sent you his credentials. An script that would do that is:
$userResult = mysql_query('select id from users where binary userName = \''.
mysql_real_escape_string($_POST['userName']) .'\' and binary passWord= \''.
mysql_real_escape_string($_POST['passWord']) .'\'');
if (mysql_num_rows($userResult))
{
start_session();
$userId = mysql_fetch_row($userResult);
mysql_query('insert into sessions (sessionId, userId) values (\''.
mysql_real_escape_string(session_id()) .'\', \''. (int)$userId[0] .'\')');
}else
{
//handle user supplying bad username or password
}
Each time the user sends a request you should find out who he is:
session_start();
$inputSessionIdentifier = mysql_real_escape_string(session_id());
$result = mysql_query('select * from sessions where sessionId = \''.
$inputSessionIdentifier .'\'');
if (mysql_num_rows($result))
{
// user is already logged in, lets find out his data
$sessionData = mysql_fetch_assoc($result);
$userResult = mysql_query('select * from users where id=\''.
mysql_real_escape_string($sessionData['userId']) .'\'');
$userData = mysql_fetch_assoc($userResult);
echo 'Hello '. $userData['userName'];
}else
{
//user is not logged in, ask for credentials or whatever ...
}
an example definition of the sessions table could be :
create table sessions ( sessionId varchar(255) not null,
userId int(10) unsigned not null,
unique(sessionId));
assuming that your users table has an unsigned integer primary key and is defined along the lines of :
create table users (id int(10) unsigned not null auto_increment primary key,
userName varchar(16) not null,
passWord varchar(100) not null,
unique(userName));
Have in mind that sessions must expire and the relevant table should be purged of inactive sessions. That means that a real life script would be a tad more complex...
IMPORTANT SECURITY ISSUE!
The sample above assumes that you are storing plain text passwords in your database. This is WRONG and a very poor security practice. Passwords should always be stored in an encrypted (hashed) form preferably the one generated by the blowfish cypher.

Related

Difficulty in Fetching data for logged in user

Here is my login process, I want a same dashboard but data will be different for each user. But I am stuck with creating uid variables to get data for each login user.
if(isset($_POST['login_btn']))
{
$email_login=$_POST['email'];
$password_login=$_POST['password'];
$admin="admin";
$co_admin="co_admin";
$query = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$admin' ";
$query_run = mysqli_query($connection, $query);
$query_co = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$co_admin' ";
$query_run_co = mysqli_query($connection, $query_co);
if(mysqli_fetch_array($query_run))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $admin;
header('Location: index.php');
}
else if(mysqli_fetch_array($query_run_co))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $co_admin;
header('Location: company_view.php');
}
else
{
$_SESSION['status'] = 'Email ID / Password / User Type is Invalid';
header('Location: login.php');
}
}
Above source code is for separating Co-admin and Admin. Now Any Co-Admin login to the portal he should get his own details, I would like to know which function I have to call or how should I declare a uid variable to fetch data tables for each current logged in user. I found some other source codes but which is not related to me so i am confused with how I fix it with those code. Can anyone do it in my codes.
I think you are asking how to get data for the current user from mysql tables. Yes, the standard way of doing this is via a unique ID for each user that is pulled from the registered_users table, storing this in the session, and then referencing this in the other tables and filtering by this ID. I would not suggest storing anything else from this table in the session as the ID is likely to have a stronger guarantee of imutibility.
For example if you have a table of recently visited pages per user, you would get this via:
$query = 'SELECT * from recently_visited WHERE user_id = ?';
$stmt = mysqli_prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
You can check the mysqli documentation for how to then extract what you need from the executed statement. I've shown this example of a prepared statement so you can see how to avoid SQL injection as well.
You may want to look into using foreign keys to enforce this connection.

PHP database user selection

Alright, so I have setup a very simple login in and sign up database, it is working perfectly.
However, one of the page I have created where users can check their acccount information (Username and Email) is not working fully.
I have a database that has four columns ID, username, email and password.
All I am doing is taking the user information from the database (Who is logged in) and displaying their username and email on the page.
The problem is that the code is logging every user within the database, I only want it to select one user (The user that is logged in.)
Code:
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['email'] . "<br />";
echo $_SESSION['username'];
}
// Close the database connection
mysql_close();
?>
I'm thankful for the help !
You probably need to store the username value in a $_SESSION in your login session.
if (!isset($_SESSION)) {
session_start();
$_SESSION['id'] = the_id_of_your_logged_username;
}
Then using the value that is stored in the $_SESSION to retrieve the logged user.
session_start();
$id = $_SESSION['id'];
$query = "SELECT * FROM users WHERE id='$id'";
In these way, you can retrieve the logged user, just commonly on how users login and gets their profile directly.
Your SQL query should look something like this...
"SELECT * FROM users WHERE ID = '$user_id'"
Remember to fix any SQL vulnerabilities
$user_id = mysql_real_escape_string($user_id);

Error with a authentication script. Password not recognize

I'm building a restricted area but I have some problems with password authentication. The system doesn't recognize the password stored into database
step by step. New user:
$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];
$sql = "INSERT INTO tbl_user (user_name, user_password, user_regdate)
VALUES ('$userName', PASSWORD('$password'), NOW())";
This works. I have a new user stored into database
Database: MySQL V5.6
`user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(20) NOT NULL DEFAULT '',
`user_password` varchar(32) NOT NULL DEFAULT '',
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
So I try to login (from login form):
// if we found an error save the error message in this variable
$errorMessage = '';
$userName = $_POST['txtUserName'];
$password = $_POST['txtPassword'];
// first, make sure the username & password are not empty
if ($userName == '') {
$errorMessage = 'You must enter your User Name';
} else if ($password == '') {
$errorMessage = 'You must enter your password';
} else {
// check the database and see if the username and password combo do match
$sql = "SELECT user_id
FROM tbl_user
WHERE user_name = '$userName' AND user_password = PASSWORD('$password')";
$result = dbQuery($sql);
if (dbNumRows($result) == 1) {
$row = dbFetchAssoc($result);
$_SESSION['plaincart_user_id'] = $row['user_id'];
// log the time when the user last login
$sql = "UPDATE tbl_user
SET user_last_login = NOW()
WHERE user_id = '{$row['user_id']}'";
dbQuery($sql);
// now that the user is verified we move on to the next page
// if the user had been in the admin pages before we move to
// the last page visited
if (isset($_SESSION['login_return_url'])) {
header('Location: ' . $_SESSION['login_return_url']);
exit;
} else {
header('Location: index.php');
exit;
}
} else {
$errorMessage = 'Username or password wrong';
}
}
return $errorMessage;
}
It seems that doesn't recognize the password function (), because if I write manually in the database password fiels a value not encrypted, it works...
You're using MySQL's PASSWORD function for a use it's not intended for. Aside from being a horrible idea from a security standpoint (plaintext passwords can end up in the logs), it also means that MySQL will silently truncate the password if the password field isn't long enough for it. This will results in password hashes that can never match.
You need to look into password hashing to make your passwords more secure and less prone to truncation errors (DO NOT USE MD5 OR SHA-1 FOR THIS! Even SHA-256 is dubious). You also need to determine how long a hash string will be for the method you've chosen and make sure the password field is big enough to take it.
http://php.net/manual/en/book.password.php

assign $_session var from object

This is a login script I am working on; It uses mysqli (I know it is not as secure as PDO)
After running the MySQL query I am fetch_object(). I am then assinging $_session to hold the user ID and email. $_SESSION['uid'] = $user->ID works but not $_SESSION['uemail'] = $user->email. Could this be because of email is stored in the object $user? Do I have to convert it somehow?
email is store ass a varchar(255) in the database ID is a int(11).
<?php
include_once("config.php");
$username = $_POST['username'];
$password = sha1($_POST['password']);
$query = "SELECT ID FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";
if ($result = $db->query($query)) {
while ($user = $result->fetch_object()) {
$_SESSION['uid'] = $user->ID;
$_SESSION['uemail'] = $user->email ;
header("Location: index.php");
//exit();
}
}else {
echo "Invalid login information. Please return to the previous page.";
//exit();
}
//var_dump(get_object_vars($result));
//$db->close();
?>
Thanks in advance.
Comment to answer:
You need to select the column(s) for which you are querying for:
SELECT ID, email FROM ...
which is why $_SESSION['uemail'] = $user->email ; is failing.
Either choose the specific column(s) in question, or a SELECT * would also work.
However and it's been said before, that using * isn't suggested, therefore select the actual column(s).
you are not selecting the email column from the database.
Try:
$query = "SELECT ID, email FROM user WHERE username = '$username' AND password = '$password' LIMIT 1";

Check login script letting in guests?

For some reason my check login script is letting in guests.
I have not made the site live yet so its all good.
I check the database for the username and the password the user puts in the html form but for some reason if it don't even get a result it still sets the username to nil
if it gets the result it sets the username to the username but if it don't get any results it sets the username to nothing.
I have a if statement but still setting it.
$myusername = mysql_real_escape_string($_POST['myusername']);
$mypassword = mysql_real_escape_string($_POST['mypassword']);
$sql = "SELECT * FROM users WHERE username='$myusername'";
$result = mysql_query($sql) or die(mysql_error());
$battle_get = mysql_fetch_array($result);
if ($battle_get['password'] == $mypassword)
{
$_SESSION['username'] = $myusername ; // store session data
header('Location: http://mydomainname.net/new_rpg/dashboard.php');
} else {
echo "wrong password" ;
}
You don't check if the user account actually exists. You just blindly fetch a row from the result set, even if that result set has NO records in it. That means $battle_get will be an empty array (or a boolean false if the query failed). You then do a string comparison against the submitted password. If that password is also empty, you're doing if (empty == empty) and boom... the user's in.
What you SHOULD be doing is:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "SELECT ... FROM users WHERE (username = '$username') AND (password = '$password')";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($sql) != 1) {
die("Invalid username and/or password"); // don't tell the user which failed.
}
Checking how many rows were returned is critical - if no rows are returned, then the user doesn't exist or the password is wrong. If 1 row is returned, then it's a valid login. If more than 1 row is returned, you've got duplicate username/password pairs in the database and need to fix that right away.
And, having just seen your "md5 is hard" comment above: You're dead wrong. MD5 is trivially EASY.
When you create the user record, you can hash the password easily:
INSERT INTO users (password) VALUES (MD5('$password'));
and for the login check:
SELECT ... WHERE (password = MD5('$password'));
Nothing to it at all.
Yur mistake:
Say I am not a user.
So $battle_get['password'] = false;
and $mypassword is also false,
so $battle_get['password'] equals $mypassword
Two way you can resolve this.
First, chek the password with sql:
$sql = "SELECT * FROM users WHERE username='$myusername' AND password = '$mypassword'";
or
if(!$battle_get) {
echo "wrong password" ;
}

Categories