Am actually building a login and register system but having these internal error in the email activation part, when am trying to change the active table to 1, if users email and email_code matches.
the activate.php code :
<?php
} else if (isset($_GET['email'], $_GET['activation']) === true) {
$email = trim($_GET['email']);
$email_code = trim($_GET['activation']);
if (email_exists($email) == false) {
$errors[] = 'Ooops, We counldn\'t find that email address';
} else if (activate($email, $email_code) == false) {
$errors[] = 'Ooops, We had problem activating your account';
}
if (empty($errors) == false){
echo output_errors($errors) . '<br><br>';
} else {
header('Location : activate.php?success');
exit();
}
} else {
header('Location: index.php');
exit();
}
?>
The activate($email, $email_code) function :
function activate($email, $email_code) {
global $connection;
$email = $email;
$email_code = $email_code;
$active = 0;
$new_update_active = 1;
$stmt = $connection -> prepare('SELECT id FROM users WHERE email = ? AND email_code = ? AND active = ?');
$stmt -> bind_param('ssi', $email, $email_code, $active);
$stmt -> execute();
$stmt -> store_result();
$stmt -> fetch();
if ($stmt -> num_rows() == 1) {
$update_active = $connection -> prepare('UPDATE users SET active = ? WHERE email = ?');
$update_active -> bind_param('is', $new_update_active, $email);
return true;
} else {
return false;
}
}
The error:
The error image!!
The code is seems correct and am only having these intenal serval when it comes to the part that the email and email_code matches and to change the active table to 1 in the database.
I later spot the error and i just change the
header('Location : activate.php?success');
to
header('Location: activate.php?success');
Related
Hello I have been encountering this bug for a long time.
So basically here is by code:
function loginUser($conn, $username, $password) {
$checkExists = checkExists($conn, $username, $username);
if ($checkExists === false) {
header("Location: ../login.php?error=wronglogininfo");
exit();
}
$passwordHashed = $checkExists['password'];
$checkPassword = password_verify($password, $passwordHashed);
if ($checkPassword === false) {
header("Location: ../login.php?error=wronglogin");
exit();
} elseif ($checkPassword === true) {
$query = "SELECT * FROM users WHERE username='$username' AND password='$checkPassword'";
$query_run = mysqli_query($conn, $query);
$usertypes = mysqli_fetch_array($query_run);
if ($usertypes['usertype'] == "admin") {
header('Location: ../login.php?admin');
} elseif ($usertypes['usertype'] == "user") {
header('Location: ../login.php?user');
}
}
}
function checkExists($conn, $username, $email) {
$sql = "SELECT * FROM users WHERE username = ? OR email = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
} else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
And so the errors work fine.
The real problem is that whenever I login with correct credentials it sends me to a 404 page with a directory I never put. I want it to send be to the admin panel or user page. Can anyone help?
This select looks like a road to ruin: SELECT * FROM users WHERE
username='$username' AND password='$checkPassword' If $checkPassword
is the result of a password_verify(). (Also be careful about possible
SQL injection.)
I suspect this is your main issue. This would essentially translate your query to:
SELECT * FROM users WHERE username = 'tony' AND password = '1';
This will likely return an empty result set, but your very next if statement is expecting a user array populated with data.
if ($usertypes['usertype'] == "admin") {
header('Location: ../login.php?admin');
} elseif ($usertypes['usertype'] == "user") {
header('Location: ../login.php?user');
}
What happens now? You won't be redirected anywhere and the current script will continue processing. So what can you do?
If you already have the user row, via checkExists() (could this be
named better?), why do another call to the database to get the
usertype?
You already have access to your user array because you called checkExists above and verified it is not false. Just use the array directly.
I just cleaned up your code a bit and added in some comments. I did not alter your queries in any way and didn't verify they are correct.
function loginUser($conn, $username, $password) {
// Renamed this variable
// Validate it and use this variable for the remainder of the function.
$user = checkExists($conn, $username, $username);
if ($user === false) {
header("Location: ../login.php?error=wronglogininfo");
exit();
}
$passwordHashed = $user['password'];
// Renamed this variable.
$validPassword = password_verify($password, $passwordHashed);
if ($validPassword === false) {
header("Location: ../login.php?error=wronglogin");
exit();
}
// You now know you have a user and a valid password.
// No need to select them again
if ($user['usertype'] == "admin") {
header('Location: ../login.php?admin');
exit;
}
if ($user['usertype'] == "user") {
header('Location: ../login.php?user');
exit;
}
// What happens if `usertype` not matched? You still need to handle this case?
}
function checkExists($conn, $username, $email) {
$sql = "SELECT * FROM users WHERE username = ? OR email = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../register.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $email);
mysqli_stmt_execute($stmt);
$resultData = mysqli_stmt_get_result($stmt);
// Cleaned up this if statement
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
return false;
}
I am doing an android project and I've got a problem while logging into the account. I am able to login even if the password is incorrect or empty. I am unable to recognize the error. I have checked my code but nothing helped me Could anyone help me with this?
My Code:
userLogin.php
require_once '../includes/DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['username']) and isset($_POST['password'])){
$db = new DbOperations();
$result = $db->userLogin($_POST['username'], $_POST['password']);
if ($result == 1) {
# code...
$user = $db->getUserByUsername($_POST['username']);
$response['error'] = false;
$response['id'] = $user['id'];
$response['email'] = $user['email'];
$response['username'] = $user['username'];
$response['phone'] = $user['phone'];
$response['gender'] = $user['gender'];
$response['message'] = "Found successfully";
}
elseif ($result == 2) {
# code...
$response['error'] = true;
$response['message'] = "Some error occurred please try again";
}
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}
echo json_encode($response);
DbOperations.php
public function userLogin($username, $pass){
$password = md5($pass);
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ? AND password = ?;");
if($stmt != FALSE){
$stmt->bind_param("ss",$username,$password);
if($stmt->execute()){
return 1;
}else{
return 2;
}
$stmt->store_result();
$stmt->close();
else
{
var_dump($this->con->error);
}
}
public function getUserByUsername($username){
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ?;");
if($stmt != FALSE){
$stmt->bind_param("s",$username);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
else
{
var_dump($this->con->error);
}
}
please return the value if records found but you are returning the value if query executed successfully.
Your code :
if($stmt->execute()){
return 1;
}else{
return 2;
}
Should be :
if($stmt->num_rows > 0){
return 1;
}else{
return 2;
}
And as per your code if you enter wrong username than it should work to.
if($stmt->execute() != FALSE) is not correct. see below code:
public function userLogin($username, $pass){
$password = md5($pass);
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ? AND password = ?;");
if($stmt != FALSE){
$stmt->bind_param("ss",$username,$password);
$stmt->execute()
$stmt->store_result();
$rows = $stmt->num_rows;
$stmt->close();
return $rows;
else
{
var_dump($this->con->error);
}
}
public function getUserByUsername($username){
$stmt = $this->con->prepare("SELECT * FROM users WHERE username = ?;");
if($stmt != FALSE){
$stmt->bind_param("s",$username);
$stmt->execute();
return $stmt->get_result()->fetch_assoc();
}
else
{
var_dump($this->con->error);
}
}
I use User Cake for user management system but I am struggling with one problem, I have had asked this question in their website but I couldn't find anyone to help me out.
What I need is simply making the users be able to update their information. ex. first name, phone, email....The email field updates correctly as it came with that functionality.
The fields that I added aren't being updated. Can someone give me some hints on what I am missing?
Here is what I tried looking at the email field. I have First Name field.
Funcs.php
//Update a user's email
function updateEmail($id, $email)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
//Update a user's first name. This is what isn't working.
function updateFirstname($id, $firstname)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}
Here is class.user.php
class loggedInUser {
public $email = NULL;
public $hash_pw = NULL;
public $user_id = NULL;
public $firstname = NULL;
//Update a users email
public function updateEmail($email)
{
global $mysqli,$db_table_prefix;
$this->email = $email;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
email = ?
WHERE
id = ?");
$stmt->bind_param("si", $email, $this->user_id);
$stmt->execute();
$stmt->close();
}
//Update a users first name
public function updateFirstname($firstname)
{
global $mysqli,$db_table_prefix;
$this->firstname = $firstname;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."users
SET
firstname = ?
WHERE
id = ?");
$stmt->bind_param("si", $firstname, $this->user_id);
$stmt->execute();
$stmt->close();
}
}
user_settings.php where I can change the fields and hit the update button. If I change the email and hit update, the email is updated but when I change firstname and hit update I get
nothing to update
//Prevent the user visiting the logged in page if he is not logged in
if(!isUserLoggedIn()) { header("Location: login.php"); die(); }
if(!empty($_POST))
{
$errors = array();
$successes = array();
$password = $_POST["password"];
$password_new = $_POST["passwordc"];
$password_confirm = $_POST["passwordcheck"];
$errors = array();
$email = $_POST["email"];
$firstname = $_POST["firstname"];
//Perform some validation
//Feel free to edit / change as required
//Confirm the hashes match before updating a users password
$entered_pass = generateHash($password,$loggedInUser->hash_pw);
if (trim($password) == ""){
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
else if($entered_pass != $loggedInUser->hash_pw)
{
//No match
$errors[] = lang("ACCOUNT_PASSWORD_INVALID");
}
if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$loggedInUser->updateFirstname($firstname);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
if ($password_new != "" OR $password_confirm != "")
{
if(trim($password_new) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_NEW_PASSWORD");
}
else if(trim($password_confirm) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_CONFIRM_PASSWORD");
}
else if(minMaxRange(8,50,$password_new))
{
$errors[] = lang("ACCOUNT_NEW_PASSWORD_LENGTH",array(8,50));
}
else if($password_new != $password_confirm)
{
$errors[] = lang("ACCOUNT_PASS_MISMATCH");
}
//End data validation
if(count($errors) == 0)
{
//Also prevent updating if someone attempts to update with the same password
$entered_pass_new = generateHash($password_new,$loggedInUser->hash_pw);
if($entered_pass_new == $loggedInUser->hash_pw)
{
//Don't update, this fool is trying to update with the same password ¬¬
$errors[] = lang("ACCOUNT_PASSWORD_NOTHING_TO_UPDATE");
}
else
{
//This function will create the new hash and update the hash_pw property.
$loggedInUser->updatePassword($password_new);
$successes[] = lang("ACCOUNT_PASSWORD_UPDATED");
}
}
}
if(count($errors) == 0 AND count($successes) == 0){
$errors[] = lang("NOTHING_TO_UPDATE");
}
}
if($email != $loggedInUser->email)
{
if(trim($email) == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_EMAIL");
}
else if(!isValidEmail($email))
{
$errors[] = lang("ACCOUNT_INVALID_EMAIL");
}
else if(emailExists($email))
{
$errors[] = lang("ACCOUNT_EMAIL_IN_USE", array($email));
}
//End data validation
if(count($errors) == 0)
{
$loggedInUser->updateEmail($email);
$successes[] = lang("ACCOUNT_EMAIL_UPDATED");
}
}
Clone this function as
if($firstname != $loggedInUser->firstname) blah blah
Remove this line from the function above move it in the new function:
loggedInUser->updateFirstname($firstname);
Just clone the function,just as you have done above.Change the error messages and add function to validate the name,it will be somewhat different,it will require more work.
Okay, so I'm setting up the activation page using $_GET[] from the link the server emails the user.
Here's my activation page.
if (isset($_GET['success']) && $_GET['success'] == false) {
echo 'Your account has been activated, please login to continue.';
} else if (isset($_GET['email'], $_GET['email_code']) === true) {
$email = trim($_GET['email']);
$email_code = trim($_GET['email_code']);
if (email_exists($db, $_GET['email']) == false) {
$errors[] = 'This email address hasn\'t been registered with us.';
} else if (activate($db, $email, $email_code) === false) {
$errors[] = 'We had problems activating your account, please contact an Administrator.';
}
if (empty($errors) === false) {
echo output_errors($errors);
} else {
header('Location: activate.php?success');
exit();
}
} else {
header('Location: index.php');
}
I believe that to be fine, the problem lies within my function activate()
function activate(PDO $db, $email, $email_code) {
$stmt = $db->prepare("SELECT COUNT (`id`) FROM `users` WHERE `email` = :email AND `email_code` = :email_code AND `active` = 0");
$stmt->bindValue(':email', $email);
$stmt->bindValue(':email_code', $email_code);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
return $row ? $row->type : 0;
}
At this moment, I'm just trying to get it to return something, yet it doesn't.
What I really need, is for it to do this.
function activate($email, $email_code) {
$email = mysql_real_escape_string($email);
$email_code = mysql_real_escape_string($email_code);
if (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `email` = '$email' AND `email_code` = '$email_code' AND `active` = 0"), 0) ==1) {
mysql_query("UPDATE `users` SET `active` = 1 WHERE `email` = '$email'");
return true;
} else {
return false;
}
}
But I cannot quite translate it.
Any help would be appreciated, thanks.
I thought I'd add this doesn't return any errors, mainly because I haven't put anything in correctly yet for it to return one.
EDIT:
else if (activate($db, $email, $email_code) === 0) {
$errors[] = 'We had problems activating your account, please contact an Administrator.';
}
Then the function
function activate(PDO $db, $email, $email_code) {
$sql = "SELECT `active`, `email_code` FROM `users` WHERE `email` = '?'";
$stmt = $db->prepare($sql);
$stmt->execute(array($email));
$row = $stmt->fetch();
if ($row && $row['active'] == $email_code && !$row['active'] ) {
$sql = "UPDATE `users` SET `active` = 1 WHERE `email` = '?'";
$stmt = $db->prepare($sql);
$stmt->execute(array($email));
return $stmt->rowCount();
} else {
return 0;
}
}
function activate(PDO $db, $email, $email_code) {
$sql = "SELECT active, email_code FROM users WHERE email = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($email));
$row = $stmt->fetch();
$if ($row && $row['active'] == $email_code && !$row['active'] )
$sql = "UPDATE users SET active = 1 WHERE email = ?");
$stmt = $db->prepare($sql);
$stmt->execute(array($email));
return $stmt->rowCount();
}
}
Problem & Explanation
Hello I have just coded a function that first does checking if account exists in database with that name, and then if email exists in database with that entered email.
If not, return true + insert data.
But in this case, nothing happens on submit, it just shows the form, but doesn't inserts the data..
What is wrong with it?
function createAccount($name, $password, $email)
{
global $pdo;
$check_in = $pdo->prepare("SELECT * FROM users WHERE user_name = :username LIMIT 1");
$check_in->execute( array(':username' => $name) );
if (!$check_in->rowCount())
{
$check_in = email_exists($email);
if ($check_in === false)
{
$insert_in = $pdo->prepare
("
INSERT INTO
users
(user_name, user_password, user_email)
VALUES
(:name, :password, :email)
");
$insert_in->execute( array
(
':name' => $name,
':password' => $password,
':email' => $email
));
return true;
}
else
{
return 'exists';
}
}
else
{
return 'user_in_use';
}
}
function email_exists($email)
{
global $pdo;
$check = $pdo->prepare("SELECT * FROM users WHERE user_email = :email LIMIT 1");
$check->execute( array(':email' => $email) );
if ($check->rowCount())
{
return true;
}
else
{
return false;
}
}
This is how I make up the register:
# Creating shortcuts
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
}
# Creating errors array
$errors = array();
if (isset($_POST['submit']))
{
$check_in = createAccount($name, $password, $email);
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
}
}
Question:
What is wrong with this code & how do I fix this? I have no errors at all.
It just won't insert any data to the Database.
Yes, the PDO connection & statements are right, because the login works perfectly.
Thanks a lot!
EDIT!
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
} else {
echo 'Error is there...';
}
It's echoing 'Error is there...' apon submit!
I just want to slap myself!.....
The problem was: The fields were set as INT, therefore we could not store anything but ints...