Firstly, please forgive me if i don't give enough info in my question, i'm new to the developer scene after just landing myself an amazing opportunity as a junior software developer role a few weeks ago.
I have a project i'm working on which is a basic CRUD management system.
I have a login process and user accounts all setup but i would like certain things to require "Admin" privileges like deleting items from my inventory.
So currently everything works as is (just no admin checking)
i have made this function in my config.php (which is included on every page through the header)
function checkAdmin($conn)
{
$id = $_SESSION['member_id'];
$sql = "SELECT admin FROM members WHERE id = $id";
$query = mysqli_query($conn, $sql);
$rs = mysqli_fetch_array($query);
$admin = $rs['admin'];
if($admin == 1){
return true;
}else{
return false;
}
}
So my question is, how do i then pass that value "true/false" into my query.
Im using jQuery/Ajax to do my queries but i understand this would be handed on my "ajax.php" page where all my queries are.
my current code is:
if(isset($_GET['deleteID']))
{
if('checkAdmin' == true){
$id = $_GET['deleteID'];
$sql = "DELETE FROM members WHERE id=$id";
mysqli_query($conn, $sql);
recordLog($conn, "Members", "Removed user #$id");
$data = [
'success' => true
];
}else{
$data = [
'error' => 'Admin Privileges Required'
];
}
echo json_encode($data);
}
the actual code in itself works, without the If(checkAdmin == statement but i dont think i'm on the right lines with it.
Thanks in advance for any help :) please let me know if any more info is needed
Call the function in the if statement:
if(checkAdmin($conn) == true){
Alternately you could do:
$checkAdmin = checkAdmin($conn);
if($checkAdmin == true){
Be advised that you are at serious risk of SQL Injection. Implement this now: How can I prevent SQL injection in PHP? This is bad, bad, bad:
$id = $_GET['deleteID'];
$sql = "DELETE FROM members WHERE id=$id";
Related
I am developing an adroid app and I faced some trouble about php web service.
I want to get user type information form database and according to the answer I will do some process in the background.
So in my authentication code there is a area like this to get usertype;
function getUserType(){
$sql = "SELECT `usertype` FROM `login_test` WHERE username = '". $this->username2."'
AND password = '".$this->password2."'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
if(mysqli_num_rows($result)>0){
return (?);
}
}
and my in my login code the message will be send here;
if ($userStatus) {
// user existed
// So log him to main page
$json['success'] = 1;
$json['message'] = 'Access Granted';
$json['usertype'] = 'Client';
echo json_encode($json);
Here I dont know how to access a certain field called 'usertype' in my table (I am really new in php) and how to return the value that I got.
Any help will be apreciated
P.S = $userStatus returns ture.
You could try doing this:
$sql = "SELECT * FROM `login_test` WHERE username = '$this->username2' AND password = '$this->password2'";
$result = mysqli_query($this->DB_CONNECTION, $sql);
return $result->fetch_object()->userType;
While please do keep in mind to use prepared statements.
Have had a couple questions answered very nicely here and I've got some more trouble someone can probably help with:
I have SQL database that holds a poll question answer and a user IP address. Here is my (now working!) PHP code:
// check to see if user has already voted
$current_user = $_SERVER['REMOTE_ADDR'];
$select_query = "SELECT * FROM w_poll_counter WHERE user_IP = '" . $current_user ."';";
$result = mysql_query($select_query);
if($result)
{
$row = mysql_fetch_array($result);
$user_from_db = $row['user_IP'];
if($current_user === $user_from_db)
{
//user already voted - show results page
header("Location: scripts/show_results.php");
exit();
}
}
The code works great, except there's one problem... After a user votes and sees the results page, they can click the browser's 'back' button and then simply vote again, since the code to check their IP address doesn't run in that instance.
What do I need to do to fix this issue?
Thanks!
Check if the user has already voted before executing your update statement.
Also you should take better care, your script is very vulnerable to sql injections. https://stackoverflow.com/a/60496/3595565
I can show you this example of an implementation via pdo:
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8;', 'dbUser', 'dbPassword');
$stmtCheck = $pdo->prepare("SELECT * FROM w_poll_counter WHERE user_IP = ?");
$stmtCheck->execute(array($_SERVER['REMOTE_ADDR']));
$result = $stmtCheck->fetchAll(PDO::FETCH_ASSOC);
if(count($result) === 0){
//update
}
I'm probably not using the best method to create a user system, but it doesn't need to be fancy. I also know that I'm not the most organized
The logins and everything are alright, but I'm having a problem updating the credentials.
For example, I'm allowing users to change their username. I have the "Change Username" (Not that name) form to submit to update-username.php.
I already have mysql_real_escape_string, in the function "cleanString" in another page. My textarea submitting already has the old text in it, so you can change and view it before hand.
$user_id = "";
if(isset($_POST['id']))
{
$user_id = $_POST['id'];
}
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if(!$results) { //Check to see if query failed
die(mysql_error());
}
$resultsfetch=mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = $_POST['usernameinput'];
if(isset($_POST['usernameinput'])) {
$usernamenew = cleanString($_POST['usernameinput']);
}
if($usernamenew !=$username){
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
mysql_query($submit);
if(!$submit) { //Check to see if query failed
die(mysql_error());
}
}
It's probably something stupid or simple that I missed, or something really huge. Mainly because I am absent minded.
$submit = sprintf("UPDATE users SET username = '%s' WHERE user_id = %d",mysql_real_escape_string($usernamenew),mysql_real_escape_string($user_id));
If the page is loaded, $user_id will be NULL so noting will be updated! Make sure that this page loads, by sending $_POST['id'] . if these things are correct, check this.
"Did the database user have any permission to update the table? "
I have re-arranged your code. added comments where i changed. Try this
if (isset($_POST['id'], $_POST['usernameinput'])) { // Check if both POST id and usernameinput is available
$user_id = (int)$_POST['id']; //assuming this is an integer
$query = "SELECT username,email,display_name,access,password FROM users WHERE user_id='$user_id'";
$results = mysql_query($query);
if (!$results) {//Check to see if query failed
die(mysql_error());
}
if (mysql_num_rows($result) > 0) { //verify if there is really a user with such id
$resultsfetch = mysql_fetch_array($results);
$username = $resultsfetch['username'];
$usernamenew = cleanString($_POST['usernameinput']);
if ($usernamenew != $username) {
$submit = "UPDATE users SET username = '$usernamenew' WHERE user_id = '$user_id'";
if (!mysql_query($submit)) {//Check to see if query failed
die(mysql_error());
}
}
}else{
die("no such user with userid=$user_id");
}
}
Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
So, I guess I figured it out. It's an issue with my code carrying over to the next page.
The code I had been shown only broke the page, whether it be missing an integer, or something else. I'm not 100% sure.
Thanks for all the help guys, but now I know the issue.
EDIT:
I had forgotten to echo the $user_id in my hidden field.
Basically what i am trying to do here is to read from the table in my database using the customers login details, then retrieve the record that matches this information. In this table there is a column called "AccountType", this differentiates the average user from a manager, if this column is 1, they are a average user. If this column is 2, they are a manager.
Now im having issues implementing this in my code, below is the snippet of my process script for the login:
<?php
***session_start()
$query = mysql_query("SELECT * FROM accounts WHERE username='$username' and password='$password'", $db) or die ("Query failed with error: ".mysql_error());
$count=#mysql_num_rows($query);
if(***$count == 1)
{
***$user_row = mysql_fetch_array($result)
$userid = $user_row["userid"];
$_SESSION['userid'] = $userid;
$customername = $user_row["customername"];
$_SESSION['customername'] = $customername;
$AccountType = $user_row["accounttype"];
if ($AccountType == 2)
{
$_SESSION['manager'] = $AccountType;
}
Depending on this, when my check login script which every page includes, it will display specific links on the navigation depending what there account type is, if they are user they will have access to normal links, but if they are a manager they have access to admin functions, below is the code snippet for this also:
***session_start();
if (***isset($_SESSION['userid']))
{
$employeeid = $_SESSION['userid'];
$firstname = $_SESSION['customername'];
if (***isset($_SESSION['manager']))
{
$User_Options .='Manager links go here';
}
else
{
$Links .='Normal Links go here';
}
}
Thats just a basic truncated version, but that gives the basis of what im trying to accomplish. I am guessing down to using the while loop its overwriting the session, which i understand, however there will only be one record for the information i am searching. It works to some extent, however even if the AccountType is 1, it displays the options for 2.
Can anyone assist me further in solving this issue? Thankyou!
Use something like this on the login form:
$_SESSION['manager'] = false;
if ($AccountType == 2) {
$_SESSION['manager'] = true;
}
then later:
if ($_SESSION['manager']) {
// display manager-only options
} else {
// display user-only options
}
// Display options for everyone here
I want my php query to display the user name with a link to the user profile.
<?php
$get_items = "SELECT * FROM items WHERE category='test'";
$result = mysql_query($get_items);
while($item = mysql_fetch_array($result, MYSQL_ASSOC)){
$creator = $item['created_by'];
echo "<b>Seller: </b>"."<a href='userprof.php?id=$creator'>$creator</a>";
}
?>
Clicking on this link takes it to a user profile page that I created. But I want "userprof.php?id=$creator" to know which user to display the account information. Is this the best way to do this? How can I read the url and display the correct information?
<?php
$userId = $_GET['id'];
$sql = "SELECT * FROM user WHERE id = " . intval($userId);
$result = mysql_query($sql);
...
You are sending a GET variable.
$id = $_GET['id']; // Contains whatever was in $creator;
use $_GET for getting the variable from the URL.
like in your code you want to access the user profile then get the user id from url
like
http://localhost/test/user_profile.php?uid=2
here in the url uid is 2 thet is your userid.
you can get this id by using the code
$user_id = $_GET['uid'];
use this variable in your query.
OMG!! HORRIBLE PHP ABOUNDS! IT HURTS MY EYES!!
These people, none of them did both of the correct things:
ALWAYS FILTER USER INPUT!!
NEVER TRUST PHP ESCAPE FUNCTIONS, ESP NOT intval() and addslashes()!!
EVEN mysql_real_escape_string() HAS VULNERABILITIES AND SHOULD NEVER BE USED.
You should used prepared statements for everything in 2010.
Here it is the proper way:
<?php
if (!filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT))
{
trigger_error('Invalid User ID. It must be an integer (number).', PHP_USER_ERROR);
exit;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$sql = "SELECT * FROM user WHERE id = ?";
$pdo = new PDO('mysql:host=localhost;db=mydb', $dbUsername, $dbPassWord);
$statement = $pdo->prepare($sql);
$statement->execute(array($userId));
$result = $statement->fetch(PDO::FETCH_ASSOC);
That is 100% secure. I hope people neither vote me down nor tone down my answer. Bad code is so systemic, we just have to shout from the rooftops until the new guys start learning it correctly, otherwise PHP as a professional language is seriously harmed.