php - 更新和取消链接旧图像 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!";
}
}
解决方案
所以我在 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!";
}
}
推荐阅读
- c++ - 如何在特定位置推回没有大小的向量?
- servicenow - SERVICENOW - 使用查询结果填充字段
- reactjs - Jest - 模拟函数,从另一个文件导入
- javascript - 赛普拉斯断言 .should() 失败
- java - 以编程方式使用以下 java 代码创建附加程序,我需要使用我的 partternLayout 添加 MDC
- python - 如何在python中换行?
- python - 被杀死的子进程没有标准输出
- react-native - 在 React-Native 中拍照时使用 RNcamera 设置曝光量?
- javascript - Javascript在两个div中获取选择值
- python - 如何提取具有两个文件扩展名的文件名?