Hold_My_Anger
Hold_My_Anger

Reputation: 1015

Delete a specific image out of a folder

I have a website that allows users to upload photos to my folder. When the page refreshes, it will show all images inside that folder.

I used scandir instead of glob function to read the images. I check the file type extension to see if it is in allowed format (jpg, jpeg, gif, png) Then I use a loop to display them. Each image has a "delete" link next to it.

When the user presses the "delete" link, I want to remove the specific image in the folder. I know the function unlink() is able to delete the image, but I couldn't do this because I don't know how to pass that specific image name to delete.php. Somebody told me to use AJAX, which I haven't learned yet. If it is necessary, I will go learn it immediately. So please tell me if there are any ways to solve this instead of AJAX. Thank you so much!

$dir  = 'images/';

$file_type_allowed = array('jpg','jpeg','png','gif');

$dir_contents = scandir($dir);

foreach($dir_contents as $file){

    $file_type = explode('.',$file);
    $file_type = strtolower(end($file_type));

    if($file !== '.' && $file !== '..' && in_array($file_type, $file_type_allowed) == true){

        echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
        echo '<a href="delete.php">Delete</a>';     
}

Upvotes: 0

Views: 1238

Answers (1)

cwurtz
cwurtz

Reputation: 3257

You could just pass the argument in the URL, and access it via the $_GET superglobal. This will reload the page however. Ajax will allow the user to click the "Delete" link and not have the page reload.

Anyway, if you make your delete link something like

echo '<a href="delete.php?file=' . urlencode($dir . '/' . $file) . '">Delete</a>';

And then in delete.php access the file needing to be deleted as

$file = urldecode($_GET['file']);
// verify the file exists, and that the user should have access
unlink($file);

You need to be very careful however, and make sure you check the file location prior to deleting. Otherwise a malicious user could just enter "delete.php?file=delete.php", and break your site. So you need to check what directory they are deleting from, and that the file type is an image.

Upvotes: 1

Related Questions