Unable to echo response in php - php

I have two fields in my form email & password.
I am trying to make a registration from a single form
conditions are if your is registered he will be logged in, if not he will get registered.
Unable to get echo response
<?php
include_once('connection.php');
include_once('functions.php');
$username = $_GET['username'];
$password = $_GET['password'];
$response=array();
// Check if that username is already exists.
$find_user = mysqli_query($conDB,"SELECT * FROM `users_info` WHERE `username` = '".$username."'");
if (mysqli_num_rows($find_user) != 0) $error[] = "That username is already exist.";
if (empty($error)){
$hashed_password = sha1($password);
// Check if submitted info is correct or not.
$check = mysqli_query($conDB,"SELECT * FROM `users_info` WHERE `username` = '".$username."' AND `password` = '".$hashed_password."'");
if (mysqli_num_rows($check) == 1) {
$code="login_success";
array_push($response,array("code"=>$code,"email"=>$username));
echo json_encode($response);
} else if (empty($error)){
$result = mysqli_query($conDB," INSERT INTO `users_info` (
`username`,
`password`
) VALUES (
'".$username."',
'".$hashed_password."'
)");
if(confirm_query($result)) {
redirect('login.php?signup=1');
}
} else {
$error[] = "Incorrect username or password.";
}
}
?>

Related

Password_Hash not working on my PHP login

I am making a login and registration form and I use password_hash for password encryption, the problem is that when I log in it does not recognize my password and I get the error "the password is incorrect" (a message that I set). In the registration form there are no problems, but maybe it has to do with the error that I have.
Login.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header('Location: home');
}
if (isset($_POST["signin"])) {
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'");
if (mysqli_num_rows($check_email) > 0) {
$row = mysqli_fetch_array($check_email);
$_SESSION["user_id"] = $row['id'];
if (password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
}
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
}
?>
Now, if I change the $check_email = mysqli_query($conn, "SELECT id FROM users WHERE email='$email' AND password='$password'"); to $check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'"); I can enter the home, but with any password and not the one I registered with.
Registration.php
<?php
include 'connect/config.php';
session_start();
error_reporting(0);
if (isset($_SESSION["user_id"])) {
header("Location: home");
}
if (isset($_POST["signup"])) {
$full_name = mysqli_real_escape_string($conn, $_POST["signup_full_name"]);
$email = mysqli_real_escape_string($conn, $_POST["signup_email"]);
$password = mysqli_real_escape_string($conn, $_POST["signup_password"]);
$cpassword = mysqli_real_escape_string($conn, $_POST["signup_cpassword"]);
$token = md5(rand());
$check_email = mysqli_num_rows(mysqli_query($conn, "SELECT email FROM users WHERE email='$email'"));
if ($password !== $cpassword) {
$msg[] = "Passwords do not match";
} elseif ($check_email > 0) {
$msg[] = "The email already exists, try another.";
} else {
$passHash = password_hash($password, PASSWORD_BCRYPT);
$sql = "INSERT INTO users (full_name, email, password, token, status) VALUES ('$full_name', '$email', '$passHash', '$token', '0')";
$result = mysqli_query($conn, $sql);
if ($result) {
header('Location: login');
$_POST["signup_full_name"] = "";
$_POST["signup_email"] = "";
$_POST["signup_password"] = "";
$_POST["signup_cpassword"] = "";
$msg[] = "Registered user successfully.";
} else {
$msg[] = "User registration failed, please try again later.";
}
}
}
?>
I hope you can help me.
Review my code but my low level of knowledge in php prevents me from finding the error, I hope you can do it for me, I will thank you
You should not have and password = '$password' in the query. The password in the database is the hashed password, not the same as $password. You should just fetch the row using the email, then use password_verify() to check the password.
You also need to select the password column so you can verify it.
$check_email = mysqli_query($conn, "SELECT id, password FROM users WHERE email='$email'");
You also have problems with your logic. You set the session variable and redirect to home regardless of the password verification. It should be:
$row = mysqli_fetch_array($check_email);
if ($row && password_verify($password, $row['password'])){
$msg[] = "You have successfully logged in.";
$_SESSION["user_id"] = $row['id'];
header('Location: home');
} else {
$msg[] = "The password or email is incorrect.";
}
You also shouldn't escape the password before hashing or verifying it. And of course, if you correctly use prepared statements with parameters, you shouldn't escape anything first.

Can't login using password_verify

I'm trying to make a register/login system. The hashed passwords are saved into database successfully but when i try to login it says "Invalid login" which means it doesn't verify the password. Help me with this, it's my first time using password hash and verify
Signup.php
<?php
include('AdminPanel/connect.php');
$name = $_POST['txt_name'];
$email = $_POST['txt_email'];
$password = password_hash($_POST['txt_pass'], PASSWORD_DEFAULT);
$radioVal = $_POST['Gender'];
if($radioVal == "Male")
{
$radioVal = "Male";
}
else if ($radioVal == "Female")
{
$radioVal = "Female";
}
$queryget = mysqli_query($con,"SELECT Email FROM signup WHERE Email='$email'") or die ("Query didnt work");
$row = mysqli_fetch_array($queryget);
$emaildb = $row['Email'];
if($emaildb!=$email){
echo"success";
$insert = mysqli_query($con,"insert into signup (Name,Email,Password,Gender) values ('$name','$email','$password','$radioVal')");
}else{
echo"Email already exists";
}
?>
Login.php
<?php
include('AdminPanel/connect.php');
session_start();
$email = $_POST['txt_email'];
$password = $_POST['txt_pass'];
$info = mysqli_query($con,"select count(*) from signup where Email = '$email' and Password = '$password'");
$row = mysqli_fetch_array($info);
if (($row[0] > 0) && password_verify($password, $row['Password']))
{
$_SESSION['txt_email']=$email;
echo "success";
}
else
{
echo "Invalid login<br>Please re-enter your credentials";
}
?>
You're selecting count(*):
$info = mysqli_query(
$con, "select count(*) from signup where Email = '$email' and Password = '$password'"
);
But then referencing a field:
$row['Password']
You need to select (at least) the field, but leave out the condition on password because the password you get won't match what's in the database:
$info = mysqli_query(
$con, "select * from signup where Email = '$email'"
);
Also, don't do that, because SQL injection.

How to fetch data from two different tables in sql with single login form

I made two tables in SQL. first is login table and second is registration table. In login table I inserted a row of user admin and password admin, it works when I am logging in. But now I want to login from registration table. I means if an already registered user want to login how he can did it???
Following is my code, please help me.
when I trying to login as registered user it show me the error "invalid username or password":
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "invalid usernaem or password";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
if (isset($_POST['login'])) { //for the data of registraion table in sql
$username = $_POST['uname'];
$password = $_POST['password'];
$qry = "SELECT * FROM `registration` WHERE `uname`= '$username' OR `email`='$email' AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
}
?>
You need to query the registration table when the login query doesn't find anything.
<?php
include('../dbcon.php'); //Database connection included
if (isset($_POST['login'])) {
$username = $_POST['uname']; //data of login table in sql
$password = $_POST['password'];
$qry = "SELECT * FROM `login` WHERE `uname`='$username' AND `password`='$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
// not an admin, check registration table
$email = $_POST['email'];
$qry = "SELECT * FROM `registration` WHERE (`uname`= '$username' OR `email`='$email') AND `password` = '$password' ";
$run = mysqli_query($dbcon,$qry);
$row = mysqli_num_rows($run);
if ($row<1)
{
echo "password is incorrect";
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
else
{
$data = mysqli_fetch_assoc($run);
$id = $data['id'];
echo "Your Id is " .$id;
}
}
?>
You should also learn to use prepared statements instead of substituting variables into SQL, to protect against SQL-injection. See How can I prevent SQL injection in PHP?. And you should use password_hash() and password_verify() instead of storing plaintext passwords in the database.

Email activation issue

I'm building a site which requires users to register and login. I have the majority working but the bit that isn't working 100% is the email activation.
When the user registers it sends an email with a link (http://example.com/activate?email=name#example.com&activationCode=e7870fadcf79c39584dca1fc33c47ef9)
If the user clicks on this link it goes to /activate checks to see if the email and code exist in the database and activates the account by changing the value 'active' from 0 to 1 if these do exist but, if the user just logs in it automatically activates the account which I don't want (sort of defeats the purpose of the activation email).
LOGIN
if (isset($_POST['submit'])) { // Create variables from submitted data
$uname = mysqli_real_escape_string($db_connect, $_POST['uname']);
$password = mysqli_real_escape_string($db_connect, $_POST['loginPassword']);
$passHash = md5($password); // Encrypt password
$query1 = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `uname` = '".$uname."' AND `password` = '".$passHash."' AND `active` = '1' ") or die(mysqli_connect_error()); // Uname and password match and account is active
$result1 = (mysqli_num_rows($query1) > 0);
$query2 = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `uname` = '".$uname."' AND `password` = '".$passHash."' AND `active` = '0' ") or die(mysqli_connect_error()); // Uname and password match and account is not active
$result2 = (mysqli_num_rows($query2) > 0);
if ($result1) { // If uname and password match and account is active
$_SESSION['uname'] = $_POST['uname'];
header("Location: /profile");
} else if ($result2) { // If uname and password match but account is not active
echo "<p>Your account has not been activated! Please check your email inbox.</p><br />";
back();
} else { // If uname and password do not match
echo "<p>The combination of username and password is incorrect!</p><br />";
back();
forgotPword();
register();
}
} else {
login();
forgotPword();
register();
}
ACTIVATE PAGE
if (isset($_GET['email'], $_GET['activationCode']) === true) { // If email and email code exist in URL
$email = trim($_GET['email']);
$activationCode = trim($_GET['activationCode']);
$query1 = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `email` = '".$email."' ") or die(mysqli_connect_error());
$result1 = (mysqli_num_rows($query1) > 0);
$query2 = mysqli_query($db_connect, "SELECT * FROM `users` WHERE `activationCode` = '".$activationCode."' ") or die(mysqli_connect_error());
$result2 = (mysqli_num_rows($query2) > 0);
$query3 = mysqli_query($db_connect, "SELECT COUNT(`userID`) FROM `users` WHERE `email` = '".$email."' AND `activationCode` = '".$activationCode."' AND `active` = '0' ") or die(mysqli_connect_error());
$result3 = (mysqli_num_rows($query3) > 0);
// Check email exists in database
if ($result1) {
// Check activation code exists in database
if ($result2) {
// THIS IS THE PART NOT DOING IT'S JOB PROPERLY
// Check active status
if ($result3) {
mysqli_query($db_connect, "UPDATE `users` SET `active` = '1' WHERE `email` = '".$email."' AND `activationCode` = '".$activationCode."' AND `active` = '0' ") or die(mysqli_connect_error()); // Activate account
echo "<p>Your account is now activated. You may <a href='/login'>Log In</a></p>";
exit();
} else {
echo "<p>Your account has already been activated. You may <a href='/login'>Log In</a></p>";
exit();
}
// ------------------------------------------------------------------------------------
} else { // Activation code is invalid
echo "<p>Hmmm, the activation code seems to be invalid!</p>";
exit();
}
} else { // Email does not exist
echo "<p>Hmmm, ".$email." email does not seem to exist in our records!</p>";
exit();
}
} else {
header("Location: /login");
exit();
}
Any help on where i'm going wrong is much appreciated.
You could add an " AND active = 1" condition to your sql query on login
After several painful hours of looking through and rewriting code, I have figured out what was causing the issue.
It was actually the registration page where the email is sent. I have wrapped the activation link in the body of the message in single quotes and it now works perfectly. You see them in the email...
'http://www.example.com/activate?email=".$email."&activationCode=".$activationCode."'
but the link works so I am sticking with it.
Cheers for all your help, really appreciate it.

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