我使用以下代码将图像集上传到服务器,我在上传时重命名文件,但是当我尝试上传多个文件时,它会自动替换文件,而我需要将其他文件命名为在文件名的末尾加上2,3,4等。
<input type="file" name="upl" />
<input type="submit" value="submit" />
$_SESSION['imgrand']
是生成并通过会话传递的随机字符串。
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['upl']['name']) ;
$ran = $_SESSION['imgrand'];
$ran2 = $ran.".";
$target = "uploads/";
$target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['upl']['tmp_name'], $target))
{
echo "The file has been upl as ".$ran2.$ext;
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
例如,如果随机字符串是jahkhakshdkjshdjksahds,我需要将图像命名为jahkhakshdkjshdjksahds1.ext,jahkhakshdkjshdjksahds2.ext,jahkhakshdkjshdjksahds3.ext,jahkhakshdkjshdjksahds4.ext,jahkhakshdkjshdjksahds5.ext同样?
答案 0 :(得分:1)
在覆盖之前测试现有文件。
...
$ext = findexts ($_FILES['upl']['name']) ;
$ran = $_SESSION['imgrand'];
$target = "uploads/".$ran;
for($i=1;$i < 100;$i++) {
$filename = $target.$i.".".$ext;
if (file_exists($filename)) {
continue;
} else {
if(move_uploaded_file($_FILES['upl']['tmp_name'], $filename))
{
echo "The file has been upl as : ".$filename;
break;
}
else
{
echo "Sorry, there was a problem uploading your file: ".$filename;
break;
}
} // not file_ex
} // for
...