PHP prevent URL input to delete row in database - php

I’m working on a blog website where the idea is that the current user that is logged in can edit and delete their own posts. I finally got it to work, but my question is how I can prevent that a user can write the following input in the URL and do the same actions as my delete.php action.
(Example) Manual URL input with topic_id:
/delete.php?del=133
Do anyone know how I can edit my existing code or know a better solution to the problem I will be much grateful!
This is how my code looks:
Profile.php:
if (#$_GET['id']) {
$check_d = mysql_query("SELECT * FROM users WHERE id ='".$_GET['id']."'");
while ($row_d = mysql_fetch_assoc($check_d)) {
echo "<div class='spacer'></div><h2 class='headertext'>Inlägg skapade av : ".$row_d['username']."</h2>";
$check_u = mysql_query("SELECT * FROM topics WHERE topic_creator='".$row_d['username']."' ORDER BY topic_id DESC");
while ($row_u = mysql_fetch_assoc($check_u)) {
$id = $row_u['topic_id'];
echo "<tr>";
echo "<td class='postmain'><a href='topic.php?id=$id' class='links'>".$row_u['topic_name']."<br /></a></td>";
echo "<td class='postmain'><p class='text'>".$row_u['topic_creator']."</p><br /></td>";
echo "<td class='postmain'><p class='text'>".$row_u['date']."</p><br /></td>";
if($_SESSION['username'] === $row_u['topic_creator']) {
echo "<td class='postmain'><a href='edit.php?edit=$id'><button>Redigera</button></a>";
echo "<a href='delete.php?del=$id'><button>Ta bort</button></a></td>";
}
echo "</tr>";
}
}
}
The highlighted code shows that only the current session (user) who made the post can edit and delete their own posts.
Delete.php:
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
//deleting the row from table
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
//redirecting to the display page
header("Location:admin.php");
}

Using isset function is solution here . The isset function will check that whether user clicked the delete/modify link or not(i.e he pasted delete.php directly in link) . So your code will only execute when user clicks the link .
if (isset($_GET['del']))
{
// your profile.php code here
}
else
{
// error message
}

You can use the same $_SESSION logic to ensure anyone accessing the delete.php has the appropriate permissions.
if (isset($_GET['del'])) {
//getting id of the data from url
$id = $_GET['del'];
// Get the author for the specified post to ensure they are permitted to do so
// TODO
// Check that the author is the same as the $_SESSION user
if($_SESSION['username'] === $postAuthor) {
//deleting the row from table - FIX THIS (see below)
$sql = "DELETE FROM topics WHERE topic_id='$id'";
$res = mysql_query( $sql );
} else {
// User is not authorized, create error handling
// TODO
}
//redirecting to the display page
header("Location:admin.php");
}
Unrelated, beware of SQL injection. Bobby Tables is a good guide and you should not be using the mysql_ functions and should be using prepared statements.

Related

how to display all data on a webpage

I wrote this code to comment system on my webpage. But i want to keep showing all data on web page while another people do comment and see another people's comment
include 'connection.php';
$con1= new connection();
$db=$con1-> open();
$qry= "INSERT INTO post (content) VALUES ('".$_POST["commentEntered"]."')";
$db->exec($qry);
if(isset($_POST['Submit'])) {
if ($con1->query($qry) === TRUE) {
echo "Your Comment Successfull Submited";
} else {
echo "Error: " . $qry . "<br>" . $con1->error;
}
$sql = 'SELECT * FROM post';
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$con1->close();
}
if ($_POST)
echo "<h2> Your Comment Successfully Submitted</h2> <br> ".$_POST['commentEntered']."<br>";
}
?>
after your select, inside your if($_POST) write this
while ($row = $q->fetch()) {
foreach($row as $key=>$val){
if (!is_numeric($key)) echo "<p>$key=>$val</p>";
}
}
EDIT i'm not 100% sure you can close the connection and still do a ->fetch, (I think you can but i've never tried it) so you may have to move your connection close after this (but I think you'll be alright), also I am not sure if setFetchMode will return duplicate numbered keys or not so as a precaution I have filtered for them you may not need to

How to remove a row from MySQL table data using html delete button in PHP

I am working on a project, for school. I currently have a product page to display an assortment of item includes image, description and price etc...
Under each product I have a delete button, when logged in as admin, which displays fine.
if (is_admin())
echo '<button>Delete item</button>'; }
I want to know how remove the row of data from MySQL table on clicking the delete button.
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
$deleted = mysql_query($db, "DELETE FROM products");
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'$];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo '' . $product_name ."</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo '<button>Delete item</button>';
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
<!-- end snippet -->
You should post to a url with the id in the post data, then redirect back to where you were.
<?php
//html on productpage
if(isset($_GET['product_deleted'])){
if($_GET['product_deleted'] === 'true'){
echo 'The product was deleted';
}else{
echo 'The product could not be deleted';
}
}
if (is_admin()){
/**
* It's a good idea for the page that deletes to be different from the one your on, so that when you redirect back,
* they can refresh the page without getting something
* along the lines of 'refreshing with page will re-post the data'
*/
?>
<form method="POST" action="/product/delete.php">
<button>Delete item</button>
<input type="hidden" name="id" value="<?php echo $image_id; ?>" />
</form>
<?php
}
//PHP on /product/delete.php
if(is_admin() && $_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['id'])){
//delete sql here
header('Location: /productpage.php?product_deleted=true'); //redirect back
}
One approach
Change the button to a a element and make the href look like this:
yourdomain.tld/products/delete/{id}
You have to echo the primary key from your mysql database at the id position. It will look like this:
yourdomain.tld/products/delete/5
Then you have to change your .htaccess in a way that all requests go to your index.php in your root project. At the index.php you can do the actually query then.
Update
Keep in mind that anyone visiting this URL can delete products with this approach. You have to make sure that only the admin can do that. The preferred method is a POST request.
You can also send the primary key parameter to your PHP script you are just showed. With this approach you don't need to edit your .htaccess. You may pass it as an URL parameter like this:
yourdomain.tld/your-script.php?delete-product={id}
In your script you can get the parameter like this:
<?php
if (isset($_GET['delete-product'])) {
// your mysql query to delete the product
} else {
// something else
}
If you want to delete the entire row of an record from your db you can do like this. So that you can pass the product id and delete the row. Just bind the id with query using bind parameters concept
$knownStmt=mysqli_prepare($conn, "DELETE FROM `YourTableName` WHERE `pdt_id` = ?;");
if( $knownStmt ) {
mysqli_stmt_bind_param($knownStmt,"d",$pdt_id);
mysqli_stmt_execute($knownStmt);
mysqli_stmt_close($knownStmt);
}

Is there a way to DELETE notes by PHP without having their ID's assigned with them?

I'm making a web app exercise, where the registered user can log in and create notes. Now I'd like to add a function, that deletes a certain note if I click the "X" I'm about to add to their side, but I cannot really figure out how is it possible to identify a certain note created by this method, more precisely, that how can I return it's id to use for the delete query.
Here is the site you can check the way it looks like now, below I'm gonna attach the way I've listed the comments. Thanks in advance!
http://laszlovaszi.com/mx_agency/index.php
<?php
function confirm_query($result) {
if (!$result) {
die("Database query failed.");
}
}
function find_notes_by_id($user_id) {
global $connection;
$row = array();
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
confirm_query($result);
$final_data = array();
while($row = mysqli_fetch_assoc($result)){ // iterates over the result-set object to get all data
$final_data[] = $row; //assigns value to the array
}
return $final_data;
}
?>
<div class="notes text-center">
<?php
$notes_set = find_notes_by_id($userRow['id']);
if(empty($notes_set)){
echo "No notes have been posted for this user yet.";
} else {
echo "<div class=\"notelist text-left\">";
foreach($notes_set as $note){
echo "<div class=\"note text-left\">";
echo "● ";
echo htmlentities($note['content']);
echo "<br />";
echo "</div>";
}
echo "</div>";
}
?>
</div>
Now I'd like to add a function, that deletes a certain note if I click
the "X" I'm about to add to their side
Make the "X" a link to a javascript function that takes the note id and makes an ajax request to the server to delete the note. The id would be placed in the function call while you render each note in your foreach($notes_set as $note) step. The link could be written this way:
echo "<a onclick='deleteNote($note[id])'> X </a>";
When the user presses the "X", the deleteNote() function will execute. This function would make an AJAX request to delete.php?note=123 (123 is whatever PHP put in as $note['id']).
Here is an example in raw Javascript. If you use a framework such as JQuery, it's even simpler:
<script>
function deleteNote(noteID) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//remove the note from the DOM and alert user of success
}
};
xhttp.open("GET", "delete.php?note="+noteID, true);
xhttp.send();
}
</script>
In PHP, you can retrieve the note id with $id = $_GET['note']. This value can then be used in your DELETE query.
Just remember to first verify the following before you delete:
the user is authenticated
the note id really belongs to that user
Otherwise, anyone will be able to delete everybody's notes.

Delete something from sql

I want to delete columns in my sql, which is going with succes. But there is another problem, I need to solve. I've tried and checked here around. All with any kind of succes I will try to explain my problem.
I've a member system where you can add your content, edit you submitted content and now I'm creating to delete your content. My script can delete now post which are created by the same user as logged in. For example my account is called Bobby and someone is called Alex I cannot delete the content of Alex only mimes, thats what I want.
For example my content link of bobby : category.php?nameID=cat2&id=22 And the delete link is deletepost.php?id=22
EX. content link Alex:
category.php?nameID=cat2&id=23 And the delete link is deletepost.php?id=23
When I'm logged in as Bobby and I go to deletepost.php?id=23 and receive a message like You cannot delete this content!
And When I go to mimes deletepost.php?id=22 I need to receive a message like: Your content has been delete succesfully!
I'm only receive NO!
<?php
$user = new User();
if (isset($_GET['id'])) {
$id = mysql_real_escape_string($_GET['id']);
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
if($user->isLoggedIn()) {
$pakuser = $user->data()->username;
$sql = mysql_query("DELETE FROM post
WHERE post.id = '$id' AND post.add = '$pakuser'")
or die(mysql_error());
if (!$sql) {
echo 'NO';
}
if ($sql) {
echo 'YES';
}
}
}
?>
Beside from the possible sql injections in your code, you can try this format for a delete query to determine the mistake:
<?php
$sql = "
DELETE FROM
post
WHERE
post.id = ".$id." AND post.add = '".$pakuser."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_affected_rows() == 0)
{
echo 'No records Deleted. <br />Query: '.$sql;
}
else
{
echo 'There are '.mysql_affected_rows().' records deleted.';
}
?>
Are you also sure that post.add is the username?

Can't find the friend's id to store it to the database

I'm really struggling with this now for a while and can't seem to get it working. In members.php (where I show all the registered users) I have a list printed out with a link "ADD TO FRIENDS" next to each user.
I managed, for testing purposes to display each members id well (so it gets the ID) but when I click the link it directs to the friends.php where it seems the fault is in. I don't know how to get that friend's id I clicked on IN THE friends.php file. Please have a look!
members.php
<?php
include 'connect.php';
include 'header.php';
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> to view all the <b>registered</b> members.';
echo '<br/><br/>';
}
else
{
echo '<h2>Registered users:</h2>';
$sql = "SELECT * FROM users ORDER BY user_name ASC";
$result = mysql_query($sql);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
//$name = mysql_result($result,$i,"user_name");
//$id = mysql_result($result,$i,"user_id");
//$picture = mysql_result($result,$i,"pic_location");
//?friend_id="'. $id .'
while($user = mysql_fetch_array($result)){
echo $user['user_name'].'<br/><br/>ADD TO FRIENDS<br/>';
echo $user['user_id'];
echo '<br/><br/>';
}
$i++;
}
///////////////////////////////
/// adding users as friends ///
///////////////////////////////
//while($user = mysql_fetch_array($result))
//echo $user['user_name'].'
//ADD TO FRIENDS<br/>';
//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
}
include 'footer.php';
?>
As I said I'm not sure how to get this so please have a look! Thanks!
J
friends.php
<?php
include "connect.php";
include "header.php";
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> if you want to add the person as a friend!';
echo '<br/><br/>';
}
else
{
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
//friend_id is the ID of the friend that is clicked on...
//HOW DO I GET THAT ID THAT IS CLICKED ON IN THE WHILE "loop" in members.php?
$friends = ("INSERT INTO friends SET user_id='" . $_SESSION['user_id'] . "', friend_id='".$id."', status='0'");
$result_friends = mysql_query($friends);
if(!$friends)
{
//When you can't add this person as a friend this error will show!
echo 'You cannot add this user at this time. Please try again later!';
}
else
{
//When the friend is now added to the system!
echo 'Great! Now the user needs to approve before you can be friends!';
}
}
?>
On your friends.php use
$_GET['user_id']
Instead of $id, $id is undefined, to get the value of id from the query string you call it using an $_GET variable like,
$_GET['name_of_query_string_value']

Categories