如果我上传一个同名的图片,我的代码可以在我的位置重新命名它,但是当它从数据库中取出时,重复的图片会被破坏。我重命名和存储图像的代码是:
插入\u image.php
$image = $_FILES['image'];
$name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
$newname = $name;
//print_r($_FILES);
$location = realpath(dirname(__FILE__)).'/images/'.basename($name);
$image_path = realpath(dirname(__FILE__)).'/images/';
$extention = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if(file_exists($location)){
$increment = 0;
list($name, $extention) = explode('.', $location);
while(file_exists($location)) {
$increment++;
$location = $name. $increment . '.' . $extention;
//print_r($location);
$newname = $name. $increment . '.' . $extention;
}
}
mysqli_query($dbc, "INSERT INTO post(username, post, image) VALUES('$uname', '$post', '$newname')");
if(isset($newname)){
if(move_uploaded_file($_FILES['image']['tmp_name'], $location) && is_writable($location)){
//echo 'File uploaded successfully';
}
else{
//echo "Failed to move...";
}
}
任何更好的建议都会很有帮助。
1条答案
按热度按时间wvt8vs2t1#
在
location
变量(在while循环中)只存储文件名。您还需要完整路径。更改代码如下