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 分析下图所示同步时序逻辑电路的逻辑功能。
  • ¥15 halcon联合c#遇到了问题不能解决
  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集