php从名称不在表中的文件夹中删除图像

laik7k3q  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(289)

我试图从一个不在表中的文件夹中删除图像我离解决方案只有一行之遥我不知道如何将查询结果与图像文件夹内容进行比较这就是我所拥有的

$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");

$like = scandir('users/russromei');

 foreach ($like as $thisFile) {

   $rs = mysqli_query($link,"SELECT value FROM ppbv79_listings_media WHERE value like %$thisFile%");
     if($thisFile != "." and $thisFile != ".."){   
       echo $thisFile."<br>";

****NEED TO COMPARE $thisfile with $rs???

   /*  if($thisFile != "." and $thisFile != ".."){   
       unlink ('sfbuyer/' . $thisFile);

}  */

    }
 }
r1zk6ea1

r1zk6ea11#

使用预先准备好的语句,正如@martin所说,您的代码可能容易受到sql注入的攻击。除此之外,下面是一个如何删除数据库中不存在的文件的快速示例。
假设你有下表

------------------------
| ID  |   file         |
------------------------
| 0   |  img1.png      |
| 1   |  img2.png      |
| 3   |  someimage.png |
------------------------

你有一个文件夹( img )包含以下图像:

img1.png, img2.png, someimage.png, random.png

在这里,你有两个选择;一种是获取文件中的每个图像,并检查它是否存在于数据库中,如果不存在,则删除它。
或者您可以从数据库中选择所有图像并删除不存在的图像(这就是我在这里要做的)。

<?php 
 // first put all files into an array 
 $images = scandir('img');

 // create a new empty array that going to hold all files from database 
 $files = [];
 // new we select all files from database 
 // first make your query 
 $query = 'SELECT `file` FROM `myTable`';

 // create mysqli object 
 $mysqli = new Mysqli('localhost','user','password','database');

 // even though this query is not vulnerable to SQL injections
 // I'm going to use a prepared statement 
 $stmt  = $mysqli->prepare($query);
 $stmt->execute();
 $stmt->bind_result($file);
 while($stmt->fetch()){ // insert all files into the array we created earlier
    $files[] = $file;
 }

 $stmt->close();
 $mysqli->close();

 // now you have an array of all files from database and images in folder 
 // we are going to go through each image to check if it exist in the database 
 foreach($images as $img) 
 {
     if(!in_array($img,$files)) {
        // delete file 
        unlink('img/'.$img);
        print("Deleted file [". $img ."]\n");
      } 
 } 
 unset($img);

那就够了。

相关问题