Script not getting values from the database [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
i have this user sign in script using php prepared statement, but it is not working i have tried to switch values but still not working sometimes i get a "user does not exit" error sometimes just a blank page with the redirected link.
if(isset($_POST['login'])){
require 'dbh.php';
$mail = $_POST['email'];
$pwd = $_POST['password'];
if (empty($mail) || empty($pwd)) {
header("Location: ../login.php?error=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE id=? OR email=?;";
$stmt = mysqli_stmt_init($db);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=error");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $mail, $pwd);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)){
$pwdCheck = password_verify($pwd, $row['password']);
if($pwdCheck == false) {
header("Location: ../login.php?error=wrongPassword");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['uId'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: ../profile/index.php?success");
exit();
}
}
}
}
} else {
header("Location: ../login.php");
exit();
} ```

I can see many mistakes in your code.
seems like you have missed entering the id param in the query.
Here you have mentioned id & email, "SELECT * FROM users WHERE id=? OR email=?;"
But here (mysqli_stmt_bind_param($stmt, "ss", $mail, $pwd);) you are binding $mail and password and not id and email.
You have used a extra semi colon ($sql = "SELECT * FROM users WHERE id=? OR email=?;";)

Related

password verify keeps returning wrong login credentials php

Every single time I try to log in, I tried several times with accounts in the database with passwords I am sure of, these are hashed then inserted into the database. However, whenever I use password_verify, I keep getting the error handler put in that says that the user has put wrong login credentials. Tried creating another user that contains ASCII character to check for encoding errors, but still didn't work.
<?php
require_once 'dbh.inc.php';
if (isset($_POST['login-submit'])) {
$username = $_POST['username'];
$pwd = $_POST['pwd'];
if (empty($username) || empty($pwd)) {
header('location: ../login.php?error=emptyfields');
exit();
} else {
$sql = "SELECT * FROM users WHERE username = ? OR email = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header('location: ../login.php?error=stmtfailed');
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
mysqli_stmt_close($stmt);
if (mysqli_fetch_assoc($resultData) == 0) {
header('location: ../login.php?error=usernonexistant');
exit();
}
$row = mysqli_fetch_assoc($resultData);
$pwdHashed = $row['pwd'];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false) {
header('location: ../login.php?error=wronglogincredentials');
exit();
} else if ($checkPwd === true) { /*review this bruh*/
session_start();
$_SESSION['uid'] = mysqli_fetch_assoc($resultData) ['uid'];
$_SESSION['username'] = mysqli_fetch_assoc($resultData) ['username'];
header('location: ../index.php');
exit();
}
}
} else {
header('location: ../login.php');
exit();
}
Your problem is that you are calling mysqli_fetch_assoc() four times, but you only have one row. This function is not idempotent. Each time you call it, the internal pointer moves on to the next row. You have complicated the code way too much. If mysqli is too difficult for you, please try PDO.
The same code can be rewritten to make it simpler. After some small refactoring the code will look like this:
<?php
require_once 'dbh.inc.php';
session_start();
if (!isset($_POST['login-submit'])) {
header('location: ../login.php');
exit();
}
if (empty($_POST['username']) || empty($_POST['pwd'])) {
header('location: ../login.php?error=emptyfields');
exit();
}
$username = $_POST['username'];
$pwd = $_POST['pwd'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? OR email = ?;");
$stmt->bind_param('ss', $username, $username);
$stmt->execute();
$resultData = $stmt->get_result();
$row = $resultData->fetch_assoc();
if (!$row) {
header('location: ../login.php?error=usernonexistant');
exit();
}
$checkPwd = password_verify($pwd, $row['pwd']);
if (!password_verify($pwd, $row['pwd'])) {
header('location: ../login.php?error=wronglogincredentials');
exit();
}
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
header('location: ../index.php');
exit();
In the above code, I removed the remaining three calls to mysqli_fetch_assoc() and used OO-style which is much easier to read. Be sure to enable mysqli error reporting. Read How to get the error message in MySQLi?

Display state of user from Session start when logged in [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 2 years ago.
I'm trying to display "active" or "inactive" when a user login with session start with php and mysql.
The problem is that even when I try to login with an account that has an "inactive" state, it keeps showing me that is "active". I already added session_start(); on the start of the page.
Here's a part of my login code:
$sql = "SELECT * FROM `users_tmp` WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ..index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = $row['pwdUsers'];
if($pwdCheck == false){
header("Location: ../index.php?error=wrongpwd");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idTmp'];
$_SESSION['idTmp'] = $row['idTmp'];
$_SESSION['stateUser'] = $row['stateUser'];
header("Location: ../user/perfil.php?login=success");
exit();
}
}
else{
header("Location: ../index.php?error=wrongpwds");
exit();
}
And here's what I'm trying to display:
<?php if(isset($_SESSION['idTmp']) ){
$state = $_SESSION['stateUser'];
if($state = "Active"){
echo $state;}
elseif($state = "Inactive"){
echo $state ;}
}
else{echo'nothing';}?>
$state = "Active" is always true, you need to use == operator instead, in the if.

Checking if an email exists in another table [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I'm doing an registration form and I'm trying to check if the email that the person inserts in the input is already in another table that has all emails that I allow to be registered. If it is it should register the person. I don't understand where I'm failing. I'm starting now with php. Please help.
<?php
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$username = mysqli_real_escape_string($conn, $_POST['uid']);
$email = mysqli_real_escape_string($conn,$_POST['mail']);
$password = mysqli_real_escape_string($conn,$_POST['pwd']);
$passwordRepeat = mysqli_real_escape_string($conn, $_POST['pwd-repeat']);
$check1 = $_POST['check1'];
$check2 = $_POST['check2'];
if(empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header ("Location: ../header.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidadmail&uid=");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../header.php?error=invalidadmail&uid=".$username);
exit();
}
else if (!preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidaduid&mail=".$email);
exit();
}
elseif($password !== $passwordRepeat){
header("Location: ../header.php?error=passwordcheck&uid=".$username."&mail=".$email);
exit();
}
elseif((!isset($check1)) || (!isset($check2))){
echo"<script>alert('É necessário confirmar as duas opções :(');
window.location.href='../header.php'</script>";
exit();
}
This is the part of the code that is not working
$sql2 = "SELECT * FROM emails WHERE (email_socio = '$email')";
$res = mysqli_query($conn, $sql2);
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
These are other validations and where it will insert the data into final table
else{
$sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if($resultCheck > 0){
header("Location: ../header.php?error=usertaken&mail=".$email);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql ="SELECT * FROM users WHERE uidUsers='$username' AND emailUsers='$email'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$userid = $row['idUsers'];
$sql = "INSERT INTO profileimg (userid, status) VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
}
}
header("Location: ../header.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../header.php");
exit();
}
Your condition is wrong:
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
You're checking for less than zero, when in fact it should be less than one.
So, change it to either of the two:
if (mysqli_num_rows($res) === 0) // it logically cannot contain negative values
if (mysqli_num_rows($res) < 1)

I would like to find out why my Login works on 000Webhost but does not work when I try on my system [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
When I signup successfully via the localhost file, it sends to the database successfully and echos success. But when I try using the same details to log in, it returns an error.
However, this is not the same via the hosted site. It works perfectly on 000webhost.
My login code:
<?php
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailusername = $_POST['useremail'];
$password = $_POST['userpwd'];
if (empty($mailusername) || empty($password)) {
header("Location: ../login.php?error=emptyfields");
exit();
}
else{
$sql = "SELECT * FROM `users` WHERE username=? OR email=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlError");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailusername, $mailusername);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['password']);
if ($pwdCheck == false) {
header("Location: ../login.php?error=wrongPwd");
exit();
}
else if($pwdCheck == true){
session_start();
$_SESSION['userId'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: ../index.php?login=success");
exit();
}
else{
header("Location: ../login.php?error=wrongPass");
exit();
}
}
else{
header("Location: ../login.php?error=noUser");
exit();
}
}
}
}
else{
header("Location: ../login.php");
exit();
}
My signup code:
<?php
if (isset($_POST['submit'])) {
require 'dbh.inc.php';
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordRepeat = $_POST['confirm_password'];
//if empty input
if (empty($fullname) || empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header("Location: ../signup.php?error=emptyfields&fullname="); //. $fullname."&username=". $username."&email".$email);
exit();
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-Z0-9]*$/", $username) ){
header("Location: ../signup.php?error=invalidemail&username=");
exit();
}
//if email is invalid return error
elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?error=invalidemail&fullname=");
exit();
}
//checking for valid password
elseif(!preg_match("/^[a-zA-Z0-9]*$/", $username)){
header("Location: ../signup.php?error=invalidusername&email=");
exit();
}
//check confirmed password
else if($password !== $passwordRepeat){
header("Location: ../signup.php?error=passwordRepeat&username=");
exit();
}
//if username is already taken
else{
$sql = "SELECT username FROM `users` WHERE username=?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
//did we get a match?
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if ($resultCheck > 0) {
header("Location: ../signup.php?error=usernametaken");// .$username);
exit();
}
else{
$sql = "INSERT INTO `users`(`fullname`, `username`, `email`, `password`) VALUES (?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../signup.php?error=sqlerror");
exit();
}
else{
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $fullname, $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else{
header("Location: ../signup.php");
exit();
}
I need help, please. As I need to integrate a dashboard but can't seem to get logged in the first place.
The column holding the password hashes created by password_hash() must be at least 60 characters in order to work properly. Please adjust the size of the column holding the hash, then reregister the users. Once done, the passwords will verify properly.
From the docs:
PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0). Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Information is not getting stored in session-cookie [duplicate]

This question already has answers here:
How do I get PHP errors to display?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
I just finished my login script on my website and I'm using sessions. I've set the variables but only the id and not the name and email is set in the cookie. I've tried multiple things but I'm learning and I can't get it fixed
<?php
if (isset($_POST['login'])) {
require 'db.inc.php';
$email = $_POST['email'];
$password = $_POST['password'];
if (empty($email) || empty($password)) {
header("Location: ../index.php?error=emptyfields&mailuid=".$email);
exit();
}
else {
$sql = "SELECT * FROM users WHERE name=? OR email=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $email, $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$hash = password_verify($password, $row['password']);
if ($hash == false) {
header("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($hash == true) {
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['name'];
$_SESSION['email'] = $row['email'];
header("Location: ../index.php?login=success");
exit();
}
}
else {
header("Location: ../index.php?login=wrongpassoremail");
exit();
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../diajsdians.php");
exit();
}
After this script I am logged in and theres a cookie there but no valuable info (session name is set to PHPSESSID with a value of c4ujtetrrn7k8d6b9ui2a7b2o7
I had to make the following changes:
was
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['name'];
$_SESSION['email'] = $row['email'];
fix
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['name'];
$_SESSION['email'] = $row['email'];

Categories