php - Delete a specific image out of a folder -
i have website allows users upload photos folder. when page refreshes, show images inside folder.
i used scandir instead of glob function read images. check file type extension see if in allowed format (jpg, jpeg, gif, png) use loop display them. each image has "delete" link next it.
when user presses "delete" link, want remove specific image in folder. know function unlink() able delete image, couldn't because don't know how pass specific image name delete.php. told me use ajax, haven't learned yet. if necessary, go learn immediately. please tell me if there ways solve instead of ajax. thank much!
$dir = 'images/'; $file_type_allowed = array('jpg','jpeg','png','gif'); $dir_contents = scandir($dir); foreach($dir_contents $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>'; }
you pass argument in url, , access via $_get superglobal. reload page however. ajax allow user click "delete" link , not have page reload.
anyway, if make delete link like
echo '<a href="delete.php?file=' . urlencode($dir . '/' . $file) . '">delete</a>';
and in delete.php access file needing deleted
$file = urldecode($_get['file']); // verify file exists, , user should have access unlink($file);
you need careful however, , make sure check file location prior deleting. otherwise malicious user enter "delete.php?file=delete.php", , break site. need check directory deleting from, , file type image.
Comments
Post a Comment