I have the following table
Login
IdUser (int)
Username(varchar)
Password(varchar)
Email(varchar)
Active(int)
Active is either 0 or 1 depending on if the users email is verified or not. If an account is verified the active row in the table is updated with a 1. If an account is not verified the active row in the table remains a 0.
Users should only be able to login if their account is verified.
So far my login works like this:
//login API
function login($user, $pass) {
// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
// a row was found in the database for username/pass combination
// save a simple flag in the user session, so the server remembers that the user is authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
// print out the JSON of the user data to the iPhone app; it looks like this:
// {IdUser:1, username: "Name"}
print json_encode($result);
} else {
// no matching username/password was found in the login table
errorJson('Authorization failed');
}
}
How would I give only users that are verified the ability to login?
Well, unless I'm missing something in your description, it seems that you simply have to add a AND active=1 to your WHERE clause. So you would end up with:
SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' AND active=1 limit 1
Updated
//login API
function login($user, $pass) {
// try to match a row in the "login" table for the given username and password
$result = query("SELECT IdUser, username, active, email FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
// a row was found in the database for username/pass combination
if (!$result['result'][0]['active']) {
// not activated yet
errorJson('Not activated yet: ' + $result['result'][0]['email']);
} else {
// save a simple flag in the user session, so the server remembers that the user is authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
// print out the JSON of the user data to the iPhone app; it looks like this:
// {IdUser:1, username: "Name"}
print json_encode($result);
}
} else {
// no matching username/password was found in the login table
errorJson('Authorization failed');
}
}
And by the way, as other mentionned, your code appears to be sensible to SQL injection, and you appear to store password in raw text in the database, which is a very bad practice. You should consider using mysqli + placeholders for your queries. You should also hash the passwords, at any point in the process. A simple way (though not the best) might be to use MySQL's password function. So your query would simply be changed to:
$result = query("SELECT IdUser, username, active, email FROM login WHERE username=? AND password=PASSWORD(?) limit 1", $user, $pass);
Simply add AND active = 1 before limit 1 in your query.
As an aside there are some broader issues with your code:
Avoid storing passwords directly in the database, use bcrypt instead, for example
Use mysqli or another database interface with prepared statements to avoid SQL injection
here:
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' AND emailVerified='1' limit 1", $user, $pass);
where there emailVerified is your email verified status field name, replace that to your own
first you have to check user is active or not
select active from login where username='%s';//execute this query and check result and store in active..
if(!$active)
{
errorJson("your account is not activated yet!);
}
else
{
//login code
}
Related
Here is my login process, I want a same dashboard but data will be different for each user. But I am stuck with creating uid variables to get data for each login user.
if(isset($_POST['login_btn']))
{
$email_login=$_POST['email'];
$password_login=$_POST['password'];
$admin="admin";
$co_admin="co_admin";
$query = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$admin' ";
$query_run = mysqli_query($connection, $query);
$query_co = "SELECT * FROM registered_users WHERE email='$email_login' AND password='$password_login' AND usertype='$co_admin' ";
$query_run_co = mysqli_query($connection, $query_co);
if(mysqli_fetch_array($query_run))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $admin;
header('Location: index.php');
}
else if(mysqli_fetch_array($query_run_co))
{
$_SESSION['username'] = $email_login;
$_SESSION['usertype'] = $co_admin;
header('Location: company_view.php');
}
else
{
$_SESSION['status'] = 'Email ID / Password / User Type is Invalid';
header('Location: login.php');
}
}
Above source code is for separating Co-admin and Admin. Now Any Co-Admin login to the portal he should get his own details, I would like to know which function I have to call or how should I declare a uid variable to fetch data tables for each current logged in user. I found some other source codes but which is not related to me so i am confused with how I fix it with those code. Can anyone do it in my codes.
I think you are asking how to get data for the current user from mysql tables. Yes, the standard way of doing this is via a unique ID for each user that is pulled from the registered_users table, storing this in the session, and then referencing this in the other tables and filtering by this ID. I would not suggest storing anything else from this table in the session as the ID is likely to have a stronger guarantee of imutibility.
For example if you have a table of recently visited pages per user, you would get this via:
$query = 'SELECT * from recently_visited WHERE user_id = ?';
$stmt = mysqli_prepare($query);
$stmt->bind_param("i", $_SESSION['user_id']);
$stmt->execute();
You can check the mysqli documentation for how to then extract what you need from the executed statement. I've shown this example of a prepared statement so you can see how to avoid SQL injection as well.
You may want to look into using foreign keys to enforce this connection.
So I have an SQL database that has a table for accounts and info, and another one for storing comments on articles. I Have a form for submitting comments and it works just fine, but I wanted to implement a feature to prevent spam and non registered accounts. I was trying to find a way to make the following code work so that it would call upon my account table and check to see if the username section matches what was entered in the form.
I want it to check through my username column on the table to see if what was entered in the box is actually in the database as well, that way if it hasn't been registered it won't submit.
My problem I keep running into is that I try this
<?
if ($_POST['Uname']==`username`){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
But when I do this it thinks that "username" is what the username needs to be in order to submit properly.
I do not want every username to need to be "username" in order for them to submit, I just want it to check through my username column to see if what was entered is one of the registered usernames in the SQL column.
Im not sure if this is possible, or if I am making any sense, but this is my first post on this site and I would appreciate any help I could get.
Full code is below
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("sql***.*******.com","*****","*******");
$db_selected = mysql_select_db("*********",$con); //My login
$test2=$_GET['ID']; //Ignore
$_POST['#']=$test2; //Ignore
$sql="Select * from `Articles` and `Accounts`"; //For pulling data
mysql_query($strSQL,$con);
if ( ? == ? ){ //What should go here?
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES
('".$_POST['Uname']."','".$_POST['Comment']."',
'".$_POST['Date']."','".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Edit
So after making the changes needed, should my previous code end up like this?
<?
if ($_POST['Enter']=='Enter'){
$con = mysql_connect
("*******","********","*****");
$db_selected = mysql_select_db("*****",$con);
$test2=$_GET['ID'];
$_POST['#']=$test2;
$username = $_POST['Uname'];
$sql = "Select `id` from `Accounts` where `username` = $username";
mysqli_num_rows($sql,$result);
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
echo $result;
if ($row_cnt!=''){
$strSQL="INSERT INTO `comments`
(`name`,`comment`,`date`,`#`) VALUES ('".$_POST['Uname']."',
'".$_POST['Comment']."',
'".$_POST['Date']."',
'".$_POST['#']."')";
}
else{
echo "Username invalid";
}
}
?>
Obviously what you doing is not correct, as of now you are putting condition as :
if ($_POST['Uname']==`username`)
which means you saying any user who's name is 'username' should be able to comment, but what you want to achieve is, any user who is valid user and is exist in db should be able to comment. So for that you should write a select sql to check the user, :
$username = $_POST['Uname'];
$sql = "select id from yourusertable where username = $username";
then,
perform
mysqli_num_rows
to check if you get anything greater than zero. If yes, then allow to submit comments.
Simply apply the check that only loggedIn user can comment. So if the user will not exist in users table it will not be loggedIn nor can comment.
I am trying to let users to create a book detail in a table called books. However there are two types of users which are admin and users. Admin are saved as type = 1 and users are saved as type = 0 in a user table in the database as boolean.
The user has to log into the system to update the book account. The detail of the user is saved as username in COOKIES.
Therefore I want to command computer that let only admin to upload book table relating to the COOKIES username and check the username is related to admin, if username is user don't let it create.
Users
id | name | type
1 | abc | 1
2 | xyz | 0
I am trying to do such as
$_COOKIE['username'];
$result = 'SELECT type FROM users WHERE type = 1';
$res = mysql_query($result);
if ($res){
//let admin to enter the details
} else {
//you are not an admin,
}
Your SQL query will always return 1. You want something along the lines of
$username = $_COOKIE['username'];
$res = mysql_query("SELECT type FROM users WHERE name='$username'");
Then check if the type is 1 or 0.
$row = $mysql_fetch_assoc($res);
if ($row['type'] == 1){
//You are an admin
} else {
//You are not an admin
}
It doesn't matter if you use cookies or sessions. You need to pass some sort of user information, whether it's the user's id or username, into your SQL query to check that specific user's credentials.
Now, suppose you have a php file called upload.php which handles the book upload. Now, in the file check if the session variable $_SESSION["type"] has a value of 1 i.e, the logged -in-user is an admin. Also, I would advise against using mysql_* syntax anymore since its deprecated. Take a look at mysqli. I have written my answer using mysqli.
//This code goes in upload.php file
$mysqli = mysqli_connect(HOST, USER, PASS, DBNAME);
$username = $_COOKIE["username"];
$stmt = $mysqli->prepare("SELECT type FROM users WHERE username=?");
if($stmt){
$stmt->bind_param("s", $username);
$stmt->execute;
$stmt->bind_result($type);
$stmt->fetch();
$stmt->close();
}
//Now check for type
if( $type == 1){
//Add upload code here
}
else{
//Not admin access denied
}
$mysqli->close();
I've created an arbitrary login system for users on the app I'm developing, and I am using mysqli to switch from MySQL. However, I'm having teething issues, as it will log you in successfully regardless of what data you enter. Obviously this is wrong, and I think it's got something to do with my fetch statements. Here is the code:
$sid = /* arbitrary value */
$con = new mysqli($mysql_host,$mysql_user,$mysql_password,$mysql_database);
$stmt = $con->prepare("SELECT uid, pwd FROM schools WHERE uid=?");
$stmt->bind_param("i", $sid);
$stmt->execute();
$stmt->bind_result($schoolid, $password);
$stmt->fetch();
$stmt->close();
Anybody know what's going on here and able to describe it in plain English to a relative coding newbie?
EDIT: the rest of the code is like this for the checking system. The entered user ID is $sid and the entered and encrypted password is $cleanpwd.
if ($sid == $schoolid and $cleanpwd == $password) {
header('Location: loginsuccess.php');
}
else {
header('Location: login.php?error=1'); }
It seems that if this is a login form are you getting the data first and then processing if it is correct? Or are you trying to process if it is correct (a userid and password combo in the SQL)? Because from this you are just putting in a userid and getting back a userid and password without checking if any entered password matches the database password associated with that userid.
If you want to see if the password and username match in the SQL you should try this:
$stmt = $con->prepare("SELECT uid, pwd FROM schools WHERE uid=? AND pass=?");
$stmt->bind_param("is", $sid,$form_password);
$stmt->execute();
otherwise you need to check if the data matches up later on.
if($_POST['form_pass'] == $password){
//log the user in
}
Having a noob day.
For some reason this works:
// check for user in db
$result = $connector->query('SELECT username FROM wallart_users
WHERE username ="test#testmail.com");
if (mysql_num_rows($result) == 0) {
////// ADD NEW USER
But this doesn't:
$payer_email = mysql_real_escape_string($payer_email);
// check for user in db
$result = $connector->query('SELECT username FROM wallart_users
WHERE username ='.$payer_email);
if (mysql_num_rows($result) == 0) {
////// NEW USER
The first one matches and sends me further down the page.
The second one doesn't match (with or without the escape) and tries to create a new user with the same credentials (then fails as the user already exists).
The email address PayPal is sending is always the same, and the database contains the right address.
I have written both addresses to a log file during the process and they look identical.
'SELECT username FROM wallart_users WHERE username ="'.$payer_email.'"';
This code
$result = $connector->query('SELECT username FROM wallart_users
WHERE username ='.$payer_email);
Should be
$result = $connector->query("SELECT username FROM wallart_users
WHERE username ='$payer_email' ");
Do you not think that you are doing some thing wrong with your second query? you should change your query like this
$result = $connector->query('SELECT username FROM wallart_users WHERE username ="'.$payer_email.'"');