[英]how to rename uploaded files if there's duplicated names
我在重复的名字中有一个小问题。 我想自动重命名所有重复的上传文件,例如给它们编号。
或者如果我可以使名称与数字相同,例如所有上传文件的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”])))也不起作用,我也不知道为什么
非常感谢,然后再回复
尝试此代码, 此代码将永远不会获得相同的名称,此代码将重命名文件,如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!';
}
}
?>
如果仅在文件重复的情况下需要重命名,请使用php重命名文件夹中的重复文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.