PHP and MYSQL authentication - php

my login function does not work, always says username or password does not work. i need echo ok if username and password are correct so i can continue with my project. my db password is set to md5. here are y codes:
user.php file
<?php
<?php
function sanitize($username)//sanitizes user inputs
{ $connect = mysqli_connect('localhost','root','','lr');
return mysqli_real_escape_string
($connect,$username); }
?>
//checks if user exist
function user_exists($username)
{ $username = sanitize($username);
$conn = #mysqli_connect('localhost', 'root', '', 'lr') OR die("cant connect");
$query = mysqli_query($conn, "SELECT user_id FROM users WHERE username = '$username'");
return(mysqli_num_rows($query) ==1) ? true : false;
}
//checks if user active, if set in database to 1, its active, if set to 0, not active
function user_active($username)
{ $username = sanitize($username);
$conn = #mysqli_connect('localhost', 'root', '', 'lr') OR die("cant connect");
$query = mysqli_query($conn, "SELECT user_id FROM users WHERE username = '$username' AND active =1");
return(mysqli_num_rows($query) ==1) ? true : false;
}
//Gets user id from username
function user_id_from_username ($username) {
$username = sanitize ($username);
return mysql_result(mysqli_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
function login($username, $password){
$user_id = user_id_from_username($username);
$username = sanitize($username);
$password = MD5($password);
return (mysql_result(mysqli_query("SELECT COUNT(`user_id`) FROM `users` WHERE `username`='$username' AND `password`='$password'"), 0)==1) ? $user_id : false;
}
?>
login.php file
<?php
function sanitize($username)
{ $connect = mysqli_connect('localhost','root','','lr');
return mysqli_real_escape_string
($connect,$username); }
?>

Related

cannot log in with correct password and username. keep false

when I log in, even the password and username are correct, it keep error.
Array ( [0] => That user/password combination is incorrect )
the username and password is active and existed.
login.php
<?php
include 'init.php';
if(empty($_POST) === false){
$username = $_POST['username'];
$password = $_POST['pwd1'];
if(empty($username)|| empty($password)) {
echo 'You need to enter username and password';
}
else if(user_exists($username) === true){
if(user_active($username) === true){
$login = login($username, $password);
if($login === false){
$errors[] = 'That user/password combination is incorrect' ;
} else{
$_SESSION['user_id'] = $login;
ob_end_clean();
header('Location:forum.php');
exit();
}
}
else{$errors[] = 'You haven\'t activated your account!';}
}
else{$errors[] = 'We can\'t find that username. Have you registered?';}
print_r($errors);
}
?>
users.php
<?php
function logged_in(){
return (isset($_SESSION['user_id'])) ? true :false;
}
function user_exists($username){
$username = sanitize($username);
$sql = "SELECT COUNT(user_id) FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
return (mysql_result($result,0) ==1) ? true : false;
}
function user_active($username){
$username = sanitize($username);
$sql ="SELECT COUNT(user_id) FROM `user` WHERE username = '$username' AND `active` = 1";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return (mysql_result($result,0) ==1) ? true : false;
}
function user_id_from_username($username){
$username = sanitize($username);
$sql = "SELECT user_id FROM `user` WHERE username = '$username'";
$result = mysql_query( $sql);
if ($result === false){
return false;
}
return mysql_result($result,0, 'user_id');
}
function login($username, $password){
$username = sanitize($username);
$password = md5($password);
$query = mysql_query("SELECT COUNT(user_id)
FROM `user`
WHERE username ='$username' AND pwd1 ='$password'");
$row = mysql_fetch_row($query);
if($row[0]>0){
return user_id;
}else{
return false;
}
}
?>
general.php
<?php
function sanitize($data){
return mysql_real_escape_string($data);}
?>
init.php
<?php
ob_start();
session_start();
require 'connect.php';
require 'general.php';
require 'users.php';
$errors = array();
?>
You don't assign $login to $_SESSION['user_id'], because you call die($login); before that, which is same as exit, nothing is parsed after that. Change the order.
And pray that your sanitize function works. Anyway, you had better switch to PDO, because mysql_ functions are deprecated and not safe. Even if you sanitize your $_POST and $_GET, you can still have malicious values selected from your database or from XML you parse or from other source.

PHP not returning database item

I am trying to fill a varialble $login with the users user_id so I can use sessions, however the query does not return the user_id to fill the $login with.
users.php
<?php
function user_exists($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return(mysqli_affected_rows($con) == 1) ? true : false;
}
function user_active($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `active` = 1");
return(mysqli_affected_rows($con) == 1) ? true : false;
}
function user_id_from_username ($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return mysqli_affected_rows($con) ? 0 : 'user_id';
}
function login($username, $password, $con) {
$user_id = user_id_from_username($username, $con);
$data = $username;
$username = sanitize($data, $con);
$username = $data;
$password = md5($password);
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
return (mysqli_affected_rows($con) == 1) ? $user_id : false;
}
?>
login.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 and password';
} else if (user_exists($username, $con) === false) {
$errors[] = 'We can\'t find that username. Have you registered?';
} else if (user_active($username, $con) === false) {
$errors[] = 'You have not activated your account. Please see the instructions.';
} else {
$login = login($username, $password, $con);
if ($login === false) {
$errors [] = 'That username and password combination is incorrect;';
} else {
echo 'hi';
die($login);
$_SESSION['user_id'] = $login;
}
}
print_r($errors);
}
?>
Init.php
<?php
session_start();
//error_reporting(0);
require 'database/connect.php';
require 'functions/users.php';
require 'functions/general.php';
$errors = array();
?>
When you get your userid you are returning the wrong value:
function user_id_from_username ($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return mysqli_affected_rows($con) ? 0 : 'user_id';
}
This function will return a 0 (if affected_rows is not 0) or the string 'user_id' (if affected rows is 0). First off I think the logic is probably reversed (0 vs non-zero) and secondly I think you really want to return an actual user_id instead of just the string 'user_id'.
Then in your login function:
function login($username, $password, $con) {
$user_id = user_id_from_username($username, $con);
$data = $username;
$username = sanitize($data, $con);
$username = $data;
$password = md5($password);
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `password` = '$password'");
return (mysqli_affected_rows($con) == 1) ? $user_id : false;
}
You get this 0 or 'user_id' (string) into $user_id and then ignore it until the very end when you return either that value or a false. Since the logic was reversed on the return value of the previous function, then on a successful login your $user_id contains the 0 (which is boolean false in PHP) and so this function is returning either a 0 or a false from login - both of them are false so login() is returning false. But specifically in the case of a good login you are returning a 0 which then isn't going to look like a valid ID to put into your session and, if you get it there, isn't going to compare well because of the whole situation of zero being evaluated to boolean false.

PHP Parse error: syntax error, unexpected ',' in

Well, basically I am working on a register and login tutorial on youtube. Which is using the old version of PHP, and I have attempted to update the code, however I get this error:
Parse error: syntax error, unexpected ',' in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\Forum\forum\core\functions\users.php on line 23
users.php
<?php
function user_exists($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return(mysqli_affected_rows($con) == 1) ? true : false;
}
function user_active($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `active` = 1");
return(mysqli_affected_rows($con) == 1) ? true : false;
}
function user_id_from_username ($username, $con) {
$data = $username;
$username = sanitize($data, $con);
$username = $data;
mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username'");
return mysqli_affected_rows($con), 0, 'user_id';
}
function login($username, $password, $con) {
$user_id = user_id_from_username($username, $con);
$data = $username;
$username = sanitize($data, $con);
$username = $data;
$password = md5($password);
return (mysqli_affected_rows(mysqli_query($con, "SELECT `user_id` FROM `users` WHERE `username` = '$username' AND `password` = '$password'"), 0) == 1) ? $user_id : false;
}
?>
Line 23 is this one: return mysqli_affected_rows($con), 0, 'user_id';
Must be: return mysqli_affected_rows($con) ? 0 : 'user_id'; if this what you meant.
Cannot return multiple values in PHP.

How store user ID as session in login.php

I have the following functions in a file called user.php:
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `MemberID` FROM `member` WHERE `Email` = '$username'"),0, 'MemberID');
}
function login ($username, $password) {
$MemberID = user_id_from_username ($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`MemberID`) FROM `member` WHERE `Email` = '$username' AND `Password` ='$password'"), 0) == 1) ? $MemberID : false; }
And in my login.php I have:
Session_start ();
include 'core/functions/users.php'
if (empty($_POST) === false){
$username = $_POST['Email'];
$password = $_POST['Password'];
$login = login($username, $password);
if($login === 1){
$_SESSION['MemberID'] = $login; //logged in and returned user ID and store in session
header('location: member.php?username='.$username);
}else{
// try admin login
$query2 = mysql_query("SELECT * FROM admin WHERE Email ='$username' AND Password ='$password'");
if(mysql_num_rows($query2) == 1){
$_SESSION['Email'] = $username;
header("location: admin.php");
}
else{
echo "Failed Login Attempt";
}
}
}
When I try to log a user in I get this error:
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 8 in oddjobexchange\core\functions\user.php on line 27
Failed Login Attempt
I can't get my head around this error because I can't see anything wrong with line 27 (below)
return mysql_result(mysql_query("SELECT `MemberID` FROM `member` WHERE `Email` = '$username'"),0, 'MemberID');
In my DB 'MemberID' is row 0, 'Email' is row 7 and 'Password' is row 8. Anybody know what I've got wrong?

Setting session variable from query result

I've been modifying a user authentication system and I'm having trouble setting a session for the admin. The reguser session is setting just fine, but I can't figure out why admin won't set.
A user with a userlevel of 9 is an admin. Yes, I know how to protect against SQL injection. I'm just trying to keep it as simple and easy to read for now. This probably won't get used for anything, I'm just getting some experience with PHP.
Hi everyone, thanks for your help! I got it to work. I had been staring at it for so long that my mind wasn't clear. Took a break from it yesterday, came back to it today and was able to figure it out in less than 5 minutes! You guys are awesome, I love stackoverflow!
function checklogin($email, $pass) {
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(udogoo, $connection) or die(mysql_error());
$pass = md5($pass);
$result = mysql_query("SELECT userid from users WHERE email = '$email' AND password = '$pass'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
$userid = $user_data['userid'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = '$userid'");
$isadmin2 = mysql_fetch_array($isadmin);
$isadmin3 = $isadmin2['userlevel'];
if ($isadmin3 == "9"){
$_SESSION['admin'] = true;
return true;
}
}
else
{
return FALSE;
}
}
You have a return true; if the user data exists. In fact, you only check or admin-ness if the user doesn't exist.
Remove that return true;, as it's not needed there. If you want, add else return false; after the check for the user's existence, and return true; right at the end.
Your logic is flawed as well, here:
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(test, $connection) or die(mysql_error());
$email = mysql_real_escape_string($email);
$pass = md5($pass);
$sql = "SELECT `userid`,`userlevel`
FROM `users`
WHERE `email` = '$email'
AND `password` = '$pass'
LIMIT 1"; //I certainly hope you check email for injection before passing it here. Also want the LIMIT 1 on there because you are only expecting a single return, and you should only get one since `email` should be unique since you're using it as a credential, and this will stop it from looking through all the rows for another match once it finds the one that matches.
$result = mysql_query($sql);
$user_data = mysql_fetch_array($result);
$numrows = mysql_num_rows($result);
if ($numrows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
if($user_data['userlevel'] == 9)
{
$_SESSION['admin'] = true;
}
else
{
$_SESSION['admin'] = false;
}
return true;
}
return false;
}
This should work. No good reason to do two queries when one will do just fine. Returns true if user is logged in, false if user doesn't exist or credentials don't match.
Oops, small syntax error in the SQL statement, corrected. Bigger syntax error also corrected.
And here's how you do the top part in PDO:
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$dbname = 'test';
$dsn = 'mysql:dbname=' . $dbname . ';host=' . $server;
$conn = new PDO($dsn,$user,$password); //Establish connection
$pass = md5($pass);
$sql = "SELECT `userid`,`userlevel`
FROM `users`
WHERE `email` = :email
AND `password` = :pass
LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email',$email,PDO::PARAM_STR,128) //First param gives the placeholder from the query, second is the variable to bind into that place holder, third gives data type, fourth is max length
$stmt->bindParam(':pass',$pass,PDO::PARAM_STR,32) //MD5s should always have a length of 32
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute(); //almost equivalent to mysql_query
$user_data = $stmt->fetch(); //Grab the data
if(is_array($user_data) && count($user_data) == 2) //Check that returned info is an array and that we have both `userid` and `userlevel`
{
//Continue onwards
$userid = $user_data['user_id'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = $userid");
$user_data = mysql_fetch_array($result);
$userlevel = $user_data['userlevel'];
if($userlevel == '9')
{
$_SESSION['admin'] = true;
}
so, your complete code look like this::
<?php
function checklogin($email, $pass)
{
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(test, $connection) or die(mysql_error());
$pass = md5($pass);
$result = mysql_query("SELECT userid from users WHERE email = '$email' AND password = '$pass'");
$user_data = mysql_fetch_array($result);
$numrows = mysql_num_rows($result);
if ($numrows == 1)
{
$_SESSION['reguser'] = true;
$_SESSION['userid'] = $user_data['userid'];
//MY ANSWER START HERE
$userid = $_SESSION['userid'];
$isadmin = mysql_query("SELECT userlevel FROM users WHERE userid = $userid");
$user_data = mysql_fetch_array($result);
$userlevel = $user_data['userlevel'];
if($userlevel == '9')
{
$_SESSION['admin'] = true;
}
//END HERE
}
else
{
return false;
}
}
?>

Categories