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;
}
}
?>
Related
I made a simple Login Form there are some errors in the code I guess.
Everything is working fine but I'm struggling with the MySQL(mysqli) Query part.
But here is my code first:
<?php
session_start();
if(isset($_SESSION['acuser']))
{
redirectpage();
}
else
{
if($_POST)
{
if(isset($_POST['button']) && ($_POST['username']) && ($_POST['password']))
{
$db = 'datenbank';
$dbuser = 'root';
$dbpass = '';
$dbhost = 'localhost';
$connection = mysqli_connect($dbhost,$dbuser,$dbpass);
$selection = mysqli_select_db($connection,$db);
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
$password = mysqli_real_escape_string($connection, (htmlspecialchars($_POST['password'])));
$password = md5($password);
if($connection)
{
if($selection)
{
$queryuser = "SELECT * FROM main WHERE Username = '$username'";
$result = mysqli_query($connection, $queryuser);
$checkuser = mysqli_num_rows($result);
if($checkuser)
{
$querypass = "SELECT * FROM main WHERE Username = '$username' AND Password ='$password'";
$resultpass = mysqli_query($connection,$querypass);
$checkpass = mysqli_num_rows($resultpass);
if($checkpass)
{
$data = mysqli_fetch_array ($resultpass);
$_SESSION["acID"] = $data["Id"];
$_SESSION["acUSERNAME"] = $data["Username"];
$_SESSION["acPASSWORD"] = $data["Password"];
$_SESSION["acEMAIL"] = $data["Email"];
}
// Some else stuff
?>
I guess there is something wrong with "mysqli_query()" and "mysqli_num_rows()"!
"Mysqli_num_rows()" can't handle the output of "mysqli_query()" somehow!
Maybe i will find an answer here
Not sure if this is the problem:
$username = mysqli_real_escape_string($connection,(htmlspecialchars($_POST['password'])));
is the username the same as the password in the database?
So below I have my php code, everything works fine and dandy except when the user logs in and is redirected to the restricted page. When a person signs up, they fill out their first name, email, and password. In the login page it only requires email and password. When they are redirected I want to only display their first name though. I have tried making the session = $result which should return the result of the sql query, but if I do that it doesn't even redirect to the restricted page. What am I doing wrong?
<?php
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = ?;
header ("Location: loggedin/account.php");
}
else {
session_start();
$_SESSION['login'] = '';
}
}
else {
}
}
?>
Here is what I would do.....
// DATABASE VARIABLES
$user_name = "";
$pass_word = "";
$database = "";
$server = "";
// CONNECTS TO DATABASE
$db_handle = mysql_connect($server, $user_name, $pass_word);
$db_found = mysql_select_db($database, $db_handle);
// ACCOUNT INFORMATION
$email;
$password;
$num_rows = 0;
// IF SUBMIT IS CLICKED
if (isset($_POST['submit'])) {
// STORES INPUTS AS VARIABLES
$email = $_POST['email'];
$password = $_POST['password'];
// REMOVES HARMFUL CODE
$email = htmlspecialchars($email);
$password = htmlspecialchars($password);
if ($db_found) {
$SQL = "SELECT * FROM accounts WHERE email = '$email' AND password = '$password'";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
// Grab user name from db
$row = mysql_fetch_row($result);
if ($num_rows > 0) {
// Add to session variable
session_start();
$_SESSION['login'] = $row['username'];
header ("Location: loggedin/account.php");
}
else {
//Either exit or redirect to login failure page.
}
}
else {
This seems alright to me although I cant test at current.
Edit
You may want to have a read on using the Mysqli and PDO connection, it is slightly quicker and definitely more secure, just a suggestion if you have the time. Also prepared statements would definitely be more secure.
This is how I do Login... You must have an ID for each user in mysql and define
$_SESSION['user_id'] = $fetched_id;
and in loggedin/account.php page you can simply make this:
$user_id = $_SESSION['user_id'];
$query = mysql_query("SELECT `first_name` FROM `users` WHERE `id` = '{$user_id}'");
<?php
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
$rowcount = $query->rowCount();
if($rowcount == 1){
$row = mysql_fetch_array($query);
$dbPass = $row["password"];
if($password == $dbPass){
session_start();
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else
return false;
} else
return false;
}
?>
This is a PHP code snippet from a project I am globally converting to PDO. This is the functions.php file for the login page. Obviously it is not fully converted to PDO so don't criticize that, but basically in the login.php file I have it access this method, and pass the database(which is required in), the username, and the password from the form. I setup a basic query to find all users with the username input of the form. Then i prepare, and execute the query. I then need a row count, so I setup a $rowcount variable running the rowCount() method on the query, but the code does not move past there. The rowcount is == 0 when I echo it out so it won't proceed to the following if statement. Am I doing something wrong with the PDO or something? Or the rowCount(). My suspicion is that perhaps I am calling the rowCount() too late, so I tried moving it up before I execute the $query but no luck. Thank you!
___EDIT___
<?php
session_start();
function login($database, $username, $password) {
$query = "SELECT * FROM `users` WHERE username=':username'";
$query = $database->prepare($query);
$query->execute(array(':username' => $username));
if($query->rowCount()){
$row = $query->fetch();
echo $row;
$dbPass = $row["password"];
if($password == $dbPass){
$dbId = $row["id"];
$dbUser = $row["username"];
$dbEmail = $row["email"];
$dbFirstname = $row["firstname"];
$dbLastname = $row["lastname"];
//Register Session Variables
$_SESSION['id'] = $dbId;
$_SESSION['username'] = $dbUser;
$_SESSION['email'] = $dbEmail;
$_SESSION['name'] = $dbFirstname." ".$dbLastname;
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
Don't mix pdo and mysql_ functions together. NEVER!
Don't store password in plain text. NEVER! Instead try Password_compat !
First:
Is to replace
$row = mysql_fetch_array($query);
with
$query->fetchAll(PDO::FETCH_ASSOC)
Second:
session_start() should appear at the top of your script, not inside your function.
Third:
Is to replace
$rowcount = $query->rowCount();
if($rowcount == 1){
//
}
with this:
if($query->rowCount()){}
Fourth:
This is BAD!!
return true;
} else
return false;
} else
return false;
}
Always, use a complete delimiter. You are instilling a bad-codding practice, that will haunt you for life.
Simple do
if($foo){
if(){
//do something
}else if{
//do something
}else{
//do something
}
}
Fifth:
~Not good, but definitely better that your approach.
function small_query(pdo $pdo, $query, array $value){
$stmt = $pdo->prepare($query);
$stmt->execute($value);
return $stmt->fetchAll();
}
$pdo = new PDO('mysql:host=localhost; dbname=foo', 'root', 'pass');
$result = small_query($pdo, "SELECT * FROM users WHERE name = ?", array($_POST['name']))
EDIT.
Since you seem to love your code so much, I have done it your way. Try this:
<?php
session_start();
function login($database, $username, $password){
$query = "SELECT * FROM users WHERE username = ?";
$stmt = $database->prepare($query);
$stmt->execute(array($username));
if($stmt->rowCount()){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION["id"] = $result["id"];
$_SESSION["username"] = $result["username"];
$_SESSION["email"] = $result["email"];
return true;
}else{
return false;
}
}
I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).
I've written a functional login script using MySQL. However, I've now been told that it needs to be done using PDO, and I've a functional PDO connection:
function getConnection()
{
$userName = '*****';
$password = '*****';
$dbname = '******';
$db = new PDO("mysql:host=localhost;dbname=$dbname", $userName, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
However I've no idea how to convert the login query to PDO.
if (isset($_REQUEST['attempt']))
{
$user = $_POST['user'];
$password = $_POST['password'];
$qry = mysql_query
("SELECT *
FROM subscriber
WHERE email = '$user'
AND password = '$password'")
or die(mysql_error());
$total = mysql_num_rows($qry);
if ($total > 0)
{
session_start();
$_SESSION['user'] = 'yes';
header('location: account.php');
exit;
}
else
{
// Do nothing.
}
}
How can I do it?
To get you started:
$db = getConnection();
$stmt = $db->prepare("
SELECT * FROM subscriber WHERE email = :email AND password = :password
");
$stmt->bindParam(":email" , $user );
$stmt->bindParam(":password", $password);
$stmt->execute();
$total = $stmt->rowCount();
Non-bloated version:
$stm = $pdo->prepare("SELECT * FROM subscriber WHERE email = ? AND password = ?");
$stm-> execute($_POST['user'], $_POST['password']);
if ($id = $stm->fetchColumn()) {
session_start();
$_SESSION['user'] = $id;
header('location: account.php');
exit;
}
You can also use this example if you would not like to use bindParam. But I extracted it from #eggyal's answer. Great thanks go to eggyal.
<?php session_start();
include_once('pdo.inc.php');
$username = (isset($_POST['username']))? trim($_POST['username']): '';
$password = (isset($_POST['password']))? $_POST['password'] : '';
$pas = md5($password);
$redirect = (isset($_REQUEST['redirect']))? $_REQUEST['redirect'] :
'view.php';
$query = ("SELECT username FROM site_user WHERE username=:username
AND password =:password");
$query_login = $con->prepare($query);
$query_login->execute(array(
':username'=>$username,
':password'=>$pas));
$result = $query_login->rowCount();
if($result>0)
{
$_SESSION['username'] = $username;
$_SESSION['logged'] = 1;
echo "success";
}
else {
// Set these explicitly just to make sure
echo 'User name invalid';
}
?>