How can i fetch uploaded images in web server and also delete the ones i don't want?

I am uploading images in the "images" folder on my web server and I want all uploaded images to be visible in a table in index.html page with a delete button for each uploaded image so that i can be able to delete any image i want to delete. I don't want anything to do with database and i will be the one uploading the images from my admin.
I only want a simple scripts that will do this job, thanks everyone


index.php

<form name="upload" action="upload.php" method="POST" enctype="multipart/form-data">
    Select image to upload: <input type="file" name="image">
    <input type="submit" name="upload" value="upload">
</form>



upload.php

<?php
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
    echo "Image succesfully uploaded.";
} else {
    echo "Image uploading failed.";
}
?>
ten tenAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mohan singhWeb developerCommented:
It is simple
first create page 1  like Fetch_image.php and do like this
 <table border='1'>
<tr> <th>Image </th>  <th> Action </th></tr>
<?php
$sql = mysqli_query($conn, "SELECT  * FROM your_table";
while($row = mysqli_fetch_array($sql)){
$image =  $row['image_path'];
$id = $row['id'];
// $path is fetch all path which is available in your database column 
// also fetch image id which is auto generated in your database table
?>
<?php

echo "<tr> <td><img src='image'> </td><td> <a href='delete_image.php?id=$id'> </td>";

<?php  } ?> 

// $id is your image id which will pass to your next page in delete_image.php 

Open in new window


After this  you have to receive that id which you will click

create second page  delete_page.php
than do like this
 
<?php
if(isset($_REQUEST['id'])){
$image_id = $_REQUEST['id'];  // $image_id is that id which you clicked in your first page 
$delete_sql = mysqli_query($conn, "DELETE FROM your_table_name WHERE id = '$image_id'";
if($delete_sql){
echo"<script> alert('Image deleted successfully') ;window.location='Fetch_image';</script>";
}
else{
echo"<script> alert('Something went wrong) ;</script>";
} 
?>

Open in new window



Definitely it will work
0
Php_expertCommented:
db.php // DB connection

<?php

// server info
$server = 'localhost';
$user = 'root';
$pass = 'root';
$db = 'images';

// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);


?>

list.php (-- will just display one list of images with actions)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>List Images</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>

<h1>View Images</h1>


<?php
// connect to the database
include('db.php');

// get the records from the database
if ($result = $mysqli->query("SELECT * FROM images ORDER BY image_id"))
{
      // display records if there are records to display
      if ($result->num_rows > 0)
      {
            // display records in a table
            echo "<table border='1' cellpadding='10'>";

            // set table headers
            echo "<tr><th>ID</th><th>Image Name</th><th>Image</th><th></th></tr>";

            while ($row = $result->fetch_object())
            {
                  // set up a row for each record
                  echo "<tr>";
                  echo "<td>" . $row->id . "</td>";
                  echo "<td>" . $row->name . "</td>";
                  echo "<td><img src=" . $row->imagepath . "></td>";
                  echo "<td><a href='delete.php?id=" . $row->id . "'>Delete</a></td>";
                  echo "</tr>";
            }

            echo "</table>";
      }
      // if there are no records in the database, display an alert message
      else
      {
            echo "No results to display!";
      }
}
// show an error if there is an issue with the database query
else
{
      echo "Error: " . $mysqli->error;
}

// close database connection
$mysqli->close();

?>

<a href="index.php">Add New</a>
</body>
</html>


delete.php (To delete image record)

<?php

// connect to the database
include('db.php');

// confirm that the 'id' variable has been set
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
      // get the 'id' variable from the URL
      $id = $_GET['id'];

      // delete record from database
      if ($stmt = $mysqli->prepare("DELETE FROM images WHERE id = ? LIMIT 1"))
      {
            $imageData = $mysqli->query("SELECT * FROM images WHERE id = ".$id." LIMIT 1 ");
            $stmt->bind_param("i",$id);
            $stmt->execute();
            $stmt->close();
            
            
            while ($row = $imageData->fetch_object())
            {
             unlink($row[imagepath]);
            }

      }
      else
      {
            echo "ERROR: could not prepare SQL statement.";
      }
      $mysqli->close();

      // redirect user after delete is successful
      header("Location: list.php");
}
else
// if the 'id' variable isn't set, redirect the user
{
      header("Location: list.php");
}

?>
0
ten tenAuthor Commented:
Thanks for your reply, i stated i don't want anything that has to do with database, i only want a simple way i can view all files uploaded in a folder in  the index.html and also can delete the ones i don't want.
somebody told me about using unlink in php.
don't know how to go about it
0
The Five Tenets of the Most Secure Backup

Data loss can hit a business in any number of ways. In reality, companies should expect to lose data at some point. The challenge is having a plan to recover from such an event.

Php_expertCommented:
Ok,

you can go with glob php function like below

<table border="3">
    <tr>
        <td>    
            <?php
            $files = glob("img/*");
            foreach ($files as $file) {
                echo "<div class='divimages'>";
                echo '<img src="'.$file.'"/>';
                echo "<input type='submit' value='Delete image'/><br>";
                echo "</div>";  
            }
            ?>
        </td>
    </tr>  
</table>
0
Vijaya KumarCommented:
Try this one

save as files.php
------------------------

[<?php

$dirname = "images";
$images = glob("images/*.*");


      echo "<div id='display'>";
      foreach($images as $image) {
            echo '<img height="50px" width="50px" src="'.$image.'" /><button class="del" name="'.$image.'">delete</button> <br />';
      }
      echo "</div>";



?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
      
      $('.del').click(function(){
            alert($(this).attr('name'));
            var url = $(this).attr('name');
            var name = url.split("/");
            $.ajax({
            type: "POST",
            url: "del.php?name="+name[1],
             }).done(function( data ) {
                    $('#display').html();
                    $('#display').html(data);
             });
      });
      
});
</script>]

del.php
-----------
[<?php

$path = "images/".$_GET["name"];
unlink($path);

$dirname = "images";
$images = glob("images/*.*");

      foreach($images as $image) {
            echo '<img height="50px" width="50px" src="'.$image.'" /><button class="del" name="'.$image.'">delete</button> <br />';
      }



?>]
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ten tenAuthor Commented:
Thanks @vijaya Kumar, you are the best, works like a charm
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.