我在重复的名字中遇到了一个小问题。 我想自动重命名任何重复的上传文件,例如编号。
或者如果我可以将名称与数字相同,例如file1.jpg / file2.jpg 对于所有上传的文件
这是我的代码
<?php
include('connect-db.php');
if (isset($_POST['submit'])) {
$filename= $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000))
{
if(file_exists($_FILES["imgfile"]["name"]))
{
echo "File name exists.";
}
else
{
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"photos/$filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo= mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename== '' ) {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
甚至if的回声(file_exists($ _ FILES [“imgfile”] [“name”]))它不起作用,我不知道为什么
在回复之前非常感谢
答案 0 :(得分:1)
试试这段代码
此代码永远不会得到相同名称此代码将重命名文件,如2jh5425h44u5h45h454k5image.jpg
这就是它将如何保存文件所以无需担心重复文件
我添加了随机名称生成器$newname = md5(rand() * time());
,这将为您的文件生成随机名称
<?php
include('connect-db.php');
$newname = md5(rand() * time());
if (isset($_POST['submit'])) {
$filename = $_FILES["imgfile"]["name"];
if ((($_FILES["imgfile"]["type"] == "image/gif") || ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png") || ($_FILES["imgfile"]["type"] == "image/pjpeg")) && ($_FILES["imgfile"]["size"] < 20000000)) {
if (file_exists($_FILES["imgfile"]["name"])) {
echo "File name exists.";
} else {
move_uploaded_file($_FILES["imgfile"]["tmp_name"], "photos/$newname . $filename");
}
}
if (is_numeric($_POST['id'])) {
$id = $_POST['id'];
$id_photo = mysql_real_escape_string(htmlspecialchars($_POST['filename']));
// check that firstname/lastname fields are both filled in
if ($filename == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
} else {
// save the data to the database
mysql_query("UPDATE table SET id_photo='$filename' WHERE id='$id' ") or die(mysql_error());
// once saved, redirect back to the view page
echo("<meta http-equiv='refresh' content='0'>"); //Refresh by HTTP META
}
} else {
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
?>
如果您只需要在文件重复时重命名,请回答Renaming duplicate files in a folder with php