PHP mysql bug query - php

Hi guys i've been working for straight 12 hours, i can't seem to find fix.
i'm trying to compare user-input to database result for example $username == $result echo "Username is aldready taken, but the problem is it's passing through 2 statements without a break, and if i put a break to exit the loop, it always check for $email == $result2 despite of not entering any email in the field.
if (isset($_POST['username']) or isset($_POST['email'])) {
$extract = mysql_query("
SELECT
`username`, `email`
FROM `users`
WHERE `username`='$username' OR `email`='$email'
");
$resultq = mysql_num_rows($extract);
while ($row = mysql_fetch_array($extract)) {
$result = $row['username'];
$result2 = $row['email'];
echo " " . $result;
echo " " . $result2;
if ($username == $result) {
echo " Username is already Taken!";
// break; //whenever i put break, it always gives me the else if statement echo, despite not entering any email in the field
} //$pass = $_POST['pass'];
else if ($email == $result2) {
echo "Email Address is already used!";
// break;
} else {
}
}
}

Upgrade from mysql to either MySQLi, or PDO.
However;
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}

See sniko for the answer to your initial problem. However, see the following...
You're not defining $username or $email
if ($username == $result ) should be
if ($_POST['username'] == $result )
or you could define $username and $email at the beginning of the conditional.
You should also change this:
isset($_POST['username']) or isset($_POST['email'])
to this:
isset($_POST['username']) && isset($_POST['email'])
because you depend on both in your query.
and as sniko said, switch to mysqli or PDO. mysql_ is deprecated.
full sample:
if(isset($_POST['username']) && isset($_POST['email']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT username, email FROM users where username='$username' or email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0) {
echo 'Either your username, or email is already taken!';
return;
}
}
Also note, you're not sanitizing the input. You could be hacked with this input. switching to mysqli or pdo and using prepared statements would help this.

Related

PHP - password_hash() verification

The following code should be straight forward and simple, the insert into the db on signup creates a hash, but later when I try to login with the same password the hash it is creating isn't matching up to what is in the database (I had print_r's throughout to verify). Can someone see if I'm just overlooking something dumb?
session_start();
require_once("login.php");
$error = "";
$email = "";
$password = "";
if (isset($_GET['logout'])) {
unset($_SESSION['id']);
setcookie('id', '', time() - 60*60);
$_COOKIE['id'] = "";
} else {
if (isset($_SESSION['id']) or isset($_COOKIE['id'])) {
header("Location: loggedinpage.php");
}
}
if (isset($_POST["submit"])) {
$link = mysqli_connect($hn, $un,$pw,$db);
if($link->connect_error) die("Fatal Errror.");
if (!$_POST["email"]) {
$error .="An email address is required<br>";
}
if (!$_POST["password"]) {
$error .="A password address is required<br>";
}
if ($error != "") {
$error= "<p>There were error(s) in your form:</p>".$error;
} else {
if ($_POST['signup'] == 1) {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link,$_POST['password']);
$query = "SELECT id FROM `users` WHERE email = '".$email."' LIMIT 1";
$result=$link->query($query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is taken.";
} else {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$query = "INSERT INTO `users`(`email`,`password`) VALUES ('".$email."', '".$hashedPassword."')";
if (!mysqli_query($link,$query)) {
$error = "<p>Could not sign you up, please try again later</p>";
} else {
$_SESSION['id'] = mysqli_insert_id($link);
if(isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', mysqli_insert_id($link), time()+60*60*24);
}
header("Location: loggedinpage.php");
}
}
} else {
$email = mysqli_real_escape_string($link, $_POST['email']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
$query = "SELECT * FROM users WHERE email = '".$email."' LIMIT 1";
$result = $link->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if ($email == $row['email'] and password_verify($password,$row['password'])) {
if (isset($_POST['stayLoggedIn']) and $_POST['stayLoggedIn'] == 1) {
setcookie('id', $row['id'], time()+60*60*24);
header("Location: loggedinpage.php");
}
} else {
$error = "Incorrect Username/Password combination";
}
}
}
}
}
Although it's tucked away at the end of a paragraph, PHP documentation does say that "it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice)."
The current default algorithm, bcrypt, generates hashes that are 60 characters long. If your database column cannot hold at least this many characters, your hashes will be truncated and verification will fail.
You've got a few other problems as well:
You're modifying the password before generating the hash (with mysqli_real_escape_string())
You're not using prepared statements
You appear to be relying on cookies for authentication. Cookies are user-generated data, they are not to be trusted! This is why PHP provides session support, because the data is stored on the server.
You should not be checking for an existing email address using a query, instead you should have a unique index set on the email column in the database.
try
if(password_verify($password, (string)$row->password)){
//Your Code
}
because of password_verify function return Boolean only true or false
And
$hashedPassword = password_hash($password,PASSWORD_DEFAULT);
Only add once when you Insert to Sql (new user)

PHP - variables not comparing to one another

I am doing a password reset page for my website and when a user puts a new password on the <form method="post" action="passVerif.php"> it goes to the PHP with this code:
Until now I cannot make the php compare the two new entered passwords to verify if they are equal or not, it simply jumps over that part.
P.S. don't mind the $senha = md5($password) it is like this for easy troubleshoot on localhost (MAMP).
<?php
session_start();
include("connectivity.php");
$user_id = $_SESSION['ResetUtilizadorID'];
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];
$sql = mysqli_query($conn, "SELECT FROM usuarios WHERE id =".$user_id."");
$password = $password1;
$senha = md5($password);
$adminID = $_SESSION['usuarioNiveisAcessoId'];
if (strcmp($user_id,$adminID) == 0) {
$_SESSION['avisoReset'] = "not possible to change admin password.";
header('Location: ../login/reset_password.php');
} else {
while ($row = mysqli_fetch_array($query)) {
if ($senha == $row['senha']){
$_SESSION['avisoReset'] = "password taken";
header('Location: ../login/reset_password.php');
}
}
if ($password1 == $password2){
mysqli_query($conn, "UPDATE usuarios SET senha = '".$senha."' WHERE id='".$user_id."'");
$sql = 'SELECT * FROM usuarios';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
$_SESSION['avisoReset'] = "new passoword set";
//header('Location: ../login/reset_password.php');
} else {
$_SESSION['avisoReset'] = "Passwords not equal!";
header('Location: ../login/reset_password.php');
}
}
?>
Why are you using strpos? strpos finds the position of the first occurrence of a substring in a string. So the password could be a subset of another string (the stored password) and still evaluate to true for your use case.
if (strpos($user_id,$adminID) == true)
You should instead use strcmp (Binary safe string comparison):
if (strcmp($user_id,$adminID) == 0)
I solved the problem by adding a username and then comparing the user input data to the DB. So the problem of multiple users by any chance use the same password it is all good.

If statement outputting same every time no matter what the user input

I want to echo a field from database IF two other fields that are entered are correct with their corresponding ones in the database.
example
Email: (enters email: (is it same as one in database))
Answer: (enters answer: (is it the same as one matching email in database?))
Code Echos.... Your password is here: (**********).
No matter the input on my code though, it always returns message ' Security Answer Correct' but then does not echo the variable.
PhP Code
$query = mysqli_query ($db, "SELECT * FROM admin where email = '$email' AND securitya = '$securitya'");
$password = mysqli_query ($db, "SELECT password FROM admin WHERE email = '$email' AND securitya = '$securitya'");
$passwordrow= mysqli_fetch_array ($password);
$result_password = $passwordrow ['password'];
$row = mysqli_fetch_array ($query);
if($row['email'] = $email AND $row['securitya'] = $securitya)
{
$_SESSION['email'] = $row['securitya'];
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Security Answer Correct');
</SCRIPT>");
echo ('<br>Password: ' . $result_password . '<br>');
}
else
{
die ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Incorrect Security Answer, Please Try Again')
window.location.href='passwordreset.php';
</SCRIPT>");
}
}
And I receive the error message:
Notice: Undefined variable: result_password in C:\xampp\htdocs\Intranet\passwordreset.php on line 118
What is Wrong with my statements is the question I am trying to ask.
Can anyone help?
Try with this code, I think this happens due to multiple query with same object.
$query = mysqli_query ($db, "SELECT * FROM admin where email = '$email' AND securitya = '$securitya'");
$row = mysqli_fetch_array ($query);
if($row['email'] == $email AND $row['securitya'] == $securitya)
{
$_SESSION['email'] = $row['securitya'];
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Security Answer Correct');
</SCRIPT>");
echo ('<br>Password: ' . $row['password'] . '<br>');
}
else
{
die ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Incorrect Security Answer, Please Try Again')
window.location.href='passwordreset.php';
</SCRIPT>");
}
}
You are setting the values in the line below (which is triggering a false positive for the if), instead of comparing them.
if($row['email'] = $email AND $row['securitya'] = $securitya)
Use == to compare:
if($row['email'] == $email AND $row['securitya'] == $securitya)
Your query might be failing, use the debugging functions available, add or die(mysqli_error($db)); after your queries to see if they're failing or not.
Edit 1
Seeing as you are using MySQLi you should use prepared statements to prevent SQL injections.
Edit 2
You are assigning values instead of comparing values, use == not = in your if statements.
Edit 3
Never trust user input, you should always sanitize all your input. Check out htmlspecialchars, intval, trim (not sanitizing but can be used to check for empty fields).
You have an extra space as typo.
Replace this $result_password = $passwordrow ['password'];
with this
$result_password = $passwordrow['password'];
Replace
if($row['email'] = $email AND $row['securitya'] = $securitya)
with
if($row['email'] == $email && $row['securitya'] == $securitya)

ISSET Php mysql [duplicate]

This question already has answers here:
isset() function is returning true even when item is not set
(4 answers)
Closed 9 years ago.
guys how come whenever i click submit button on my form without any data in the textbox, it's saying echo 'Either your username, or email is already taken!'; . How come it still passes through this despite of the form not having any data? what could be the best explanation?
if(isset($_POST['username']) && isset($_POST['email']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT * FROM users where username='$username'");
$resultq = mysql_num_rows($extract);
if($resultq > 0)
{
echo 'Either your username, or email is already taken!';
return;
}
}
Please hi'm stuck with this line for 12 hours, i can't seem to move on :(
isset renders true for empty string. it checks the existence of a variable. Here is a detailed explanation.
You should use if (trim($_POST['username']) != "")
if(isset($_POST['submit']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT * FROM users where username='$username'");
$resultq = mysql_num_rows($extract);
if($resultq > 0)
{
echo 'Either your username, or email is already taken!';
return;
}
}
You can also try !empty :
If you want to check both username OR email if already exist you also need to check email in select query
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$username = $_POST['username'];
$email = $_POST['email'];
$extract= mysql_query("SELECT * FROM users where username='$username' OR email='$email'");
$resultq = mysql_num_rows($extract);
if($resultq > 0)
{
echo 'Either your username, or email is already taken!';
return false;
}
else
{
echo 'Accept';
return true;
}
}

null values submitted to mysql database

I am trying to make a user system for my website but having some trouble with submitting it. It always submit a 0 to the database for everything. I have read on w3schools about global and local variables and I think this may be my problem but I don't know for sure.
Heres my code
<?php
$con = mysql_connect(localhost, 262096, 9201999);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("262096", $con);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$username = $_POST['username'];
$password = $_POST['password'];
$passwordconf = $_POST['passwordconf'];
$email = $_POST['email'];
$securityq = $_POST['securityq'];
$qanswer = $_POST['qanswer'];
if(!isset($firstname) || !isset($lastname) || !isset($username) || !isset($password) || !isset($passwordconf) || !isset($email) || !isset($securityq) || !isset($qanswer))
{
echo "You did not fill out the required fields.";
}
$uname = "SELECT * FROM users WHERE username='{$username}'";
$unamequery = mysql_query($uname) or die(mysql_error());
if(mysql_num_rows($unamequery) > 0)
{
echo "The username you entered is already taken";
}
$emailfind = "SELECT * FROM users WHERE email='{$email}'";
$emailquery = mysql_query($emailfind) or die(mysql_error());
if(mysql_num_rows($emailquery) > 0)
{
echo "The email you entered is already registered";
}
if($password != $passwordconf)
{
echo "The passwords you entered do not match";
}
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}
else
{
$salt = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
$hpassword = crypt($password,$salt);
$insert = "INSERT INTO users (firstname, lastname, username, password, email, securityq, qanswer, salt)
VALUES ('$firstname','$lastname','$username','$hpassword','$email','$securityq','$qanswer','$salt')";
mysql_query($insert);
if(!mysql_query($insert))
{
die('Could not submit');
}
else
{
echo "Information was submited. Please check your email for confirmation";
}
}
?>
Let me try to answer.
First of all, I agree with advice to move to PDO. mysql_* functions are deprecated. But if you wish to use it, escape every variable directly before sql due to '-symbols in your sql:
$hpassword = mysql_real_escape_string($hpassword );
As for me, the following syntax is easier to view rather than insert ... values():
$insert = "INSERT INTO `users`
SET `firstname` = '$firstname',
SET `hpassword` = '$hpassword'..."
Actually, I am trying to forgot this kind of code. I use PDO or comfortable uniDB class for simple apps.
Is it correct behaviour that it inserts user no matter errors like matching password? You should fix conditions.
Your conditions logic is wrong. You submit after if(!preg_match($regex, $email)). So if email is correct, it submits. Fix it as follows using ELSEIF
$regex = "/^[a-z0-9]+([_.-][a-z0-9]+)*#([a-z0-9]+([.-][a-z0-9]+)*)+.[a-z]{2,}$/i";
if(mysql_num_rows($emailquery) > 0){
echo "The email you entered is already registered";
}elseif($password != $passwordconf){
echo "The passwords you entered do not match";
}elseif(!preg_match($regex, $email))
{
echo "The email you entered is not in name#domain format";
}else{
// insertion code HERE
}

Categories