scythe scythe - 1 month ago 7
PHP Question

Delete an image using link/id from database

I want to delete an image by an button called 'DELETE'.
My image is saved on the server, my image link is saved into a database table.

To delete now works great, but every user can delete every users images right now by typing in the picture id in the URL.

uploads.php

<div id="myuploads">
<?php
//Configuration
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'myimg';

$salt = "u6d5u6mj65dehjum568nuu65umk57endjzu766imm57e8u5u56";

if(isset($_SESSION['username'])){
$hash = hash('sha224', $_SESSION['username']).$salt;
}

$conn = mysqli_connect("$host", "$user", "$pass", "$db");

//Script
if(isset($_SESSION['username'])){
$uid = $_SESSION['username'];
$dir = $uid . "/";

$alledateien = mysqli_query($conn, "SELECT * FROM imglinks WHERE uid='$uid'");

foreach ($alledateien as $datei)
{

echo "<div class='pictures'> \
<img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \
<form action='functions/deleteimg.php'></div> \
<input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
<input class='post' type='submit' value='PUBLISH'></form>";
}
}else{
header("Location: ../index.php");
}
?>
</div>


deleteimg.php

<?php
include '../config.php';

$uid = $_SESSION['username'];

$username = mysqli_query($conn, "SELECT uid FROM imglinks WHERE uid='$uid'");

foreach($username AS $name) {

if(isset($_GET['deleteimg']) && $uid = $name['uid']){
$sql = "SELECT * FROM imglinks WHERE id='".$_GET['deleteimg']."' LIMIT 1";

$filepath = mysqli_query($conn, $sql);

foreach($filepath AS $value) {
unlink($value['link']);
}

$uid = $_SESSION['username'];
mysqli_query($conn, "DELETE FROM imglinks WHERE id='".$_GET['deleteimg']."' AND uid='$uid'");
}}


The links given out coming out of the imglinks table of my database.

DATABASE STRUCTURE

If you need more detail, feel free to ask.

Answer

You need to change your buttons like this:

foreach ($alledateien as $datei)
{

    echo "<div class='pictures'> \
          <img class='pbild' src='" . $dir . $datei["link"] . "'><br/> \ 
          </div><form action='functions/deleteimg.php'> \
          <input type='hidden' name='img_id' value='".$datei["id"]."'> \
          <input class='deleteimg' type='submit' name='deleteimg' value='DELETE'> \
          <input class='post' type='submit' name='publish' value='PUBLISH'></form>";
}

Then on deleteimg.php, get the image id and execute a delete query:

if(isset($_POST['deleteimg']) && $_POST['deleteimg'] == 'DELETE'){
    $img_id = $_POST['img_id'];
    mysqli_query($conn, "DELETE FROM imglinks WHERE id='$img_id'");
}