PHP Displaying user info when logged in - php

Alright, I have tried and searched everywhere to fix this but no luck.
All I am trying to do is display a users username and email (Who are logged in) and then print their details to thier account page.
The problem is that all of the users in the database are being logged, I only want the users who is logged in to be displayed.
Db.php
<?php
$myConnection= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "register") or die ("no database");
>
Auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
?>
Login.php
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($myConnection, $username);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($myConnection, $query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['user_id'] = $row['user_id'];
header("Location: index.php"); // Redirect user to index.php
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Register.php
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($myConnection, $username);
$email = stripslashes($email);
$email = mysqli_real_escape_string($myConnection, $email);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysqli_query($myConnection, $query);
if($result){
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Account.php //Where I want user data to be displayed on page
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>

$strSQL = "SELECT * FROM users";
Why that query? if you say you wanted to display only the info about users logged in, you are getting all users without conditions
Do the query for the user who is logged in at the moment, something like
$strSQL = "SELECT * FROM users WHERE username = '".$_SESSION['username']."'";
or somethinbg like this
<?php
session_start(); //Add this
//Also you have to add your connection file before your query
require('db.php');
// SQL query
$strSQL = "SELECT username, email FROM users WHERE user_id = '".$_SESSION['user_id']."'";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>
I think it should have to work, tell me if it worked for you

Related

password_verify() always return false

I am a newbie and I was trying to create a login system using PHP and Mysql. After finishing registration form and adding few users, I was trying to create a login form. but it always returns false saying my your Your username or password is incorrect!. Below is my code. It will be great if someone could help me. Advance sorry if my doubt is tooo basic :/
<?php
session_start();
include '.\includes\functions\db.php';
?>
<?php
$username = strtolower(mysqli_real_escape_string($db, $_POST['username']));
$password = strtolower(mysqli_real_escape_string($db, $_POST['password']));
$sql = "SELECT * FROM users WHERE username = '$username' ";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['password'];
echo $hash_pwd;
echo $password;
$hash = password_verify($password, $hash_pwd);
if ($hash ==0) {
header("Location: ./index.php?error=check");
exit();
}else {
$sql = "SELECT * FROM user WHERE username = '$username' AND password = '$hash_pwd'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 0) {
echo "Your username or password is incorrect!";
}else {
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['username'];
}
//header("Location: ./index.php");
}
?>
and my registration page is as follows
<?php
//This Page is for registration of users
?>
<?php
// this php tag is for all includes
include '.\includes\functions\db.php';
?>
<?php
//print isset($_POST["submit"]);
//Getting all details inserted in form
if(isset($_POST["register"])){
$username = $_POST['username'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$date = date('Y-m-d H:i:s');
//Encrypting and Securing recieved data
$username = strtolower(mysqli_real_escape_string($db, $username));
$firstname = strtolower(mysqli_real_escape_string($db, $firstname));
$lastname = strtolower(mysqli_real_escape_string($db, $lastname));
$email = strtolower(mysqli_real_escape_string($db, $email));
$password = strtolower(mysqli_real_escape_string($db, $password));
$encryptedpassword = password_hash($password, PASSWORD_DEFAULT);
//To check duplication of email ids
$sql = "SELECT email FROM users WHERE email='$email'";
$result = mysqli_query($db, $sql);
$row = mysqli_num_rows($result);//$row will return count of rows if any duplicate email ids are found
//To check duplication of usernames
$sql2 = "SELECT username FROM users WHERE username='$username'";
$result2 = mysqli_query($db, $sql2);
$row2 = mysqli_num_rows($result2);//$row2 will return count of rows if any duplicate usernames are found
//conditions to check what all duplicates are found
if($row > 0 && $row2 >0){
echo "Sorry...This email id and username is already taken!!!";
} elseif ($row > 0 ) {
echo "Sorry...This email id is already taken!";
} elseif ($row2 > 0) {
echo "Sorry...This Username is already taken!";
}else {
$query = mysqli_query($db, "INSERT INTO users (username, firstname, lastname, password, email, regdate) VALUES
('$username', '$firstname', '$lastname', '$encryptedpassword', '$email', '$date')");
if($query){
echo "Thank You! you are now registered.";
}
}
}
?>
The error in my code is because of password = '$hash_pwd' condition in my where clause. When i retried row with given username and later verified password using php, it works as intended. I guess password hashed in php using password_hash() cannot be retrived and verified like encryption. Anyway thanks for all of yours responses

get ID for a specific user in mysql database in PHP

When a user signs in i want to echo back there ID (which is created because of the auto_increment in phpMyAdmin) from there account, here's my login.PHP:
<?php
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
echo "Welcome: Buyer";
}else{
$int = 1;
//echo "Buyer login failed...";
}
}else{
echo "Login failed...";
}
}
mysqli_stmt_close($statement);
mysqli_close($conn);
?>
Add the column name id in your sql query.let say your column name for id is ID
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
echo $user_id;
echo "Welcome: Buyer";
}
Since your making login in php its good choice to use $_SESSION.
All you need to do is add a session_start(); at the top of any php script where you need to use session.
<?php
session_start();
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
//using session
$_SESSION["user_id"] = $user_id;
echo $user_id;
echo "Welcome: Buyer";
}
Now you can access anywhere in your php script using the $_SESSION variable.
echo $_SESSION["user_id"] ;
Let's start from the beginning. You create a login form, you store sessions based on the values:
login.php
session_start();
$_SESSION["username"] = $username;
main.page
$username = $_SESSION["username"];
echo "Hi $username";
EDIT 2
Ok, so you want to check if username exists and then echo their ID. Regardless, almost all login systems have sessions.
After logging in, let's say you have a $_SESSION of id.
php
session_start();
$id = $_SESSION["id"];
$db = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$check = $db->query("SELECT * FROM users WHERE id='$id'");
$num_check = $check->num_rows;
$fetch_check = $check->fetch_object();
$id2 = $fetch_check->id;
if($num_check) {
// User Exists
echo $id2;
} else {
echo "You don't exist."
}
Please note, normally, I would just echo $id. However, the OP requested to echo the id from the db, so I echoed $id2.

PHP won't check to see if a variable matches a part of a mysql row

<?php
include "config.php";
?>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
?>
<?php
$sql = "SELECT username FROM usr";
$resultuser = $conn->query($sql);
$conn->close();
$sql = "SELECT password FROM usr";
$resultpass = $conn->query($sql);
$conn->close();
?>
<?php
if ($resultuser == $username) {
if($resultpass == $password) {
echo "test";
} else {
echo "Wrong user or pass" ;
}
}
?>
Php won't send a query to mysql to check if the variable (username, and password) matches one of the rows in my mysql database.
I'm not sure what else to do
also config.php is the file which contains the code to connect to my mysql server.
you have to iterate over the obtained result as
$result = $conn->query($sql);
$resultUser= "";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$resultUser =$row['username '];
}
}
and you are doing it wrong. In order to check where the username and password match the database entry should be like :
select * from user_table
where username = 'pass_the_user_name' and password='user_password';
If this returns a row, that means this is a valid user else invalid credentials or anything.

Save $_SESSION on JQUERY $.POST

I have an HTML page in which I use Jquery .post() to post the forms into one big php file. I thought that this way I'll be able to save the username in a $_SESSION.
I have a login form that stores the username into a session, but then, when I try to display the php file (using .load()) in a different html page (linked to by the login one) I have no session variable set.
When I did a little debugging I found out the session is lost only if it's created in the if(isset($_POST['username'})) part of the page.
<?php
session_start();
include_once("connect.php");
$username = $_SESSION['username'];
//check if username is in session
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
?>
<div id="part_login">
<?php
//if not, check login
if(isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5($_POST['password']);
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$password' AND active='1' LIMIT 1") or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
echo "<div class='ui-btn'>Invalid Login Credentials</div>";
}
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
$query = mysqli_query($conn, "UPDATE `users` SET lastlogin=now() WHERE username='$username' LIMIT 1");
}else{
}
?>
</div>
<div id="part_user">
<?
echo $username . " " . $oldlogin;
?>
</div>

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories