首页 > 解决方案 > 更新和取消链接旧图像 PHP 的问题

问题描述

所以问题是我创建了两种方法来设置文件并检查图像是否在 tmp 中有图像,它应该在移动新图像之前删除旧图像。但是当我上传图片时,unlink 给出了这样的错误unlink(\Users\Murat\Desktop\xampp\htdocs\new\usersimages\42\1593769114256123131.jpg): No such file or directory in this number属于我上传的不是旧图像。

它将新图像移动到文件夹并尝试删除新图像但不删除旧图像。这是主要问题。可能我做错了,但找不到在哪里。代码如下。

public function set_file($file){
            $this->image = basename($file['name']);
            $this->tmp_path = $file['tmp_name'];
            $this->type     = $file['type'];
            $this->size     = $file['size'];
            $this->image = preg_replace('#[^a-z.0-9]#i', '', $this->image);
            $kaboom = explode(".", $this->image); // Split file name into an array using the dot
            $fileExt = end($kaboom); // Now target the last array element to get the file extension
            $this->image = time().rand().".".$fileExt;

    }

public function checkPhoto($user_id){
        global $database;

    if(!empty($this->tmp_path)) {
        $path = $this->upload_directory.$user_id.DS.$this->image; 
        unlink($path);
        move_uploaded_file($this->tmp_path, 
        $path);
        // unlink("album_uploads/$this->image");
    } elseif (empty($this->tmp_path)) {
        $sql = "SELECT * FROM users WHERE user_id = :user_id ";
        $query =$database->query($sql, [':user_id'=>$user_id]);
        $row = $query->fetch();
        $this->image = $row['image'];
        $this->type = $row['type'];
        $this->size = $row['size'];
    } else {
        $this->errors[] = "Unexpected error please try again after refresh the page!";
    }
} 

标签: phpimagefileupload

解决方案


所以我在 checkphoto 方法中添加了这部分,它现在可以工作了。如果我做错了,请告诉我谁能有更多的知识。

public function checkPhoto($user_id){
    global $database;
        $sql = "SELECT * FROM users WHERE user_id = :user_id ";
        $query =$database->query($sql, [':user_id'=>$user_id]);
        $row = $query->fetch();

        $path = $this->upload_directory.$user_id.DS; 
        
    if(!empty($this->tmp_path)) {
        $this->image = $row['image'];
        if (file_exists($this->image)) {
            unlink($path.$this->image);
        }
        // unlink("album_uploads/$this->image");
    } elseif (empty($this->tmp_path)) {   
        $this->image = $row['image'];
        $this->type = $row['type'];
        $this->size = $row['size'];
    } else {
        $this->errors[] = "Unexpected error please try again after refresh the page!";
    }
} 

推荐阅读