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();
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.
in my database i have the table called users, where i have 5 fields (id, username, email, password, user_level) - for the user_level field i have 2 options administrator and editor.
What i want to do is that when the user who is logged in have administrator in the user_level field to see all the pages from backend, and the user who have in the user_level field editor to see only some of the pages from the backend such as newsletter, or messages.
I hope you understand what i'm asking if not fell free to ask me if you need more specific details.
I tried to make a php page called access.php wher i put the following code, but not working
<?php
session_start();
$sql = $mysqli->query("SELECT user_level FROM imobiliare_users WHERE id=$id");
$user_level = $mysqli->query($sql);
echo $user_level;
if ($user_level !="administrator") {
echo "You are not the proper user type to view this page";
die();
}
?>
I need a little help. Thx in advance for helping me. :)
IN your sql, add a new column called useraccess. Then you could do,
$sql = "select user_access from imobiliare_users where email = '$email'";
$sql = mysql_fetch_array(mysql_query($sql));
if ($sql['user_access'] != 'user_level2') {
// show error about not having authorisation
}
else
{
// login/process script
}
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
}
I have a problem, I can not prevent a logged in user to delete post by others users?
In my code now, I can delete all users posts, but I want to be able to only delete my posts (the logged
in user posts).
Can somebody help me in the right direction on how to do that?
<div class="deletebtn">Delete post</div>
$id=$_GET['id'];
$sql="DELETE FROM shouts WHERE id='$id'";
$result=mysql_query($sql);
if($result)
{
echo('<div class="deletedpost">You have deleted a post. Tillbaka till Bloggen</div>');
}
else
{
echo "Something went wrong";
}
mysql_close();
Im using a href in one file, linking to another file where a use Sql code.
you can do this via session
check if user is logged in or not. if logged in then delete the post
if(isset($_SESSION['user']))
{
//delete post
}
Store userId in your table and update your delete query like this...
$sql="DELETE FROM shouts WHERE id='$id' and userId = '$_SESSION[user]'";
Check whether the logged in user is the owner for the particular post before deleting.
Write a select query with post id and owner id. If it returns true allow him to delete the post otherwise do not allow.
Don't you have a $_SESSION['id'] of sorts?
And you do have that user id associated in shouts table, so you know who's shout is it right?
DELETE FROM shouts WHERE id='$id' AND user_id='$_SESSION['id']'
You should treatthe inputs though.
use this kind of query, here it will delete only logged in user's post.
$sql="DELETE FROM shouts WHERE id='$id' and user_id = '$loggedin_session_id'";
I would suggest that upon the user signing up, you assign them a unique id (or let the database do it with auto increment) and save it in the database. Then, whenever they log in, you can pull that user_id from the database and store it in a session variable. When shouts are created, you store the user_id of the person who created the shout alongside the shout itself in the shouts table of the database. When a user attempts to delete a shout, you first check to make sure that that shout belongs to them before allowing them to delete it.
An example:
<?php
//when user logs in
$email = 'example#example.com';
$password = 'default';
$sql = "SELECT id FROM user_table WHERE email = '$email' AND password = '$password'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$_SESSION['user_id'] = $row['id'] //'id' is the user's id; assign it to the session variable
//user creates the shout
$user_id = $_SESSION['user_id']; //get the user_id from the logged-in user
$shout = $_POST['shout'];
$sql = "INSERT INTO shout_table (user_id, shout) VALUES ('$user_id','$shout')"; //store user id alongside the shout for future queries
mysql_query($sql);
//user about to delete the shout
$id = $_GET['id'];
$user_id = $_SESSION['user_id'];
//the sql to check in the shout_table to see if the shout they are deleting belongs to them
$sql = "SELECT * FROM shout_table WHERE user_id = '$user_id' AND id = '$id'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if ($row)
{
//everything is alright; this user can delete the shout, so prepare the DELETE query to do so
}
else
{
//the user is not allowed to delete the shout because it's not theirs; tell them so with an echo or whatever you're using for error handling
}
?>
The example above is rife with SQL injections. Validate and sanitize, of course. As well, mysql_query functions will be deprecated as of PHP 5.5, so get in the hang of using mysqli_query functions instead. Better yet, see if you can use PDO. :)
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
}