【问题标题】:Problem with updating and unlinking old image PHP更新和取消链接旧图像 PHP 的问题
【发布时间】:2020-10-24 00:37:11
【问题描述】:

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

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

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!";
    }
} 

【问题讨论】:

  • 如果您使用move_uploaded_file,您将无法取消链接同一个文件,因为您移动了该文件。
  • 我正在尝试取消链接旧的。不是同一个文件
  • 我没有立即看到问题,但总是使用file_exist() 检查文件是否存在于服务器上,然后取消链接。始终进行检查以确保用户永远不会看到任何这些消息
  • 我是这样解决的 ` if($_FILES['filename']['name']!='') { $albumclass->remove_image(); }`

标签: php image file upload


【解决方案1】:

所以我在 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!";
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多