I am creating a simple registration page using IBM Db2 and PHP and all my data is saved in the Db2 database. However, I can't keep the constraint of already existing username. It is registering the user even if the username is already there in Db2. Also, it is logging in with any password entered!
I couldn't understand when the entries are shown in the database it means the data has found the right connection to the database. Then why it is not catching the constraints logic.
I just changed the MySQL functions in Db2 for PHP and there are some functions which are giving me error vibes like db2_exec() and db2_fetch_assoc.
$user_check_query= "SELECT * FROM users WHERE username ='$username'"
$result = db2_exec($db,$user_check_query);
$user = db2_fetch_assoc($result);
if(!empty($user)){ // Not empty mean database already exist this username
array_push($errors,"Username exists");
}
the above raised query is solved in the following code snippet;
if(isset($_POST['signup'])){
$username = ($_POST['username']);
$email = ($_POST['email']);
$password = ($_POST['password']);
$confirm_password = ($_POST['confirm_password']);
//form validation
if(empty($username)) {array_push($errors, "Username is required");}
if(empty($email)) {array_push($errors, "Email is required");}
if(empty($password)) {array_push($errors, "Password is required");}
if($password != $confirm_password) {array_push($errors, "Passwords do not match");}
if(strlen($password)<6){array_push($errors, "Password must be at least 6 characters long");}
if (!preg_match($password_requirements, $password) ) {array_push($errors,"Password must contain at least one upper case , one lower case and one digit" );}
//check db for existing user with same username
$check_username = "SELECT * FROM people WHERE username = '$username'";
$check_email = "SELECT * FROM people WHERE email = '$email'";
$res_username = db2_exec($db, $check_username);
$user_username = db2_fetch_assoc($res_username);
$res_email = db2_exec($db, $check_email);
$user_email = db2_fetch_assoc($res_email);
if(!empty($user_username)){
array_push($errors, "Username already exists!");
}
if(!empty($user_email)){
array_push($errors, "Email already exists!");
}
//register user if no error
elseif (count($errors) == 0) {
//$password = md5($password);
$query = "INSERT INTO people (username, email, password)
VALUES ('$username', '$email', '$password')";
db2_exec($db,$query) or die("couldn't execute query..".db2_stmt_errormsg());
$_SESSION['username']= $username;
$_SESSION['success']= "You are now logged in";
//echo "you are now logged in";
header('Refresh: 0; URL=index.php', true, 301);
}
}
Just add another query to check username and password
$check_username_password= "SELECT * FROM users WHERE username ='$username' AND
password = '$password'";
$result = db2_exec($db,$check_username_password);
$user = db2_fetch_assoc($result);
if(!empty($user)){ // username match with the password
// Set your session here
// Redirect to the page you want
}
else{
// Show your error here
}
Related
I have a code below
//When user clicks on login button
if(isset($_POST['login-btn'])){
$email = $mysqli->real_escape_string($_POST['email']);
$password = $mysqli->real_escape_string($_POST['password']);
if(empty($email)){
$errors['email'] = "Email field is required";
}
if(empty($password)){
$errors['password'] = "Password field is required";
}
if(count($errors) == 0){
$sql = "SELECT * FROM accounts WHERE email=? LIMIT 1";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if(password_verify($password, $user['password'])){
$_SESSION['isLoggedin'] = true;
$_SESSION['name'] = $user['name'];
$_SESSION['birthday'] = $user['birthday'];
$_SESSION['id'] = $user['id'];
$_SESSION['email'] = $user['email'];
$_SESSION['username'] = $user['username'];
$_SESSION['verified'] = $user['verified'];
header('location: index.php');
exit();
}
else
{
$errors['wrongcred'] = "Wrong email/password combination";
}
}
}
I have declared $errors array for email and password. $errors['email'] = "Email field is required" - If email field is left empty, $errors['password'] = "Password field is required" - If password field is left empty, $errors['wrongcred'] = "Wrong email/password combination" - If user enters wrong credentials. When I enter email address that exists in database but wrong password its works as intended - shows that user entered wrong email/password combination. The problem is that when I enter email address that not exists in database, php gives me this "Notice: Trying to access array offset on value of type null", I want it to display as $errors array that user entered wrong email/password combination.
You can change this line:
if(password_verify($password, $user['password'])){
into this:
if(isset($user['password']) && password_verify($password, $user['password'])){
Explanation: when there is no such e-mail address, the SQL query returns no data (empty set). Therefore $user['password'] is not set at all (not existing). You try to pass this to the password_verify function and you get this notice.
In my proposed code, the if statement will evaluate false if the variable is not set and there will be no notice because the rules are parsed from left to right and there's && (logical AND - when the first one is false it knows that the whole will be false and it will never evaluate the second condition).
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 2 years ago.
Improve this question
This time i am trying to make a last seen on user profiles. I've added a column called lastseen in my phpmyadmin with type "DATETIME". When a user logs out, the lastseen should update to the date and hour it currently is. So i made an SQL in my logout script that updates this value. When i tested it, it was not working as always.. Tried many things but none are helping. I figured out that without my WHERE statement the date just updates as it should, but sadly for all users. So the WHERE statement is required in the SQL. And i added it back after testing without it but it's not working again, wich makes me sure its something with WHERE but i really don't see what.
This is my logout script:
<?php
session_start();
session_unset(); // Well.. One of these two will definitely work!
session_destroy();
// Updating
include('C:\xampp2\htdocs\settings\sh_config.php');
include('./static/index/scripts/session_start.php');
$conn = mysqli_connect($database['host'], $database['user'], $database['password'], $database['db'], $database['port']);
$last_timestamp = date("Y-m-d H:i:s");
$last_user = $_SESSION['username'];
$lastseen_query = mysqli_query($conn, "UPDATE users SET lastseen='$last_timestamp' WHERE username = '$last_user'");
header('Location: /');
$conn->close();
?>
The include of "sh_config.php" is private, but i will tell what it does in this script. Well simple answer: i configured the database connection in that file. So everything with $database is configured correctly in that file.
The script of the "session_start.php":
<?php
include('C:\xampp2\htdocs\settings\sh_config.php');
session_start();
// Initializing variables
$username = "";
$email = "";
$errors = array();
// Connect to the database
$db = mysqli_connect($database['host'], $database['user'], $database['password'], $database['db'], $database['port']);
// REGISTER USER
if (isset($_POST['reg_user'])) {
// Receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
$fname = mysqli_real_escape_string($db, $_POST['fname']);
$lname = mysqli_real_escape_string($db, $_POST['lname']);
$sex = mysqli_real_escape_string ($db, $_POST["sex"]);
$bday = mysqli_real_escape_string($db, $_POST['bday']);
// Form validation: ensure that the form is correctly filled ...
// By adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if (empty($fname)) { array_push($errors, "Firstname is required"); }
if (empty($lname)) { array_push($errors, "Lastname is required"); }
if (empty($sex)) { array_push($errors, "What is your gender?"); }
if (empty($bday)) { array_push($errors, "When is your cakeday?"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// First check the database to make sure
// A user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // If user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "Email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1); // Encrypt the password before saving in the database
$user_ip = $_SERVER['REMOTE_ADDR']; // Getting the IP of the user
$bio = $config['default-bio']; // Setting default biography
$profileimg = $config['default-profileimg']; // Setting default profile image
$timestamp = date('d.m.Y'); // Defining the current date
$query = "INSERT INTO users (username, bio, profileimg, regdate, email, password, firstname, lastname, gender, birthday, ip)
VALUES('$username', '$bio', '$profileimg', '$timestamp', '$email', '$password', '$fname', '$lname', '$sex', '$bday', '$user_ip')";
mysqli_query($db, $query);
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = TRUE;
$_SESSION['success'] = "You are now logged in";
// Generate user id
$generate_id_query = "SELECT id FROM users WHERE username='$username' ORDER BY id";
$get_id = $db->query($generate_id_query);
$gen_id = $get_id->fetch_assoc();
if ($gen_id['id'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst signing up, please refer to the helpcenter. (SE100)");
}
if ($get_id->num_rows > 0 && $gen_id['id'] > 0) { // Redirecting the user to his or her profile if it is a valid id
header('location: /content/users/profile?id=' . $gen_id['id'] . '');
}
}
}
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username or email is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE ( username='$username' OR email = '$username' ) AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
session_regenerate_id();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = TRUE;
$_SESSION['success'] = "You are now logged in";
// Get user id
$get_id_query = "SELECT id FROM users WHERE username='$username' ORDER BY id";
$get_id = $db->query($get_id_query);
$user_id = $get_id->fetch_assoc();
if ($user_id['id'] <= 0) { // Checking if the user id is a valid id (not below or equal to 0), and if not, displaying a critical error
array_push($errors, "Something went wrong whilst logging in, please refer to the helpcenter. (SE100)");
}
if ($get_id->num_rows > 0 && $user_id['id'] > 0) { // Redirecting the user to his or her feed if it is a valid id
header('location: /content/users/profile?id=' . $user_id['id'] . '');
}
}else {
array_push($errors, "Your credentials do not match our records");
}
}
}
?>
Well, as you see, theres alot of info in it. Basically, this manages everything of registering and logging in and redirecting to the unique profile with the user id. I thought this file might come in handy because the id and username are defined in this file. If you look good, you can see that i included this file to my logout script so the defined words should just work, but they don't. Trying to redefine it in the file without the include, doesn't work either. Oh by the way, i use MySQLi.
Help me out please, thanks already.
You have a bug in your code, in that when a user logs in with their email address that address is stored in $_SESSION['username']. In your log out script you assume that that is in fact their username where in reality it might not be. Change your update query to something like this and your problem might be solved:
UPDATE users
SET lastseen='$last_timestamp'
WHERE username = '$last_user'
OR email = '$last_user';
While this might work I would recommend making use of your precious user id. Instead of comparing strings, which are susceptible to various kinds of errors (letters with wrong case, leading/trailing white space, different encoding, etc.), compare your IDs. This not only makes things less error-prone but will also cut down your computation time, especially in the context of database lookups.
$_SESSION['user_id'] = $user_id['id']; // or $gen_id['id'] in the signup code.
$last_user = $_SESSION['user_id'];
$lastseen_query = mysqli_query($conn, "UPDATE users SET lastseen='$last_timestamp' WHERE id = '$last_user'");
To debug issues like this yourself in the future you can utilize a popular, quick-and-dirty way of dumping the contents of a variable: Print/echo the values of $username and $email when you create a user and echo the value of $username that is used in the above script to update the last seen value in the database like this:
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
var_dump($username);
var_dump($email);
$last_user = $_SESSION['username'];
var_dump($last_user);
If the dump of $last_user matches $email you know that the above bug applies and is the reason why your script(s) misbehave. You might also find there is some issue with the string values (maybe an unintended mutation at some point) which causes the comparison in your SQL query to fail.
This question already has answers here:
php mysql issue with check if record exist before insert
(4 answers)
Closed 3 years ago.
I'm coding PHP system , and I want it to check if the username is available in register page. I want to avoid two users in database with same username
I tried a lot of things but didn't get it to work.
This is my config.php:
// REGISTER USER
function register(){
// call these variables with the global keyword to make them available in
function
global $db, $errors, $username;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, user_type, password)
VALUES('$username', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: dashboard.php');
}else{
$query = "INSERT INTO users (username, user_type, password)
VALUES('$username', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: dashboard.php');
}
}
}
You should add a new error handle, checking if the username exist in the database.
$query="SELECT COUNT(username) as counter FROM users WHERE username='$username'";
$checkusername=mysqli_query($db, $query);
if($checkusername[0]->counter){
array_push($errors, "The username is already taken");
}
//Here your insert logic
I recently used a format for my login that stored the password in the database using $password = md5(password_1) full code below...
Then changed that to $password = (password_hash($password_1, PASSWORD_DEFAULT); full code below....
it successfully saved a hashed password in my database like:$2y$10$.FTJmF/47NbmQMU3nZGTZeKAHYZ8TBm8X2Jc.TLbAIK...
Now verifying the password is where something is going wrong,
The original code was $password = md5($password_1) which would successfully log me in with the md5 storing in the first code.
I changed that to $password = password_verify($password_1, PASSWORD_DEFUALT);
but thats giving me this error.
Ive tried $hash = password_verify($password_1, PASSWORD_DEFAULT );
but its giving me the same error,
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$errors = array();
// connect to the database
$db = mysqli_connect('', '', '', '');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM loginsystem WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
//Hashing the password
$password = password_hash($password_1, PASSWORD_DEFAULT);//encrypt the password before saving in the database
$query = "INSERT INTO loginsystem (username, email, password)
VALUES('$username', '$email', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: home.php');
}
}
// ...
// ...
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) $password = password_verify($password, PASSWORD_DEFAULT); {
$query = "SELECT * FROM loginsystem WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
apart from the typos there are two problems:
1st: password_verify() has different parameters: the typed password and the hashed password from database.
which leads us to the second problem:
You can only verify the password after you got the hash from the database.
So get that hash first (by querying for usename alone), than verify.
$query = "SELECT username, email, password FROM loginsystem WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$row = mysqli_fetch_assoc($results);
if(password_verify($password, $row['password'])) {
// password correct!
} else {
// nope
}
} else {
// wrong credentials
}
You should also change to a prepared statements, as this now could be vulnerable to sql injection.
PASSWORD_DEFUALT is misspelled. It should be PASSWORD_DEFAULT as in the example below:
$hash = password_hash($password, PASSWORD_DEFAULT);
[...]
if (password_verify($password, $hash)) {
// Password matches
}
The first parameter of password_verify is the user-entered password. The second parameter is the stored hash generated by password_hash.
I'm trying to figure out how to use PDO to login to my site give the user the option of either their email address or username once they are logged in, I checked some of the other answers but it doesn't seem to work for me.
Here is the code
<?php
if(isset($_POST['username']) || isset($_POST['password'])){
if(!$_POST['username'] || !$_POST['password']){
$error = "Please Enter your Username and Password";
}
So the issue stems from below, I tried adding an OR on the $query as I saw it from one of the other posts on here but doing that allows the user to login through email but not with username, if I remove "OR user_email" they can login through username but not E-Mail.
if(!$error){
//No errors - lets get the users account
$query = "SELECT * FROM users WHERE user_name OR user_email = :username";
$result = $DBH->prepare($query);
$result->bindParam(':username', $_POST['username']);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
if($row){
//User found - let’s check the password
if(password_verify($_POST['password'], $row['user_password'])){
$_SESSION['loggedin'] = true;
$_SESSION['userData'] = $row;
echo "<script> window.location.assign('index.php?p=viewprofile'); </script>";
}else{
$error = "Username/Password Incorrect";
}
}else{
$error = "Username/Password Incorrect";
}
}
}
?>
You SQL query is wrong:
$query = "SELECT * FROM users WHERE user_name = :username OR user_email = :username";
You forgot to compare the column user_name with the user input