why doesn't it want to check and then insert - php

for school i have to make a portfolio with a working login and registration system, the login part kinda works but by the regestration part i kinda got stuck. so why doesn't want to insert the users data after it checks the database of the username and email already exists? (hope u dont mind, but i am still a student who recently started with coding)
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg .= '<p class="error">The email address you entered is not valid!</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$query_username = "SELECT id
FROM members
Where username == '$username'
LIMIT 1";
$available_username = array();
if ($resultUsername = mysqli_query($mysqli, $query_username)) {
if (mysqli_num_rows($resultUsername) > 0) {
$error_msg .= '<p class="error">A user with this username already exists!</p>';
}
}
$query_email = "SELECT id
FROM members
Where email == '$email'
LIMIT 1";
$available_email = array();
if ($resultEmail = mysqli_query($mysqli, $query_email)) {
if (mysqli_num_rows($resultEmail) > 0) {
$error_msg .= '<p class="error">A user with this email adress already exists!</p>';
}
}
if (empty($error_msg)) {
$ipadress = $_SERVER['REMOTE_ADDR'];
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
$password = hash('sha512', $password . $random_salt);
if (!$tableRowEmail = 1) {
$sqlinsert = "INSERT INTO members (username, email, ipadress, password, salt) VALUES ($username, $email, $ipadress, $password, $random_salt)";
if (!mysqli_query($mysqli, $sqlinsert)) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
header('Location: ./register_success.php');
}
}
?>

Just a wild guess: You use == in your sql statements. I'm quite sure you should only use =

Field values are missing single quote '
all the fields are varchar datatype.Single quotes should be used for string values.
$sqlinsert = "INSERT INTO members (username, email, ipadress, password, salt) VALUES ('$username', '$email', '$ipadress', '$password', '$random_salt')";

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.

adding info (integer) to php registration form

Im trying to add more fields to my database registration form. I want to add "referrer" and have already added the columns in the database as well as the fields on the signup form. However I dont know what to change on the actual form that connects to the database (register.inc.php) Any ideas would be appreciated!
I have seen how to add strings (adding info to php registration form) but every time I try to add a number i get the error that is at the bottom.
Here is what I started with:
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if (empty($error_msg)) {
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
$password = hash('sha512', $password . $random_salt);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
}
header('Location: ./register_success.php');
exit();
}
}
This is What i tried and isn't working:
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
// Sanitize and validate the data passed in
$share = $_POST['share'];
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if (empty($error_msg)) {
// Create a random salt
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
// Create salted password
$password = hash('sha512', $password . $random_salt);
if(is_numeric($share)){
$share = $share;
}else{
$share = 0;
}
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (referrer, username, email, password, salt) VALUES (?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $share, $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
}
header('Location: ./register_success.php');
exit();
}
}

unknown column 'email' in where clause

I have problem with this code. It gives me 'Unknown column 'email' in where clause.
I tried almost everything, but I don't know what is the problem. I am beginner so please be gentle :)
Any ideas how to solve it?
Thanks a lot
session_start();
include('connect.php');
if(isset($_POST['submit']))
//when isn't username in form
if($_POST['firstname'] == '')
{
$_SESSION['error']['firstname'] = 'First name is required';
}
if($_POST['surname'] == '')
{
$_SESSION['error']['surname'] = 'Surname is required';
}
//when email isn't in form
if($_POST['email'] == '')
{
$_SESSION['error']['email'] = 'Email is required';
}
//check if is email in correct format
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['email']))
{
//email is in correct format and exist?
$email = $_POST['email'];
$sql1 = "SELECT * FROM users WHERE email = '$email'";
$result1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
if(mysqli_num_rows($result1) > 0)
{
$_SESSION['error']['email'] = 'Email is already used';
}
}
else
//error for wrong format of email
{
$_SESSION['error']['email'] = 'Your email is in wrong format';
}
//when isn't password in form
if($_POST['password'] == '')
{
$_SESSION['error']['password'] = 'Password is required';
}
//when is error -> registration form
/*if(isset($_SESSION['error']))
{
header("Location: index.php");
exit();
}
else
*/
{
$firstname = mysqli_real_escape_string($connect,$_POST['firstname']);
$surname = mysqli_real_escape_string($connect,$_POST['surname']);
$email = $_POST['email'];
$password = mysqli_real_escape_string($connect,$_POST['password']);
$phone_number = mysqli_real_escape_string($connect,$_POST['phone_number']);
$note = mysqli_real_escape_string($connect,$_POST['note']);
$sql2 = "INSERT INTO users (firstname, surname, email, phone_number, note, password) VALUES ('$firstname', '$surname',
'$email', '$phone_number', '$note','$password')";
$result2 = mysqli_query($connect, $sql2) or die('Error: ' .mysqli_error($connect));
the column name email may be wrong or does not exist in the data base use the same column name as defined in the data base

adding info to php registration form

Im trying to add more fields to my database registration form. I want to add "firstname" and "lastname" and have already added the columns in the database as well as the fields on the signup form. However I dont know what to change on the actual form that connects to the database (register.inc.php) Any ideas would be appreciated!
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
if (isset($_POST['username'], $_POST['email'], $_POST['p'])) {
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if (empty($error_msg)) {
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
$password = hash('sha512', $password . $random_salt);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $username, $email, $password, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
}
header('Location: ./register_success.php');
exit();
}
}
You'll need to:
Update your html form to add the new fields
Update your PHP code to read those values in with
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
$lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
Update the MYSQLi prepare to include the firstname and lastname (note the extra tags and ?'s)
$insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password, salt, firstname, lastname) VALUES (?, ?, ?, ?, ?, ?)"))
Update the bind to add the first name and last name
$insert_stmt->bind_param('ssssss', $username, $email, $password, $random_salt, $firstname, $lastname);
I would put it into an array, so it will save me time if I needed to add more columns.
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
$arr=['username','email','p','firstname','lastname','salt'];
$arrvalues=new Array(arr.length())
for($i=0;$i<$array.length();$i=$i+1){
if (isset($_POST[$arr[$i]]&& !empty($_POST[$arr[$i])) {
$arrvalues[$i] = filter_input(INPUT_POST,$arr[$i], FILTER_SANITIZE_STRING);
if($arr[$i]=="email"){
$arrvalues[$i]=filter_var($arrvalues[$i], FILTER_VALIDATE_EMAIL);
if (!filter_var($arrvalues[$i], FILTER_VALIDATE_EMAIL)) {
$error_msg .= '<p class="error">The email address you entered is not valid</p>';
}
}
if($arr[$i]=="password"){
if (strlen($arrvalues[$i]) != 128) {
$error_msg .= '<p class="error">Invalid password configuration.</p>';
}
}
}
}
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if($stmt){
$stmt->bind_param('s', $arrvalues[1]);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$error_msg .= '<p class="error">A user with this email address already exists.</p>';
}
} else {
$error_msg .= '<p class="error">Database error</p>';
}
if (empty($error_msg)) {
$arrvalues[5] = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
$arrvalues[2] = hash('sha512', $arrvalues[2] . $arrvalues[5]);
// Insert the new user into the database
for($i=0;$i<$array.length();$i=$i+1){
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (".$arrvalues[$i].") VALUES (?)")) {
$insert_stmt->bind_param('ssss', $arrvalues[$i]);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
exit();
}
}
}
header('Location: ./register_success.php');
exit();
}

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