I made a php registration & log-in script. Registration part is OK with Arabic and English characters.
However, Log-in with Arabic characters in not working while with English characters, it works.
Any hint for me to proceed please?
This is my code. I hope it is clear.
function login($username, $password){
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0 ) == 1) ? $user_id :false;}
function user_id_from_username($username){
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');}
<?php
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = ' ◄ يجب آلا تكون الحقول فارغة!';
} else if (user_exists($username) === false) {
$errors[] = '◄ إسم المستخدم الذي أدخلته غير مسجل لدينا !!';
} else if (user_active($username)=== false){
$errors[] = '';
} else {
if(strlen($password) > 32){
$errors[] = '◄ كلمة المرور غير صالحة ! ';
}
$login = login($username, $password);
if ($login === false) {
$errors[] = '◄ يوجد خطاء في البيانات التي أدخلتها.. تأكد من اللغة أو حالة الأحرف !!';
}else{
//set the user session للمستخدم الحالي فقط
$_SESSION['user_id'] = $login;
// redirect user
header ('location: challengersland-cboard.php');
exit();
}
}
} else {
$errors[] = 'عذرا، لم يتم إستلام أية بيانات.';
}
if(empty($errors) === false) {
?>
<h3>▼ عذراً،حدثت الأخطاء التالية أثناء محاولتك تسجيل الدخول ▼</h3>
<?php
echo output_errors($errors);
}
?>
Related
I am uploading my website in a web server and my login is not working.On localhost everything was fine.Now when i put the correct username and password it gives me That username/password combination is incorrect.When i put the incorrect password it give this again.The other validations work fine and my code :
log in.php
<?php
include 'core/init.php';
if(empty($_POST) === false) {
$username= $_POST['username'];
$password = $_POST['password'];
if(empty($username)=== true || empty($password) === true ) {
$errors[] = 'You need to enter a username & password';
}else if (user_exists($username) === false) {
$errors[]='We cant find that username.Have you registered?';
}else if (user_active($username) === false) {
$errors[]='You havent activated your account!';
}else {
if(strlen($password) > 32) {
$errors[] = 'Password too long';
}
$login = login($username, $password);
if($login === false) {
$errors[] = 'That username/password combination is incorrect';
}else{
$_SESSION['user_id'] = $login;
header('Location: index2.php');
exit();
}
}
}else {
$errors[] = 'No data received';
}
include 'overall/headerr.php';
if (empty($errors)=== false) {
?>
<h2>We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
users.php
function login($username, $password){
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username`='$username' AND `password`='$password'"), 0)==1) ? $user_id : false;
}
function logged_in() {
return (isset($_SESSION['user_id'])) ? true : false;
}
function user_exists($username) {
$username = sanitize($username);
return (mysql_result( mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` ='$username' "), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return(mysql_result(mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username` = '$username' AND `active` =1"), 0) == 1) ? true : false;
}
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
general.php
<?php
function sanitize($data) {
return mysql_real_escape_string($data);
}
function output_errors($errors) {
$output = array();
foreach($errors as $error) {
$output[] = '<li>'. $error .'</li>';
}
return '<ul>' . implode ('', $output) . '</ul>';
}
?>
init.php
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array() ;
?>
Why are you making your code long & complicated?
I use this simple and nice code:
<?php
session_start(); /* Start a session on browser */
require('connect.php'); /* Get database-connection script */
$username = $_POST['username']; /* Define variable ' $username ' */
$password = $_POST['password']; /* Define variable ' $password ' */
/* Check if username or password is empty */
if(empty($username) || empty($password)) {
/* If one of the fields are empty, send user back. */
echo 'afar'; // All fields are required
} else {
/* Select usernames & passwords from our database */
$check_accpass = $dbh->query('SELECT username,password FROM `users` WHERE `username`='.$dbh->quote($username).' AND `password`='.$dbh->quote($password).'')->fetchAll();
/* Check if username & password has any matches in our database */
if($check_accpass) {
echo 'success';
/* IF they do, set $username to $_SESSION['USERNAME'] and same with password */
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
// Set cookies
// name, value, expire, path, domain, secure, httponly
setcookie("username", $username, time() + (172800 * 30), "/", NULL, TRUE, TRUE); /* 2 days = 48 hours */
setcookie("password", $password, time() + (172800 * 30), "/", NULL, TRUE, TRUE); /* 2 days = 48 hours */
// Send user to root
header('location:/');
} else {
/* if no matches are found, print the text below */
echo 'wuop'; // wrong username or password
}
}
?>
I'm using php 7 and postgres and I'm failing to get this password hash thing down.
Here's my user Registration. It's outputting passwords to the db similar to "$2y$10$1GWNRZokmwGR1/dxnMRiOuw4/dNh2IzH9O2QvIu5wjlLAX2OZRW5G" which seems to work:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$required_fields = array('username', 'password', 'confirm_password', 'first_name', 'last_name', 'email_address', 'phone',
'department', 'group_role');
foreach ($_POST as $key => $value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with asterisk are required';
break 1;
}
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === true) {
$errors[] = 'Sorry, the username \'' . $_POST['username'] . '\' is already taken';
}
if (preg_match("/\\s/", $_POST['username']) == true) {
$errors[] = 'Your useranme must not contain any spaces';
}
if (strlen($_POST['password']) < 14) {
$errors[] = 'Your password must be at least 14 characters';
}
if ($_POST['password'] !== $_POST['confirm_password']) {
$errors[] = 'You passwords do not match';
}
if (filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'A valid email address is required';
}
if (email_exists($_POST['email_address']) === true) {
$errors[] = 'Sorry, this email \'' . $_POST['email_address'] . '\' is already registered';
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
include 'include/iHead.php';
include 'include/widgets/login.php';
include 'include/widgets/login_report.php';
if (empty($errors) === false) {
?>
<h3>Registration Successful! You will receive an email once your registration is approved. </h3>
<?php
include 'include/widgets/login_rpt.php';
}
} else {
if (empty($_POST) === false && empty($errors) === true) {
$user_req = $_POST['username'];
$password = $_POST['password'];
$hashedPassword = password_hash($password, PASSWORD_DEFAULT)."\n";
$register_data = array(
'username' => $_POST['username'],
'password' => $hashedPassword,
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email_address' => $_POST['email_address'],
'phone' => $_POST['phone'],
'department' => $_POST['department'],
'region' => $_POST['region'],
'group_role' => $_POST['group_role'],
'active' => 0
);
register_user($register_data);
header('Location: register.php?success');
exit();
} else if (empty($errors) === false) {
include 'include/iHead.php';
include 'include/widgets/login.php';
include 'include/widgets/login_report.php';
if (empty($errors) === false) {
?>
<h3>Registration unsuccessful: </h3>
<?php
echo output_errors($errors);
include 'include/widgets/login_rpt.php';
}
}
}
function email_exists($email) {
$email = sanitize($email);
// echo "SELECT COUNT (userid) FROM user_profiles WHERE email_address = '$email'";
return (pg_fetch_result(pg_query("SELECT COUNT (userid) FROM user_profiles WHERE email_address = '$email'"), 0) == 1) ? true : false;
}
?>
And here is my login script:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Please enter a username and password';
} else if (user_exists($username) === false) {
$errors[] = 'Username not found. Please register.';
} else if (user_active($username) === false) {
$errors[] = 'Account not active';
} else {
if (strlen($password) > 32) {
$errors[] = 'Password too long';
}
$hash = login($username, $password);
if (password_verify($password, "$hash")) {
$_SESSION['userid'] = $login;
header('Location: main.php');
exit;
} else {
$errors[] = " Username & Password are incorrect";
}
}
} else {
header('Location: index.php');
}
include 'include/iHead.php';
include 'include/widgets/login.php';
include 'include/widgets/login_report.php';
if (empty($errors) === false) {
?>
<h3>login unsuccessful: </h3>
<?php
echo output_errors($errors);
include 'include/widgets/login_rpt.php';
include 'include/eFoot.php';
}
function login($username, $password) {
$user_id = get_id($username);
$username = sanitize($username);
// $hash = password_hash($password, PASSWORD_DEFAULT);
$row = pg_fetch_assoc(pg_query("SELECT password FROM user_profiles WHERE username = '$username'"));
$hash = $row['password'];
return $hash;
}
?>
I'm new to php, so any help would be outstanding!!!
Okay, thank you for your answers, but none of you were correct. I had to use pg_escape_string prior to the hash and verify functions. Simple, simple, simple....
hi i created this code below in my wordpress theme within my login.php page i created conditional statements successfully without any problem but in my last if statement when the username and password is correct i can't when this statement is correct i log in?
i want when the username and password is correct directly show legge in username and add the log out link to log out from the theme.
<?php
$error = '';
$success = '';
global $user_identity;
if(isset($_POST['task']) && $_POST['task'] == 'login') {
$username = esc_attr($_POST['login_username']);
$password = esc_attr($_POST['login_password']);
$remember = esc_attr($_POST['login_remember']);
$user = get_user_by('login', $username);
$user_id = $user->ID;
$user_data = get_userdata($user_id);
$user_login = $user_data->user_login;
$user_pass = $user_data->user_pass;
if($username == '' && $password == '') {
$error = 'Please Fill Required Fields!';
}
if($username == '') {
$error = 'Please Enter Your Username';
}
if($password == '') {
$error = 'Please Enter Your Password';
}
if($user_login != $username) {
$error = 'The Username is Incorrect';
}
if($user_pass != $password) {
$error = 'The Password is Incorrect';
}
if($user_login == $username && $user_pass == $password) {
}
}
?>
hey just create array of user data and passed into wp_signon($data,false) see below.
$login_data = array();
$login_data['user_login'] = $username;
$login_data['user_password'] = $password;
$login_data['remember'] = $remember; // set true or false for remember
$user_verify = wp_signon( $login_data, false );
if ( is_wp_error($user_verify) )
{
echo $user->get_error_message();
exit;
} else {
header("Location: " . home_url() . "/login/error/");
}
read document for more detail wp_signon()
I'm trying to check a table called members to see if a user exists with it's email and password. I'm able to connect to the database, but for some reason, it jumps all these if statements and echoes 'You have been logged in!' even when I put the wrong email or password? Here is the html and php:
<form action="/login-user" method="POST">
Email: <input type="text" name="login_email"><br>
Password: <input type="password" name="login_password"><br>
<button type="submit">Login</button>
</form>
PHP:
<?php
session_start();
/*error_reporting(0);*/
require 'users/functions/user-functions.php';
require 'users/connect-database.php';
if (empty($_POST) === false) {
$email = mysqli_real_escape_string($connection, $_POST['login_email']);
$password = stripslashes(mysqli_real_escape_string($connection, $_POST['login_password']));
$encrypted_password = md5($password);
if (empty($email)) {
echo 'You need to enter an email<br>';
} else if (empty($password)) {
echo 'You need to enter a password<br>';
} else if(user_exists($connection, $email, $encrypted_password) === false) {
echo 'You don\'t seem to be registered?';
} else if (user_active($connection, $email, $encrypted_password) === false) {
echo 'You haven\'t activated your account!';
} else {
$login = login($connection, $email, $encrypted_password);
if ($login === false) {
echo 'That email/password combination is incorrect';
} else {
$_SESSION['user_id'] = $login;
$_SESSION['logged_in'] = true;
echo 'You have been logged in!';
}
}
/*print_r($errors);*/
} else {
echo 'inputs were empty<br>';
}
require 'users/disconnect-database.php';
?>
Content of the file 'user-functions.php':
<?php
function sanitize($connection, $data) {
return mysqli_real_escape_string($connection, $data);
}
function logged_in() {
return $_SESSION['logged_in'];
}
function user_exists($connection, $email, $password) {
$query = mysqli_num_rows(mysqli_query($connection, "SELECT * FROM members WHERE email = '$email' AND password = '$password'"));
return ($query > 0) ? true : false;
}
function user_active($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password' AND `active` = 1");
return ($query !== false) ? true : false;
}
function return_user_id($connection, $email, $password) {
return mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
}
function login($connection, $email, $password) {
/*$user_id = mysql_result(mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'"), 0, 'user_id');*/
/*$password = md5($password);*/
$query = mysqli_query($connection, "SELECT user_id FROM members WHERE email = '$email' AND password = '$password'");
/*return (mysqli_query($connection, $query) or die (false));*/
if ($query === false) {
return false;
} else {
return $query;
}
/*return ($query !== false) ? true : false;*/
}
function log_out() {
unset($_SESSION['logged_in']);
session_unset();
session_destroy();
}
?>
If the answer is using mysql_result or mysqli_result, please explain in full detail because even after reading on the manual and W3Schools and everywhere else, I still don't understand how those functions work.
Thanks for any answers, and by the way, I have read all the other posts about this stuff but I didn't find any answers. Thanks.
First of all I would really advise to use a sha for encrypting passwords because md5 is decrypted in no time at all.
for your login function try the following:
<?php
function login($connection, $email, $password) {
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
?>
after the script has returned true you could set a session or do what you need to do with it.
EDIT You need session_start in every file so the best thing to do is include this.
I hope this works I typed it realy fast so there might be some errors in it but please let me know:
<?php
function generate($password) {
$password = hash('sha1', $password);
return $password;
}
function login($connection, $email, $password) {
$password = generate($password);
$query = mysqli_query($connection, "SELECT `email`, `password` FROM `members` WHERE `email` = '$email' AND `password` = '$password'");
$count = mysqli_num_rows($query); //counting the number of returns
//if the $count = 1 or more return true else return false
if($count >= 1) {
return true;
} else {
return false;
}
}
function exists($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$count = mysqli_num_rows($query);
if($count >= 1) {
return true;
} else {
return false;
}
}
function detail($connection, $detail, $table, $row, $value) {
$query = mysqli_query($connection, "SELECT `$detail` FROM `$table` WHERE `$row` = '$value'");
$associate = mysqli_fetch_assoc($query);
return $associate[$detail];
}
function errors($error) {
echo '<ul class="error">';
foreach($error as $fault) {
echo '<li>'.$fault.'<li>';
}
echo '</ul>';
}
function isLoggedIn() {
if(!empty($_SESSION['logged_in']) && exists($connection, 'id', 'members', 'id', $_SESSION['logged_in']) == true) {
return true;
} else {
return false;
}
}
function logout() {
unset($_SESSION['logged_in']);
}
if($_POST) {
$email = mysqli_real_escape_string($connect, strip_tags($_POST['email']));
$password = mysqli_real_escape_string($connect, strip_tags($_POST['password']));
if(!empty($email) && !empty($password)) {
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = 'Your email: '.$email.' is not valid';
}
if(exists($connection, 'email', 'members', 'email', $email) == false) {
$error[] = 'You are not registered';
}
if(detail($connection, 'active', 'members', 'email', $email) != 1) {
$error[] = 'Your account is not activated';
}
if(empty($error)) {
$query = login($connection, $email, $password);
if($query == true) {
$_SESSION['logged_in'] == detail($connection, 'id', 'members', 'email', $email);
}
}
} else {
$error[] = 'There are empty fields';
}
if(!empty($error)) {
echo errors($error);
}
}
?>
<form action="" method="POST">
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
I created a login form but when i try to login, it says email or password is incorrect but I'm going in the right email and password.
I create user in my database users table but again again i get this error. All error is ok when i try to emtpy email and password it says You need to entere a email and password.
and activated error also ok.I am entering the correct password and email address. Gives me the error.
This is users.php
<?php
function user_exists($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email'"), 0) == 1) ? true : false;
}
function user_active($email) {
$email = sanitize($email);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `users` WHERE `email` = '$email' AND `active` = 1"), 0) == 1) ? true : false;
}
function user_id_from_email($email) {
$email = sanitize($email);
return mysql_result(mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"), 0, 'id');
}
function login($email, $password) {
$id = user_id_from_email($email);
$email = sanitize($email);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT (`id`) FROM `users` WHERE `email` = '$email' AND `password` = '$password'"), 0 ) == 1) ? $id : false;
}
?>
And this is login.php
<?php
include("core/init.php");
if(empty($_POST) === false) {
$email = $_POST['email'];
$password = $_POST['password'];
if (empty($email) === true || empty($password) === true) {
$errors[] = 'You need to enter a email and password';
} else if (user_exists($email) === false) {
$errors[] = 'We can\'t find that email. Have you registered ?';
} else if (user_active($email) === false) {
$errors[] = 'You have\'t activated your account';
} else {
$login = login($email, $password);
if ($login === false) {
$errors[] = 'That email/passowrd cocmbination is incorrect';
}else {
$_SESSION['id'] = $login;
header('Location: main.php');
exit();
}
}
print_r ($errors);
}
?>
Sorry, but there's a whole load of stuff which is wrong - lots of it may be producing errors.
1) there is no 'sanitize' function in php and you haven't told us what it does.
2) your login.php does niclude users.php
3) generating an md5 hash of the password is far from secure (it should be a slated sha1 hash as a minimum)
4) you never check for errors being returned by the DBMS
5) ...actually - that's not true - you compare the return value from the functions in users.php to false - and you'll only get false if the query fails - not if it returns 0 rows
Consider....
function do_something_with_email($email, &$err) {
$email = mysql_real_escape_string($email);
if (!($res=mysql_query("SELECT `id` FROM `users` WHERE `email` = '$email'"))) {
$err=mysql_error();
return false;
}
if (!($data=mysql_fetch_array($res)) {
$err=mysql_error();
return false;
}
return $data[0];
}
switch (do_something_with_email($email, $err)) {
case false:
die ($err);
case 0:
print "No records matched";
break;
default:
print "OK";
break;
}