【发布时间】: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(); }`