简体   繁体   English

从给定路径删除文件和文件夹

[英]Deleting files and folder from given path

I have a folder called images, within the folders of the users like: 我在像这样的用户文件夹中有一个名为images的文件夹:

Images 图片

  • user 1 用户1
  • user 2 用户2
  • etc.. 等等..

When i'm deleting a user from the database, i would like to also remove all the files and the folder of that given user. 当我从数据库中删除用户时,我还要删除该给定用户的所有文件和文件夹。 all this is inside a class with functions, but when i'm execute the function my whole folder images get deleted... 所有这些都在具有函数的类中,但是当我执行函数时,我的整个文件夹图像都会被删除...

I already checked if the correct user is selected, if the path is allright. 我已经检查了是否选择了正确的用户,路径是否正确。 while i'm testing it on a test.php file it works well but inside my function it get broke. 虽然我在test.php文件上对其进行了测试,但效果很好,但是在我的函数内部却崩溃了。

if clicked te delete button it go to this function: 如果单击删除按钮,它将转到此功能:

$user = new user();

$id = $_db->mysqli->real_escape_string($_POST['id']);

$query = "SELECT * FROM users WHERE id = '" .$id."'";
$result = $_db->mysqli->query($query);

$userNumb = $result->num_rows;
$finalUserNumb = $userNumb;

if ($finalUserNumb > 0) {
  $user->deleteUser($id);
}

Get the user info by the given id 通过给定的ID获取用户信息

public function userSelsectByID($selector, $id)
{
    $query = "SELECT " .$selector. " FROM users WHERE id ='" .$id."'";
    $result = $this->mysqli->query($query);
    $userInfo = $result->fetch_assoc();

    $itemResult = $userInfo[$selector];
    return $itemResult;
  }

delete files function 删除文件功能

public function delete_files($target)
{
      if(is_dir($target)){
          $files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned

          foreach( $files as $file ){
              $this->delete_files( $file );
              echo "Deleted ".$file." succesfull...</br>";
          }

          rmdir( $target );
      } elseif(is_file($target)) {
          unlink( $target );
      }
  }

delete the user function 删除用户功能

public function deleteUser($id)
{
    $user               = "DELETE FROM users WHERE id = '$id'";
    $userResult         = $this->mysqli->query($user);

    $uren               = "DELETE FROM uren WHERE user_id = '$id'";
    $urenResult         = $this->mysqli->query($uren);

    $cookieLogin        = "DELETE FROM cookieLogin WHERE user_id = '$id'";
    $cookieLoginResult  = $this->mysqli->query($cookieLogin);

    $gebruikersnaam = str_replace(' ', '_', $this->userSelsectByID('gebruikersnaam', $id));
    $this->delete_files('/sites/domain.nl/www/admin/images/'.$gebruikersnaam);
  }

I want that the folder with the username is deleted, but in fact the whole images folder gets deleted... i have tried a lot but nothing works :( 我想删除带有用户名的文件夹,但实际上整个图像文件夹都被删除了……我已经尝试了很多,但没有任何效果:(

Someone that can help me? 有人可以帮助我吗?

I think you have missed a slash before the star 我想你在星星前错过了一个斜线

$files = glob( $target . '/*');

UPDATE UPDATE

Let's do some analysis. 让我们做一些分析。

  1. the username is "test" 用户名是“ test”
  2. you call $this->delete_files('/sites/domain.nl/www/admin/images/test'); 您调用$this->delete_files('/sites/domain.nl/www/admin/images/test');
  3. the target is a directory - so you take a glob('/sites/domain.nl/www/admin/images/test/*') 目标是目录-因此您需要使用glob('/sites/domain.nl/www/admin/images/test/*')
  4. the glob returns an empty array - so you do not delete any files Glob返回一个空数组-因此您不会删除任何文件
  5. then you make rmdir('/sites/domain.nl/www/admin/images/test'); 然后制作rmdir('/sites/domain.nl/www/admin/images/test'); and get out of the function 并退出功能

The only way this can go wrong is if your username is an empty string. 唯一可能出错的方法是,如果您的用户名是一个空字符串。

In your deleteUser function you delete the user prior to selecting their username from the database. deleteUser函数中,先删除用户,然后再从数据库中选择用户名。

I suspect that this causes this->userSelsectByID() to return null , resulting in passing '/sites/domain.nl/www/admin/images/' to $this->delete_files() instead. 我怀疑这会导致this->userSelsectByID()返回null ,从而导致将'/sites/domain.nl/www/admin/images/'传递给$this->delete_files()

You would need to adjust your order of operations, to ensure the username is retrieved before removing it from the database, as well as ensure the username and user's directory exists before passing it to $this->delete_files() . 您需要调整操作顺序,以确保在将用户名从数据库中删除之前已检索到用户名,并确保在将用户名和用户目录传递到$this->delete_files()之前,该用户名和用户目录存在。

public function deleteUser($id)
{
    $gebruikersnaam = str_replace(' ', '_', $this->userSelsectByID('gebruikersnaam', $id));
    $userImagesPath = '/sites/domain.nl/www/admin/images/'.$gebruikersnaam;

    $user               = "DELETE FROM users WHERE id = '$id'";
    $userResult         = $this->mysqli->query($user);

    $uren               = "DELETE FROM uren WHERE user_id = '$id'";
    $urenResult         = $this->mysqli->query($uren);

    $cookieLogin        = "DELETE FROM cookieLogin WHERE user_id = '$id'";
    $cookieLoginResult  = $this->mysqli->query($cookieLogin);

    if (!empty($gebruikersnaam) && is_dir($userImagesPath)) {
        $this->delete_files($userImagesPath);
    }
  }

As an alternative to recursively using glob within a function. 作为在函数内递归使用glob的替代方法。 I recommend using the RecursiveDirectoryIterator instead. 我建议改用RecursiveDirectoryIterator

Which will allow you to retrieve a list of all files and directories in the order they should be deleted: 这样一来,您就可以按照删除顺序检索所有文件和目录的列表:

Given a directory structure of 给定一个目录结构

/home/fyrye/test/images
   - user1
       - 2018-12
           - image1.jpg
           - image2.jpg
       - 2019-01
           - image1.jpg
           - image2.jpg
   - user2
       - 2019-01
           - image1.jpg
           - image2.jpg
       - 2018-12
           - image1.jpg
           - image2.jpg

Then to delete the user1 directory and everything inside of it. 然后删除user1目录及其中的所有内容。

$directory = '/home/fyrye/test/images/user1';

$ri = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS | FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO),
    RecursiveIteratorIterator::CHILD_FIRST
);
/**
 * @var string $path
 * @var \SplFileInfo $splFileInfo
 */
foreach ($ri as $path => $splFileInfo) {
    if ($splFileInfo->isDir()) {
        rmdir($path);
        echo 'deleted directory: ' . $path;
    } elseif ($splFileInfo->isFile()) {
        unlink($path);
        echo 'deleted file: ' . $path;
    }
}
rmdir($directory);
echo 'deleted directory: ' $directory;

Results: 结果:

deleted file: /home/fyrye/test/images/user1/2018-12/image1.jpg
deleted file: /home/fyrye/test/images/user1/2018-12/image2.jpg
deleted directory: /home/fyrye/test/images/user1/2018-12
deleted file: /home/fyrye/test/images/user1/2019-01/image1.jpg
deleted file: /home/fyrye/test/images/user1/2019-01/image2.jpg
deleted directory: /home/fyrye/test/images/user1/2019-01
deleted directory: /home/fyrye/test/images/user1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM