I imneed to display logged in/authenticated user's id in html page. My sign in script is below followed by the display script. I've been on it for quite a while. I need to display logged in user's id from the mysql database to html.
<?php
session_start();
include_once('server.php');
$error = false;
if(isset($_POST['btn-login'])){
$username = trim($_POST['username']);
$username = htmlspecialchars(strip_tags($username));
$password = trim($_POST['password']);
$password = htmlspecialchars(strip_tags($password));
if(empty($username)){
$error = true;
$errorUsername = 'Please Input Username';
}
if(empty($password)){
$error = true;
$errorPassword = 'Please Input Password';
}elseif(strlen($password)< 6){
$error = true;
$errorPassword = 'Password must be at least six characters';
}
if(!$error)
{
$password = md5($password);
$sql = "select * from users where username = '$username'";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
if($count==1 && $row['password'] == $password){
$_SESSION['username'] = $row['username'];
header('location: loggedin.php');
}else{
$errorMsg = 'Invalid Username or Password';
}
?>
//display script
<?php
session_start();
echo 'welcome user'.$_SESSION['id'];
?>
You need to set session like this.
$_SESSION['id'] = row['id'];
You are not getting the id value because $_SESSION['id'] is null.
to display the loged user
change this:
echo 'welcome user'.$_SESSION['id'];
to this:
echo 'welcome user'.$_SESSION['username'];
because $_SESSION['id'] is not set and you most probably dont want to show it in the html page so just use the user name or set it to somthing more natural like actual name if it exists in your db row.
Related
I am making a login form for my website. When I click submit on my login form it doesn't seem to run the SELECT statement as it is in my code.
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = '$passwordclean'");
if($row = mysqli_fetch_assoc($result)){
$finalmessager['success'] = 'You are logged in';
$_SESSION['finalmessager']= $finalmessager;
}else{
$finalmessager['fail'] = 'You are not logged in';
$_SESSION['finalmessager']= $finalmessager;
}
It seems to identify $emailclean but it doesn't seem to read $passwordclean. However, when I try to manually put the password such as
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = 'celenelqdekdnnd.......'");
it seems to work fine.
What am I doing wrong here?
This is my Code:
require "../config/init.php";
require "../config/config.php";
if(isset($_POST['submit'])){
$passwordclean = mysqli_real_escape_string($mysqli_conn, hash("sha512", $_POST['password']));
$emailclean= mysqli_real_escape_string($mysqli_conn, $_POST['email']);
$errorCheckr = array(); //an array is introduced to check errors
$finalmessager = array();//an array to display final message
if (empty($emailclean)) {
$errorCheckr['emailcheck'] = 'Please enter your email';
}else{
$_SESSION['email'] = $emailclean;
}
if (empty($passwordclean)) {
$errorCheckr['passwordcheck'] = 'Please enter your password';
}else{
$_SESSION['password'] = $passwordclean;
}
//Sanitize
if (!empty($emailclean) && !filter_var($emailclean, FILTER_VALIDATE_EMAIL)) {
$errorCheckr['emailvalidcheck'] = 'Your email is not valid';
}
if (strlen($email) > 50) {
$errorCheckr['emaillengthcheck'] = 'Your email is too long';
}
if (!empty($passwordclean) && strlen($passwordclean) < 5) {
$errorCheckr['passwordlengthcheck'] = 'Your password is too short';
}
if (empty($errorCheckr)) {
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '$emailclean' AND password = '$passwordclean'");
if($row = mysqli_fetch_assoc($result)){
$finalmessager['success'] = 'You are logged in';
$_SESSION['finalmessager']= $finalmessager;
}else{
$finalmessager['fail'] = 'You are not logged in';
$_SESSION['finalmessager']= $finalmessager;
}
unset($_SESSION['email']);
unset($_SESSION['password']);
header('location:../loginform.php');
}else{
$_SESSION['regErrors']= $errorCheckr;
header('location:../loginform.php');
}
}
First turn on errors:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
Test if post variable and password is set:
<?php
var_dump($_POST['password']);
var_dump($passwordclean);
Few tips:
1) Why save the password in a session?
2) You're checking the length of $passwordclean which will always be 128 chars since it is being hashed with sha512.
3) :
<?php
$result = $mysqli_conn->query("SELECT * FROM user WHERE email = '". mysqli_real_escape_string($mysqli_conn, $_POST['email']) ."' AND password = '". mysqli_real_escape_string($mysqli_conn, hash("sha512", $_POST['password'])) ."'");
I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>
I was wondering if anyone knows what is wrong with my php code and how I can fix it. Everytime I try to see if it works it just tells me "The information is incorrect, Click here to try again" but the problem is I haven't written in the username or password. It directly tells me that the information is wrong and try again. Can anybody help me and tell me what is wrong with my code and what
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
if(mysql_num_rows($sql) >0); // count the row nums
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
?>
You need set your if and else condition in the right place.
Try this.
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
if(mysql_num_rows($sql) >0); // count the row nums
while($row = mysql_fetch_array($sql)){
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
exit();
}
}else{
echo 'That information is incorrect, try again Click Here';
exit;
}
So I suppose your code is called "login.php". So instead of this else code
else {
echo 'That information is incorrect, try again Click Here';
exit();
}
You actually want to return the html form here.
else {
echo '<form class="login-form"> .........';
exit();
}
It's this line of code that is failing:
if (isset($_POST["username"]) && isset($_POST["password"]))
You need to write the HTML code that posts the username and password
Also, you probably meant to put your "else" condition after the SQL query, like this:
<?php
session_start();
if (isset($_SESSION["manager"])) {
header("location: index.php");
exit();
}
?>
<?php
// Parse the log in form if the user has filled it out and pressed "Log In"
if (isset($_POST["username"]) && isset($_POST["password"])) {
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["username"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password"]); // filter everything but numbers and letters
// Connect to the MySQL database
include "../storescripts/connect_to_mysql.php";
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"); // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
if(mysql_num_rows($sql) >0){ // count the row nums
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: index.php");
}
exit();
}else{
echo 'That information is incorrect, try again Click Here';
}
}
exit();
?>
So that if no results are returned from the query.. then you get the error message
Why are you using preg_replace to replace everything but numbers and letters on the userName and password fields? That prevents using many valid character such as !, ^, etc. It would be better for security if the user can use these characters in their passwords.
If it is malicious user input you are concerned about, you can runn all user input through a function, such as this:
function clean_input($var){// clean all user input
$var = strip_tags(stripslashes(trim(rtrim($var))));
$var = htmlspecialchars($var);
$var = mysql_real_escape_string($var);
return $var;
}
...and then run all user input data through the function like so:
$errors = array();
if (!empty($_POST['username'])) {//handle the user name input
$user_name = clean_input($_POST['user_name']);
} else {//user_name not entered
$errors[] = 'You forgot to enter a user name';
}
if (!empty($_POST['password'])) {//handle the password input
$user_id = '';
$password = clean_input($_POST['password']);
$q = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1";
$r = mysql_query($q);
while ($row = #mysql_fetch_array($r)) {
$id = $row["id"];
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
}
} else {//password not entered
$errors[] = 'You forgot to enter a password';
}
if(!empty($errors)){
echo '<h3 class="error">Error!</h3>
<p class="error">The following error(s) occurred:<br/>';
foreach($errors as $msg){
echo " - $msg<br/>\n";
}
echo '</p><p class="error">Please try again.</p>';
}else{
header("location: index.php");
}
I have the following code:
session_start ();
include 'core/init.php';
$username = '';
$password = '';
$dbusername = '';
$dbpassword = '';
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
$numrow = mysql_num_rows ($query);
// user login
if ($numrow!=0)
{
while ($row = mysql_fetch_assoc($query))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header('Location: member.php?username='.$username);
}
}
else
{
// admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
$numrow2 = mysql_num_rows ($query2);
if ($numrow2!=0)
{
while ($row = mysql_fetch_assoc($query2))
{
$dbusername = $row['Email'];
$dbpassword = $row['Password'];
}
//Check to see if they match
if ($username==$dbusername&&$password==$dbpassword)
{
$_SESSION ['Email']=$username;
header("Location: admin.php");
}else{
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
}
}
}
But if a user logs in incorrectly, none of the error messages are displaying, just a blank page, I think its my curly brackets but no matter how many times i change them i either make it worse or nothing at all. Can anyone tell me what im doing wrong?
Check out:
if (empty ($username) === true|| empty($password) === true) {
echo "Please enter a username and password";
} else if ($username!=$dbusername){
echo "That user does not exist! Have you registered?";
} else if ($username=$dbusername&&$password!=$dbpassword) {
echo "Incorrect password";
}
}
This section which includes login errors is found in the " admin login " section, therefore no error is seen when a non-admin user login fails.
Your select statement is already ensuring that the provided username and password match what is in the database. There is no need to do a second comparison in PHP. Your code could just be the following:
if (isset($_POST['Email']) && isset($_POST['Password']))
{
$username = $_POST['Email'];
$password = md5($_POST['Password']);
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 1)
{
$_SESSION['Email'] = $username;
header('location: member.php?username='.$username);
}
else
{
// try admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
if(mysql_num_rows($query2) == 1)
{
$_SESSION['Email'] = $username;
header("location: admin.php");
}
else
{
echo "Failed Login Attempt";
}
}
}
Since your query only returns records where the username and password match, there is NO way you will ever get a result back where the username matches but the password didn't, so your conditional check you do near the end of your admin login will NEVER occur.
As a side-note, it would be bad form to inform the user that the username was correct but password wasn't, or visa versa. This is a security issue and could make it easier for a malicious user to more easily gain access. This is besides the point though, so please only take this suggestion as personal advice and not directed at your question.
$query = mysql_query("SELECT * FROM member WHERE Email ='$username' AND Password='$password'");
if(mysql_num_rows($query) == 0){
echo 'You have entered wrong username/password'; }else {
// you can continue with your query below.
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;