我遇到以下问题。我写了这段代码:
$imagesDir = '../gender/male/';
$imagesDir2 = '../uploads/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
$profile_picture = $randomImage;
使用查询后,完整路径将插入到数据库表中。
查询后,我编写了以下代码:
$select = $db->query("SELECT * FROM users WHERE email='".$email."'");
$select = $select->fetch_object();
if(!empty($select->profile_picture)){
chmod($randomImage, 0777);
chmod($imagesDir2, 0777);
$new_name = pathinfo($randomImage);
copy($randomImage,$imagesDir2.$new_name['basename']);
$new_file = md5(mt_rand()).$new_name['basename'];
chmod ($imagesDir2.$new_name['basename'], 0777);
rename($imagesDir2.$new_name['basename'],$imagesDir2.$new_file);
chmod('../gender/male/' . $new_name['basename'], 0777);
unlink('../gender/male/' . $new_name['basename']);
$db->query("UPDATE users SET profile_picture='".$new_file."' WHERE email='".$email."'");
}
我就是无法让它工作。我想要它做什么,
- 将图片复制到上传文件夹
- 在图片名称前使用 md5(mt_rand()) 重命名上传文件夹中的图片(例如 md5(mt_rand())1.jpg)
- 在数据库中更新此内容
- 取消链接/销毁“../gender/male/”文件夹中的原始文件
唯一不起作用的是取消链接。文件仍在文件夹中。
我希望有人能帮助我解决这个问题。对于所有竭尽全力提供帮助的人,我要预先感谢你们。
最佳答案
首先,我要感谢自己提供的所有帮助。其次,对于所有遇到类似问题的 future 读者。我将 if 语句更改为:
if(!empty($select->profile_picture)){
chmod($imagesDir2, 0777);
$new_name = pathinfo($randomImage);
copy($randomImage,$imagesDir2.$new_name['basename']);
$new_file = md5(mt_rand()).$new_name['basename'];
chmod ($imagesDir2.$new_name['basename'], 0777);
rename($imagesDir2.$new_name['basename'],$imagesDir2.$new_file);
chmod($imagesDir.$new_name['basename'], 0777);
unlink($imagesDir.$new_name['basename']);
$db->query("UPDATE users SET profile_picture='".$new_file."' WHERE email='".$email."'");
}
它有效。确保您具有正确的权限设置。希望能帮助您解决问题。
关于php - 将图像复制到另一个文件夹并重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37195871/