What is wrong with this PHP/MySQL code? - php

if(!empty($username) && !empty($email) && !empty($password) && !empty($confirm_password)){
$username = htmlentities($username);
$username = stripslashes($username);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$username = preg_replace("[^A-Za-z0-9]", "", $username);
$email = htmlentities($email);
$email = stripslashes($email);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$email = preg_replace("[^A-Za-z0-9]", "", $email);
if(strstr($email, "#") && strstr($email, ".")) {
require("$baseURL/scripts/connect.php");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$email'") or die(mysql_error());
$numrows_checkemail = mysql_num_rows($checkemail);
if($numrows_checkemail > 0) {
require("$baseURL/scripts/connect.php");
$checkusername = mysql_query("SELECT * FROM users WHERE username='$username'") or die(mysql_error());
$numrows_checkusername = mysql_num_rows($checkusername);
if($numrows_checkusername > 0) {
if($password == $confirm_password) {
$hashpass = md5(md5($password));
//All set to insert into the db
require("$baseURL/scripts/connect.php");
mysql_query("INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$hashpass')") or die(mysql_error());
$this->noticeMsg = "You have been signed up successfully!";
} else {
$this->errorMsg = "Uh-oh, looks like your passwords do not match!";
}
} else {
$this->errorMsg = "Oops, looks like that username is already in use! Please pick a different username.";
}
} else {
$this->errorMsg = "That email is already in use, please sign up with another email.";
}
} else {
$this->errorMsg = "Please enter a valid email address!";
}
} else {
$this->errorMsg = "Please fill in all the fields!";
}
The error I keep getting is "That email is already in use, please sign up with another email." even though the right file is being "required" and is connected to the database properly. The problem is most likely at the $numrows_checkemail part because when I use if($numrows_checkemail == 0) it works just fine. Why won't the ">" symbol work?
Am I doing something wrong?
Thank you

if($numrows_checkemail > 0) will return true only if $numrows_checkemail is bigger than 0.
You need to check for $numrows_checkemail == 0 or empty($numrows_checkemail)

The > is reversing your logic;
$numrows_checkemail > 0 is true if at least one user with that email already exists in the database (ie if there is more than zero rows in the database with that email)
$numrows_checkemail == 0 is true if no user with that email already exists in the database (ie if there isn't any row in the database with that email)

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 register suddenly not working- was working previously, but there are no errors

I am creating a register page, and it was working fine, however now when I go to create a new user it isn't working. It just keeps saying user could not be created. There are no errors that are appearing. This is my php code:
if(!empty($_POST['username']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['passwordagain'])) {
$fmsg = null;
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordRepeat = $_POST['passwordagain'];
if(strlen($username) < 2) {
$fmsg = 'empty username';
}
if($fmsg === null && !filter_var($email, FILTER_VALIDATE_EMAIL)){
$fmsg = 'invalid email';
}
if($fmsg === null && $password !== $passwordRepeat) {
$fmsg = 'passwords don`t match';
}
if ($fmsg === null) {
$email = mysqli_real_escape_string($conn, $email);
$username = mysqli_real_escape_string($conn, $username);
$sql = "SELECT COUNT(user_id) as user_count FROM zz_login WHERE username='$username' OR email='$email'";
$result = mysqli_query($conn, $sql);
if(!is_bool($result)) {
$user = mysqli_fetch_assoc($result);
mysqli_free_result($result);
if($user['user_count'] == 0) {
$password = password_hash($password, PASSWORD_BCRYPT);
$sql = "INSERT INTO zz_login (`username`, `email`, `password`) VALUES ('$username', '$email', '$password')";
$result = mysqli_query($conn, $sql);
if ($result) {
$smsg = "User Registered Successfully";
} else {
$fmsg = "User couldn`t be created";
}
} else {
$fmsg = 'User already exists';
}
} else {
$fmsg = 'ERR_QUERY_1';
}
}
if($fmsg === null) {
unset($fmsg);
}
}
If anyone has any answers as to why this could suddenly not work can you please let me know. As I have no idea, thank you
UPDATE: all other errors work, eg user already exists and passwords don't match

Making a change password and change email address in one form

I am currently programming php, and enjoying it.
I know how to code a script that will update a user's email address or password in different processes. I need to update them in one form. Here's a screenshot:
I need to update one of them, if he didn't enter a password then update the email, if he didn't enter the email update the password, if he entered both update both..
the script I am currently coding has been twirling around my mind and I have lost myself over and over and over...
update_settings_process.php: (I have Updated the script!!)
<?php
error_reporting(1);
session_start();
include("../common/config.php");
include("../common/conn.php");
$case = '';
$error_str = '';
//email:
$email = stripslashes($_REQUEST['email_address']);
//password:
$old_password = trim($_REQUEST['old_password']);
$password = trim($_REQUEST['password']);
$conf_password = trim($_REQUEST['conf_password']);
$get_users_qry = "Select password From users where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND password = '".md5($old_password)."' AND status = 1";
$get_users = $db->get_row($get_users_qry,ARRAY_A);
$qry = "Select email from users where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
echo 'Email:' . $email;
echo '<p>';
echo 'Old Password: '. $old_password;
echo '<p>';
echo 'Password:' . $password;
echo '<p>';
echo 'Confrim Password:' . $conf_password;
echo '<p>';
if(filter_var($email, FILTER_VALIDATE_EMAIL) && (strlen($password) > 5) && $get_users && !mysql_num_rows($res))
{
//update email and password
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo 'Email and Password Has been Updated!';
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "There is nothing to update";
echo $error_str;
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "Use a secure Password";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && (strlen($password) < 5))
{
$error_str .= "Password must be atleast 5 characters";
echo $error_str;
$case = 0;
die();
}
else
{
if ($email == '' && $password != $conf_password)
{
$error_str .= "Passwords Do not Match";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && !$get_users)
{
$error_str .= "Please enter correct old password <br>";
echo $error_str;
$case = 0;
die();
}
else
{
//update password only!
if(strlen($password) == 0)
{
die();
}
else
{
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Password changed successfully";
exit();
}
}
}
}
}
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
if($case = 0)
{
echo $error_str;
die();
}
?>
I have really lost myself in there, and I couldn't figure out why because of that..
I have updated the script:
it can update password and email at the same time
it can update password only
it can not update email only.. <-- im stuck here
here's the update email only part:
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
There are some mistakes in your if-clauses. Try changing them to something like this:
$email == ''
1) = is the assignment operator, == is the comparison operator, which you weirdly used correctly with the strlen($password) comparison. The mnemonic is "Twice is for T(w)sets, Once is for Owssignment" (works best in a North English accent).
2) You're doing something rather odd with the strlen() function. strlen() always returns an integer (until someone invents half-letters). Consequently, strlen == '' is a bad, bad test. What you would want that line to look like is this:
if ($email = '' && (strlen($password) == 0))
(though why you didn't use strlen() both times puzzles me!)
3) Do not, not even jokingly, use the word 'retard' in code, or at least be bright enough not to post it publicly. It's ableist and, frankly, stupid. There are loads of people on this board who are extremely experienced and would, were they not better (wo)men, think you to be one for using a single = to test. Never call your users, or indeed anyone, a 'retard'. It's not funny.

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
}

Php login issue

What is the wrong in my code. it's say... (1) Username required (2) Password is not correct if i click Log in button without username and password, but it' should be show All filed required.
<?php
if(isset($_POST['action']) && isset($_POST['action']) == "Sign in")
{
include("../secure/content/database/db.php");
$uname = mysql_real_escape_string(trim($_POST['uname']));
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
/// check user name
$sql = mysql_query("SELECT uname FROM members WHERE uname = '$uname'");
$num_u = mysql_num_rows($sql);
// check user password
$sql2 = mysql_query("SELECT pass FROM members WHERE pass = '$pass'");
$num_p = mysql_num_rows($sql2);
$err = array();
if(isset($uname) && isset($pass))
{
if( empty($uname) && empty($pass))
{
$err[] = "All field required";
}
else
{
if(empty($uname))
{
$err[] = "Username required";
}
else
{
if($num_u == 0) $err[] = "Username is not correct";
}
if(empty($pass))
{
$err[] = "Password required";
}
else
{
if($num_p == 0)
$err[] = "Password is not correct";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red>$er</font><br>";
}
}
else
{
include("content/include/newsession.php");
$tm = date("Y-m-d H:i:s");
$ip = $_SERVER['REMOTE_ADDR'];
$rt = mysql_query("insert into plus_user_login(id,uname,ip,tm, status, tm_out) values ('$_SESSION[id]','$_SESSION[uname]','$ip','$tm', 'ON', '')");
echo mysql_error();
print "<script>";
print " self.location='content/index.php';";
print "</script>";
}
}
}
Any idea or Solution..
On this line:
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
You are calling md5() which will always return a value, even if $_POST['pass'] was empty. So empty($pass) will never be true.
The md5() sum of an empty string or NULL does not result in an empty value, so you always have a value in $pass, even if $_POST['pass'] was empty.
// Never empty
$pass = md5(mysql_real_escape_string(trim($_POST['pass'])));
// Because:
var_dump(md5(""));
string(32) "d41d8cd98f00b204e9800998ecf8427e"
When you check for the presence of $uname & $pass, use the $_POST values instead:
// instead of
if( empty($uname) && empty($pass))
// do
if(empty($uname) && empty($_POST['pass']))
please remove this md5 from following line, md5 create a string if pass is empty.
md5(mysql_real_escape_string(trim($_POST['pass'])));
use this.
mysql_real_escape_string(trim($_POST['pass']));
use md5 in another.
Your are running into this problem because empty strings are hashable see this.
Change
if(isset($uname) && isset($pass))
to
if(isset($uname) && isset($_POST['pass']))

Categories