Username or Email already exist - php

Is it possible to split the Username or Email already exists into specific error messages?
I'm working on this user registration script, if you have any tips about the rest of code given would be much appreciated
if(isset($_POST['register'])){
if(
// check if posts not empty
empty($_POST['username']) ||
empty($_POST['email']) ||
empty($_POST['password']) ||
empty($_POST['re_password']) ||
$_POST['password'] != $_POST['re_password']
){
// if a field is empty, or the passwords don't match make a message
error = '<p>';
if(empty($_POST['username'])){
$error .= 'No username given<br>';
}
if(empty($_POST['email'])){
$error .= 'No email given<br>';
}
if(empty($_POST['password'])){
$error .= 'No password given<br>';
}
if(empty($_POST['re_password'])){
$error .= 'You must re-type your password<br>';
}
if($_POST['password'] != $_POST['re_password']){
$error .= 'Passwords don\'t match<br>';
}
$error .= '</p>';
}
else{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = $_POST['re_password'];
$query = mysqli_query(
$conn,"SELECT * FROM members WHERE username = '". $username ."' OR email = '". $email ."'");
if(mysqli_num_rows($query) > 0){
echo "Username or Email already exist";
}
else {
$sql = "INSERT INTO members (username, password, email)
VALUES
('$_POST[username]',
'$_POST[email]',
'$_POST[password]')";
if (mysqli_query($conn, $sql)) {
echo "Registered";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
}
}
if(isset($error)){
echo $error;
unset($error);
}

You need to change here only:--
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_assoc($query)){
if(isset($row['username']) && !empty($row['username']) && $_POST['username'] ==$row['username'] )){
echo "Username already exist";
}
if(isset($row['password']) && !empty($row['password']) && $_POST['password'] ==$row['password'] )){
echo "Password already exist";
}
}
}
Note:- if your password have some encryption then you need to change password part condition accordingly (just third part of it). Also if i missed any wher indexes in writing let me know.

Related

"Notice: Trying to access array offset on value of type null" being returned when username is entered wrong

I am trying to create a login page, and everything works as expected, except for when a wrong username is entered, I get the error Notice: Trying to access array offset on value of type null for the line if ($_POST['username'] != $row['username']) { in the below code, and I do not understand enough to fix it, as I am still pretty new to this. Any help or suggestions would be greatly appreciated. Any advice on proper ways to write and/or execute my code is welcome as well, thank you.
session_start();
$DATABASE_HOST = "localhost";
$DATABASE_USER = "root";
$DATABASE_PASSWORD = "";
$DATABASE_NAME = "tasktracker";
$link = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASSWORD, $DATABASE_NAME);
if (mysqli_connect_errno()) {
exit("Failed to connect to database: " . mysqli_connect_error());
}
//Server side form validation
if ($_POST) {
if (!$_POST['username']) {
$error .= "A username is required!<br>";
}
if (!$_POST['password']) {
$error .= "A password is required!<br>";
}
if (strlen($_POST['password']) < 8) {
$error .= "Your password must be greater than 8 characters!<br>";
}
if (strlen($_POST['password']) > 30) {
$error .= "Your password must be less than 30 characters!<br>";
}
if ($error != "") {
$error = '<div class=""><p><strong>There were issues(s) in your form:</strong></p>' . $error . '</div>';
echo $error;
} else {
//Log user in
$query = "SELECT * FROM users WHERE username = '".mysqli_real_escape_string($link, $_POST['username'])."' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);
if ($_POST['username'] != $row['username']) {
$error = "That username is incorrect.";
} else if (md5(md5($row['id']).$_POST['password']) != $row['password']) {
$error = "That password is incorrect.";
} else {
echo 1;
}
if ($error != "") {
$error = '<div class=""><p><strong>There were issues(s) in your form:</strong></p>' . $error . '</div>';
echo $error;
} else {
exit();
}
}
}```
change this line
if ($_POST['username'] != $row['username']) {
$error = "That username is incorrect.";
}
by
if (!$result) {
$error = "That username is incorrect.";
}
because if $result is false or has 0 items then no user was found with this username

My php is not entering the values into the sql database, what is wrong with my code?

I'm having this problem where I have a registration form and I am using PHP and MySQL. The problem is that even when all the data is valid it wont enter the information into the database. I know the database is connected because I can use it with the login part of my website. I think it is the problem with the email and username cross check against the database but I am not sure. Is the positioning of the curly braces or alot more complex?
<?php
include_once('db.php');
$name = mysql_real_escape_string( $_POST["name"] );
$username = mysql_real_escape_string( ($_POST["username"]) );
$password = mysql_real_escape_string( md5 ($_POST["password"]) );
$repeatpassword = mysql_real_escape_string( $_POST['repeatpassword'] );
$email = mysql_real_escape_string( $_POST["email"] );
$confirmemail = mysql_real_escape_string( $_POST['confirmemail'] );
// the below if statement is for when the user does NOT have JS enabled in their browser
if(empty($name) || empty($username) || empty($password) || empty($email)){
echo "(*) indicate that the fields are mandatory.";
exit();
}
if($email == $confirmemail){
exit();
}else{
echo "Your Email address does not match.";
}
if($email == $repeatpassword){
exit();
}else{
echo "Your Passwords do not match.";
exit();
}
$res = mysql_query("SELECT username FROM users WHERE username='$username'");
$row = mysql_fetch_row($res);
$res1 = mysql_query("SELECT email FROM users WHERE email='$email'");
$row1 = mysql_fetch_row($res1);
if( $row > 0 ){
echo nl2br("The username $username is already in use");
}else{
if( $row1 > 0 ){
echo nl2br("the email address $email is already in use");
}else{
$sql = "INSERT INTO users VALUES('','$name', '$username', '$password', '$email')";
if( mysql_query($sql) ){
echo "Inserted Successfully";
}else{
echo "Insertion Failed";
}
}
}
?>
if($email == $confirmemail) {
exit();
}
else {
echo "Your Email address does not match.";
}
So what you're doing in the above code is "if email and confirmation email are the same, stop the script execution else print out 'Your Email address does not match.' and continue execution".
if ($email == $repeatpassword) {
exit();
}
else {
echo "Your Passwords do not match.";
exit();
}
And here you are saying if "email and repeatpassword are the same (???), stop script execution else print out 'Your Passwords do not match.' and also stop script execution".
So because of this logic obviously you never reach the code to insert data to database.

Unable to Insert Feedback into Database

I wrote the following code in baby steps, working with each thoroughly until it's worked. The last step was checking that a username/email does not exist and if true, inserting everything into a database. I got the code to send an email if there are not errors up until [5], but I cannot test anything beyond sending an email. When form is completed and sent, the page is cleared after the heading and does not proceed to the next page.
I have gone over the code as thoroughly as I possibly could, pulling up multiple sources and checking over general syntax with php validation tools. I don't have anything that comes up.
Connection:
$con = mysqli_connect('$db_host', '$db_user', '$db_pass', '$db_name');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Body:
if (isset($_POST['process'])) {
$birthday = $_POST['year'].$dash.$_POST['month'].$dash.$_POST['day'];
$user_name = htmlspecialchars($_POST['user']);
$email = htmlspecialchars($_POST['email']);
$pass = htmlspecialchars($_POST['pass']);
$confirm = htmlspecialchars($_POST['confirm']);
if ($_POST['user'] == '') {
$errors[1] = 'Please enter your username.';
} else if (!preg_match('/^[a-zA-Z0-9]{4,25}$/', $_POST['user'])) {
$errors[1] = 'Usernames must contain 4 to 25 alphanumeric characters.';
} else {
$errors[1] = '';
}
if ($_POST['email'] == '') {
$errors[2] = 'Please enter your email.';
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[2] = 'Email must be valid.';
} else {
$errors[2] = '';
}
if ($_POST['pass'] == '') {
$errors[3] = 'Please enter your password.';
} else if (!preg_match('$\S*(?=\S{6,})\S*$', $_POST['pass'])) {
$errors[3] = 'Passwords must be at least six characters long.';
} else {
$errors[3] = '';
}
if ($_POST['confirm'] == '') {
$errors[4] = 'Please confirm your password.';
} else if ($_POST['confirm'] != $_POST['pass']) {
$errors[4] = 'Passwords do not match.';
} else {
$errors[4] = '';
$hash = password_hash ('$pass', PASSWORD_DEFAULT);
}
if (time() < strtotime('+13 years', strtotime($birthday))) {
$errors[5] = 'You are not at least thirteen years old.';
} else {
$errors[5] = '';
}
$to = $email;
$subject = 'Rabbit Showing and Breeding Association Registration Confirmation';
$header = 'From: RSBA Registration <registration#rsba.net>';
$message = 'Hello ' . $user_name . '!
You are receiving this email because you recently registered at Rabbit Showing and Breeding Association at http://rsba.net
Your confirmation code is: ' . $confirm_code . '
Please copy and paste the code into the account confirmation page or follow the following link to get started:
http://rsba.net/registration/confirmation.php?confirm_code=' . $confirm_code . '
Please disregard this email if you did not sign up for RSBA.
Thank-you,
Rabbit Showing and Breeding Association
This is an automated message. Do not reply.';
if ($errors[1] == '' && $errors[2] == '' && $errors[3] == '' && $errors[4] == '' && $errors[5] == '') {
$sentmail = mail($to,$subject,$message,$header);
}
if($sentmail){
include_once "../connect_info.php";
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '" . $user_name . "'");
$row = mysqli_fetch_array($result);
if ($row['user_name']) {
$errors[6] = 'This username already exists.';
}
$result = mysqli_query($con,"SELECT * FROM users WHERE email = '" . $email . "'");
$row = mysqli_fetch_array($result);
if ($row['email']) {
$errors[7] = 'A user is already registered with this email.';
}
if ($errors[6] == '' && $errors[7] == '') {
$result = "INSERT INTO users (user_name, email, hash, birthday, confirm_code, access_level)
VALUES ('$user_name', '$email', '$hash', '$birthday', '$confirm_code', '0')";
if (mysqli_query($con, $result)) {
header('Location:sent');
} else {
$error[8] = '<span class="error">You cannot be registered.</span>';
}
}
}
mysqli_close($con);
}

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.

Registration and Log in form

I have created registration form which sends a link via e-mail and you have to click it in order to be successfully registered, which makes you have to log in. The problem is that I can't log in, while everything else is working fine. Below you will find my register.php, activation.php and login.php. Any help would be great.
action = register.php
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
action = activation
if ($_GET['action'] == 'invitation') {
if (!empty($_GET['key'])){
//thelw na eleksw an afto to key uparxei sto tabale members
$sql = "SELECT * FROM members WHERE activationCode = '".$_GET['key']."'";
$result=mysql_query($sql,$lnk);
$user= mysql_fetch_assoc($result);
if(!empty($user)){
//edw tha energopoiisw ton xristi
$sql = "UPDATE members SET flag=1 WHERE username = '".$user['username']."'";
mysql_query($sql,$lnk);
}else{
echo "this is WRONG";
}
}else{
echo 'No key';
}
}
action = login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
you are doing wrong with password.
use below code
if ($_GET['action'] == 'register') {
if(isset($_POST['formsubmitted'])){
$error = array();
if(empty($_POST['username'])){
$error[] = 'Please enter a username';
}else{
$username = $_POST['username'];
}
if(empty($_POST['email'])){
$error[] = 'Please enter a mail';
}else{
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/",$_POST['email'])) {
$email = $_POST['email'];
}else{
$error[] = 'Your mail is invalid';
}
}
if (empty($_POST['password'])){
$error[] = 'Please enter a password';
}else{
$password = md5($_POST['password']);
}
if (empty($error)){
$verify_email = "SELECT * FROM members WHERE email = '$email'";
$result_verify_email = mysql_query($verify_email,$lnk);
if (!$result_verify_email){
echo 'Database error';
}
if (mysql_fetch_assoc($result_verify_email) == 0){
$activationCode = md5(uniqid(rand(),true));
$insert_users = "INSERT INTO members VALUES ('','".$username."','".$email."','".$password."','".$activationCode."',0)";
$result_insert_users = mysql_query($insert_users,$lnk);
if(!$result_insert_users){
echo 'Database error';
}
if(mysql_affected_rows($lnk) == 1){
$message = 'To activate your account, please click on this link:\n\n";';
$message .= WEBSITE_URL . '/index.php? page=activation&action=activation&key='.$activationCode;
mail(
$email,
'Registration Confirmation',
$message,
'FROM:' . EMAIL
);
echo 'A confirmation email has been sent to ' . $Email . ' Please click on the Activation Link';
}else {
echo 'You could not be registered';
}
}else {
echo 'That email address has already been registered.</div>';
}
and for login
if ($_GET['action'] == 'login') {
$error = array();
if (empty($_POST['username'])) {
$error[] = 'You forgot to enter your username ';
} else{
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = md5($_POST['password']);
}
$check_credentials = "SELECT * FROM members WHERE username = '".$username."' AND password = '".$password."' AND flag = '1' ";
$result_check_credentials = mysql_query($check_credentials,$lnk);
$user_check_credentials = mysql_fetch_assoc($result_check_credentials);
if(!empty($user_check_credentials)){
$_SESSION['Auth'] = $user_check_credentials['username'];
header('location:index.php?page=home');
}else{
$message = '<img src="css/photos/zzzdoop.png"> ';
$_SESSION['Auth'] = false;
}
} elseif ($_GET['action'] == 'logout') {
$_SESSION['Auth'] = false;
}
I'm guessing the error is here:
action = login
if (empty($_POST['password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true)); // HERE
}
You've just changed your password into something completely random, then you are trying to look for it in the database...
The key to programming is understanding what you are doing and knowing methods to determine what is wrong. It is ALL about problem solving. As you can see in your code: (action = login)
else {
$password = $_POST['password'];
$password = md5(uniqid(rand(),true));
}
You generate a random password each time rather than hashing the password that was provided. You then go on to check if it exists with the user. You need to make it like your registration method:
$password = md5($_POST['password']);
Another problem you have is in your query to check for valid user. Your flag field is an int but you're treating it like a string.
AND flag = '1' ";
needs to be
AND flag = 1 ";
NOTICE: DO NOT USE MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO. You are also wide open for SQL injections, be careful.

Categories