So basically I have a PHP script that takes all the images from the user's individual folder in the directory and displays them on his/her gallery page. Now I want to add a delete function but im lost as to how to do it. Any help would be great!
<?php
$userid = $_GET['UID'];
$img_path = "./$userid";
chdir($img_path);
$images = glob('*.{jpg, jpeg, png, gif}', GLOB_BRACE);
foreach ($images as $image){
if (file_exists("./thumbs/$img_path/{image}")){
echo "<a href='$img_path/{$image}' rel='lightbox'><img src='./thumbs/$img_path/{$image}' alt=\"{$image}\" /></a>";
} else {
echo "<a href='$img_path/{$image}' rel='lightbox'><img src='./$img_path/{$image}' width='200' height='150' alt=\"{$image}\" /></a>";
}
}
?>
Create an anchor tag in the gallery with the file name as identification attribute. for example.
<?php
$userid = $_GET['UID'];
$img_path = "./$userid";
chdir($img_path);
$images = glob('*.{jpg, jpeg, png, gif}', GLOB_BRACE);
foreach ($images as $image){
if (file_exists("./thumbs/$img_path/{image}")){
echo "<a href='$img_path/{$image}' rel='lightbox'><img src='./thumbs/$img_path/{$image}' alt=\"{$image}\" /></a>";
//add this line
echo "<a href='$img_path/{$image}?delete=$image' rel='lightbox'>Delete</a>";
} else {
echo "<a href='$img_path/{$image}' rel='lightbox'><img src='./$img_path/{$image}' width='200' height='150' alt=\"{$image}\" /></a>";
}
}
//Updated and fixed the error, there was missing closing bracket here.
if(isset($_GET['delete'])) {
$image = $_GET['delete'];
unlink('./thumbs/'.$img_path.'/'.$image);
}
create a delete button inside anchor tags that directs the page to a delete script, passing in the URL of the image, or the id of the image as a parameter...
<a href="http://example.com/delete.php?type=image&id=1">Delete this image</a>
Inside that script, you might have to change the permissions of the file/directory: http://php.net/manual/en/function.chmod.php
before deleting (unlinking) the file: http://www.php.net/manual/en/function.unlink.php.
Then send the user back to the original page with a call to header(): http://php.net/manual/en/function.header.php
You can use the unlink function of php:
<?php
unlink('./' . $img_path . '/' . $image);
unlink('./thumbs/' . $img_path . '/' . $image);
?>