PHP glob 和取消链接

PHP glob and unlink

有点奇怪,但我想出了如何使用 glob 来显示图像列表,现在我想在每个图像下添加一个按钮,让你可以单独删除每个图像,我想我只需要使用 unlink,但每当我尝试时,它似乎都会删除服务器上的所有文件!:')

这是我目前的代码:

<?php
  // This sets the variable $filelist, and get it to search the specificied levels of wildcards for jpg, png, JPG, and PNG using glob:
    $filelist = glob('{*.jpg,*/*.jpg,*/*/*.jpg,*/*/*/*.jpg,*/*/*/*/*.jpg,*/*/*/*/*/*.jpg,*.png,*/*.png,*/*/*.png,*/*/*/*.png,*/*/*/*/*.png,*/*/*/*/*/*.png,*.JPG,*/*.JPG,*/*/*.JPG,*/*/*/*.JPG,*/*/*/*/*.JPG,*/*/*/*/*/*.jpg,*.PNG,*/*.PNG,*/*/*.PNG,*/*/*/*.PNG,*/*/*/*/*.PNG,*/*/*/*/*/*.PNG}', GLOB_BRACE);

  // This filters the above into date order from newest to oldest:
  usort($filelist, create_function('$a,$b', 'return filemtime($b) - filemtime($a);'));

  // This is how I now output the data, basically looks for each value of $filelist and sets it as $link, then outputs this and concatenates it with itself as a href and a background-image:
  echo '<div class="thumbnail-grid">';

      if($filelist){
        foreach($filelist as $link){
          echo '<div class="tile-container">';
          echo '<a style="background-image: url('.$link.');" class="photo-link" href="'.$link.'"><i class="fas fa-link"></i></a>';
          // This adds in a delete button:
          echo '<form method="post"><input style="cursor: pointer;" name="delete" type="submit" value="DELETE"></form>  ';
          echo '</div>';
          // This is the script that should be doing the unlinking:
          if(isset($_POST['delete']))
            {
                unlink($link);
            }
        }
      }else{
        echo ' No images found.';
      }

  echo '</div>';

希望这一切让sense/isn不要要求太多!

非常感谢,杰克。

这不是很安全,因为任何人都可以发送带有文件名的 POST 变量并将其删除。 但作为示例,您可以遍历文件并为删除按钮提供一个文件名值,然后当您检查发布的删除按钮时删除文件。

// This is the script that should be doing the unlinking:
if(isset($_POST['delete'])){
    unlink($_POST['delete']);
}

if($filelist){
    foreach($filelist as $link){
        echo '<div class="tile-container">';
        echo '<a style="background-image: url('.$link.');" class="photo-link" href="'.$link.'"><i class="fas fa-link"></i></a>';
        echo '<form method="post">
        <input style="cursor: pointer;" name="delete" type="submit" value="'.$link.'">
        </form> ';
        echo '</div>';
    }
}else{
    echo ' No images found.';
}