我正在使用下面的代码片段来获取文件名和扩展名,但是如何重命名文件以便文件名等于bake23 +文件的扩展名。
$variable = 'baKe23';
$filename = $_FILES['filename']['name'];
$ext = $_FILES["filename"]["type"];
重命名文件名是否已存在:
$filename = $_FILES['filename']['name'];
$extension = substr($filename, strpos($filename,'.'),
strlen($filename)-1);
$sql="SELECT filename FROM documents WHERE person_id= '$pid'";
$result=mysql_query($sql);
$query = mysql_query($sql) or die ("Error: ".mysql_error());
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
print("");
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
$existing = $row['filename'];
print("");
}
}
if ( $filename === $existing ) {
$filename = $rnd_id.strrchr($_FILES['filename']['name'], ".");
} else {
$filename = $_FILES['filename']['name'];;
}
答案 0 :(得分:4)
从提交的文件名中获取扩展名并将其添加到您的变量中:
$filename = basename($filename);
$filename = $variable . (string) strrchr($filename, '.');
修改:对于您编辑过的问题,字面上:
$filename = $variable . '.' . $ext;
但是,考虑到我要上传名为banana-smiley.gif
的图片,会发生以下情况:
$filename = 'baKe23.image/gif';
这不是你想要的。你根本不应该依赖$_FILES[*]["type"]
。您需要做的是检查每个上传的文件(确定类型,验证类型,在上传的文件上运行病毒检查程序)。
与此相关的问题是Secure File Upload and validating it和Is it important to verify that the uploaded file is an actual image file?。
答案 1 :(得分:3)
$variable = 'baKe23';
$filename = $_FILES['filename']['name'];
$filename = $variable.strrchr($_FILES['filename']['name'], ".");
或
$variable = 'baKe23';
$filename = $_FILES['filename']['name'];
$filename = $variable.".".pathinfo($filename, PATHINFO_EXTENSION);