Delete entire mysql row by grabbing link? - php

I have a list of users with names and emails displayed for admins and users ON THE SAME PAGE....
If an admin views it it shows an extra column called "Action"
Which shows three links
Edit | Delete | Make Admin
--------------------------
I have the delete button grab information from that table row and move it into a link
Here is the setup
echo "
<td>
<a href='admin.php?action=deleteuser&username={$row['username']}'>Delete</a>
</td>";
Here it is in action:
admin.php?action=deleteuser&username=bob
I spaced it out for viewing purposes.....
Anyways
I want the site to somehow grab the information FROM the url and somehow delete the row where username is equal to "bob" or something like that
Any ways to do this? Please help out.
Also how would I make it secure since the page is accessible to anyone so if someone was to manually type that link they would delete it wouldn't they?
Maybe check if the user is admin before the link runs
Here is my check admin code
if (has_access($session_user_id, 1) === true) {
echo 'The user is an admin!';
}

Something like this in admin.php ?
function getLoginUserByCookie()
{
return isset($_COOKIE["loginusername"]) ? $_COOKIE["loginusername"] : "";
}
if(getLoginUserByCookie() != "admin")
{
header("Location: /login.php");
exit;
}
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "dbuser", "dbpass");
} catch (PDOException $e) {
echo $e->getMessage();
exit;
}
$strSQL = "DELETE FROM users WHERE (username=:username);";
$stmt = $pdo->prepare($strSQL);
$stmt->execute(array(
":username" => $_GET["username"]
));
/login.php is a big job, you might find some example to check login. And save loginusername in cookie.

Related

User permissions custom cms

looking for some advice on my current setup and if there is a better approach (this is my first attempt at building an app like this) but I am at a point where I need user roles, only two so user and admin.
I have a users table and a groups table and also a join table which takes the ID from the users table and the Id from the groups table and I can allocate which group the user belongs too.
I am wanting to set a way to do a couple of things, prevent 'users' accessing the admin area by typing in the url /admin/index.php and also show a link on the index page if they are an admin and not see it it if they are a normal user.
Here is my code to demonstrate that I can show the users role title but struggling at this point:
<?php
$user = $_SESSION['user'];
try{
$results = $dbh->query("SELECT *
FROM groups
INNER JOIN user_group_link_table
ON groups.id = user_group_link_table.group_id
WHERE user_group_link_table.user_id = $user");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$group = $results->fetchAll(PDO::FETCH_ASSOC);
foreach($group as $groups){
echo
$groups["name"]
// show a link to admins that user do not see?
;}
?>
I am wondering if my approach is totally wrong?
UPDATE
<?
include('session.php');
if (!isset($_SESSION['user'])) {
header("Location: index.php");
}
if(!ini_get('date.timezone'))
{
date_default_timezone_set('GMT');
}
// This could be an include file for all admin pages
$isAdmin = false;
foreach($group as $groups){
if($groups['name'] === 'admin'){
$isAdmin = true;
break;
}
}
if(!$isAdmin){
header('Location: index.php'); // or some other arbitrary location
die();
}
?>
And I get this error:
Notice: Undefined variable: group in /Applications/MAMP/htdocs/dashboardr v3.2.3/admin/header.php on line 12
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/dashboardr v3.2.3/admin/header.php on line 12
I am wanting to set a way to do a couple of things, prevent 'users' accessing the admin area by typing in the url /admin/index.php and also show a link on the index page if they are an admin and not see it it if they are a normal user.
I'll give you a solution that'll work in your current setup; It's not the way to go, but i'll get the job done for now. If you're worried about the user being in a specific role, you're better off specifying that role in your query rather than iterating through all their potential roles.
// This could be an include file for all admin pages
$isAdmin = false;
foreach($group as $groups){
if($groups['name'] === 'admin'){
$isAdmin = true;
break;
}
}
if(!$isAdmin){
header('Location: index.php'); // or some other arbitrary location
die;
}
You'll want to place this at the top of the page, before you spit out any kind of HTML.

adding a column in mysql so that depending on which user logs in they go to a specific page

below is the authorisation script (from login). I want to send a user to a specific page depending on (new column called company to be added to database table) a user and their company.
Current script, even if someone can point me in the direction I would appreciate it:
<title>authorise</title>
<?php
session_start();
$un = $_POST['username'];
$pw = $_POST['password'];
if ($pw != ''){
$_SESSION['user'] = $un;
echo "Incorrect username / password";
}
try
{
$dbh = new PDO("mysql:host=localhost;dbname=login_site","root","black$23");
}
catch (PDOException $e){
echo $e->getMessage();
}
$query = "SELECT * FROM users WHERE LOWER(username)=:username";
$stmt=$dbh->prepare($query);
$stmt->bindValue(':username',strtolower ($_POST['username']));
$stmt->execute();
if ($stmt->rowCount() == 1)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
require('blowfish.php');
require('bcrypt.class.php');
$bcrypt = new Bcrypt(4);
if($bcrypt->verify($_POST['password'],$row['password']))
{
echo"logged in!!";
header("Location: hollyfort/123.php");
}
}
?>
I think you need a table with the userID and a page id (or perhaps w/ the companyID and a pageID), so you can determine the page to be returned by the user or company. Maybe you even want both tables, e.g. if you want all employees of a company to get a certain site, but the CEO should get to a special site where he can see all his employees' activities.
you then first check, if an entry for that user exists (if it does, you return the page). if not, check if an entry for the company exists. if you cannot find an entry, you probably want to return a default page
all is ok - I setup company variables to check against the database column and it works :)

Get data from database based on session

When you log in by my login form authentication.php will check if the data from the inputs excists in the database. When there is a match the user will be directed to a page for his role so lets say the user is a admin he will be directed to admin.php. When the user is successfully logged in i want to show a message like welcome firstname lastname. In my database i have a field called firstname and a field called lastname. I hope someone can help me with this since i cannot seem to figure it out :(
authentication.php
<?php
session_start();
// Making a connection with the database.
$mysqli=new MySQLi("localhost", "root", "root", "portfolio");
$role="";
// Declaring the username and password input.
$username=filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password=filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// If role from members where username and password from inputs exicts in database bind parameters.
// If given parameters not excists in database die
if($query=$mysqli->prepare("SELECT `role` FROM members WHERE username=? AND password=?")) {
$query->bind_param("ss", $username, $password);
$query->execute();
$query->bind_result($role);
$query->fetch();
} else {
echo "Errors in the Query. ".$mysqli->error;
die();
}
// If $role is filled make session for username to check if logged in and session role for redirect page.
// If $role and $username is not filled invalid password, username combination.
if($role!="") {
$_SESSION['ingelogt']=$username;
$_SESSION['user_role']=$role;
$location="$role.php";
header("location: $location");
} else {
echo "Invalid password, username combination";
echo "<br/><a href='login.html'>Click to go back</a>";
}
?>
The page the admin will be directed to called admin.php
<?php
session_start();
// If session is not ingelogt lead back to index.php.
if(!isset($_SESSION['ingelogt'])) {
header("location: index.php");
}
// The role that has access to this page.
$page_role="admin";
$role=$_SESSION['user_role'];
// If a user with a different role visits wrong page.
if($role!=$page_role)
{
echo "You are not supposed to be here.";
die();
}
// Start new DOMDocument and load html file.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile("admin.html");
libxml_use_internal_errors(false);
// If user is logged in add logg out icon in the menu.
if($_SESSION['ingelogt']) {
$oUl = $dom->getElementById('navUl');
$oList = $dom->createElement('li');
$oLink = $dom->createElement('a');
$oLink->setAttribute('href','logout.php');
$oI = $dom->createElement('i');
$oI->setAttribute('class','icon-logout');
$oLink->appendChild($oI);
$oList->appendChild($oLink);
$oUl->appendChild($oList);
}
// Save DOMDocument with html document.
echo $dom->saveHTML();
?>
If I'm misunderstanding you in any way, just give me a hint, and I will delete this answer. Although what I assume that you want to do is to print the greeting somewhere on the page, based off the user's first name and surname.
Basically, once you have declared a $_SESSION-element, you can access it at different pages (similar to $_COOKIE, but not identical). So the best solution for this is to initialize $_SESSION variables with the first- and last name you receive from the database, and then print those variables on the desired pages (same method as you've used with the role).
Firstly, you need to fetch the names in the database, which can be done by changing the if-statement in authentication.php to the following:
if($query=$mysqli->prepare("SELECT `role`, `firstname`, `lastname` FROM members WHERE username=? AND password=?")) //assuming that your columns are called `firstname` and `lastname`
To fetch these, you also need to change the row further down to:
$query->bind_result($role, $first, $last);
When using fetch on the next row, your variables will be put into their appropriate bound ones. So after that statement, you can do the following (preferably after the $_SESSION['user_role']=$role;):
$_SESSION["firstname"] = $first;
$_SESSION["lastname"] = $last;
After that point, you can echo the first- and last name wherever you want (it depends on where you want it to be put...). If you want it to appear at the top of admin.php, for instance, you can simply put this before $dom = new DOMDocument();:
echo "Hello " . $_SESSION["firstname"] . " " . $_SESSION["lastname"] . "!";
If you're confused where to put something, then try re-reading the given instructions. Most of my examples are simply things to replace (in which case, you just need to find the corresponding code), and if not that, I've tried to redirect you. Although realize that things like these are important to know without getting the code right in your hand, so I advice you to try to understand.

Only let a certain group display page

I want to make a certain page viewable only to a certain group of a database. My SQL table is set up as:
Table: DD_users
Columns: id | group | username | paraphrase | guild | level | salt
This is the code I am trying to use:
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
if($_SESSION['user']['group'] == '0')
{
// Destroy the session to make them log in again.
unset($_SESSION['user']);
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
// Everything below this point in the file is secured by the login system
When I try this, will let any user group (0, 1, and 2) access the page when I only want groups 1 and 2 to access the page.
You don't have any code to check if they are in groups 1 or 2. Just wrap the code around an if.
if($_SESSION['group'] == '1' || $_SESSION['group'] == '2')
Also make sure $_SESSION['group'] is set using isset. If it is not set then the last if will fail.
Got it working another way:
require('common.php');
$charname = $_SESSION['user']['username'];
$query = "SELECT adminaccess, guild, username, class, level, active, canRegister, canNews, canActive
FROM DD_users
WHERE username = ?";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute(array($charname));
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
//print_r($rows);
$group = $rows['0']['adminaccess'];
$guild = $rows['0']['guild'];
$username = $rows['0']['username'];
$class = $rows['0']['class'];
$level = $rows['0']['level'];
$accessAdmin = $rows['0']['adminaccess'];
$canRegister = $rows['0']['canRegister'];
$canNews = $rows['0']['canNews'];
$canActive = $rows['0']['canActive'];

Errors for changing variables content depending on session status

I am trying to write a script that changes a veriables content depending on there session status and what ID that was in the URL of the page (e.g www.example.com/profile.php?id=1) so it would display one set of content if they arnt logged in and viewing someone elses profile, another if there logged in and on there own profile, and another if there logged in and viewing someone elses profile.
Firstly the script gets the ID from the url:
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
Then it runs some other code i wont include, then this code:
// ------- DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
if (isset($_SESSION['idx']) && $logOptions_id == $id) { // If session is set and ID matches the profiles ID
$content = ""Your viewing your own profile";
} else if (isset($_SESSION['idx']) && $logOptions_id != $id) { // If SESSION is set, but ID dosent match profiles ID
$follow_option = "Your viewing someone elses profile";
} else {
$content = "Your are not logged in";
}
// ------- END DECIDES WHAT TO DISOPLAY, DEPENDING ON VERIABLES ---------
print $content;
Now to my problem, all it does is display the option for being logged in and viewing someone elses profile "Your viewing someone elses profile". If you see any errors that would lead to this, please answer below. Thanks! :)
It seams your variables don't hold the expected values when the $logOptions_id != $id runs, or you either forget to start the session. I don't see reference where $logOptions_id gets assigned. Use your IDE tool to debug the code.

Categories