dongtan8979 2019-01-25 15:50
浏览 125
已采纳

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

I have a folder called images, within the folders of the users like:

Images

  • user 1
  • user 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.

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

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?

  • 写回答

2条回答 默认 最新

  • dongpanshi2839 2019-01-27 16:50
    关注

    In your deleteUser function you delete the user prior to selecting their username from the database.

    I suspect that this causes this->userSelsectByID() to return null, resulting in passing '/sites/domain.nl/www/admin/images/' to $this->delete_files() instead.

    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().

    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. I recommend using the RecursiveDirectoryIterator instead.

    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.

    $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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable