我是新的PHP,这是学习过程。
我有一个html上传表单。我正在尝试重命名上传的文件。所以以下是获取文件扩展名的php代码,之后我添加了一个php uniqid();重命名它。
获取文件扩展名代码:
$img = $_FILES['images']['name'];
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$extension = getExtension($img);
$id = uniqid();
$newimg = $id.'.'.$extension;
嗯,这对我来说只有一个上传文件,但是,如果我有多个上传表单,那么如何通过此功能获得多个文件扩展?
获取以下多个文件是我的PHP代码:
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/uploaded/'; //set upload directory
for ($i = 0; $i < count($_FILES['images']['name']); $i++)
{
$number_of_file_fields++;
if ($_FILES['images']['name'][$i] != '')
{ //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['images']['name'][$i];
if (move_uploaded_file($_FILES['images']['tmp_name'][$i], $upload_directory . $_FILES['images']['name'][$i]))
{
$number_of_moved_files++;
}
}
}
Html表格
<table width="1020" border="0" cellspacing="7" cellpadding="0">
<tr>
<td valign="top" width="250">
Upload your property picture
</td>
<td>
<div id="file_container">
<input name="images[]" type="file" class="tr2" />
<br />
</div>
<a href="javascript:void(0);" onClick="add_file_field();">Add another</a>
<input type="submit" value="Save & Continue" name="Submit" class="submit" />
</td>
</tr>
</table>
答案 0 :(得分:1)
function changeFilename($str)
{
$pathinfo = pathinfo($str);
return uniqid() . "." . $pathinfo['extension'];
}
$oldarray = array("hello.txt","ytuwe.php");
$newarray = array_map("changeFilename", $oldarray);
var_dump($newarray);
以下是演示:http://ideone.com/gPi61D
答案 1 :(得分:0)
为什么不使用PHP的pathinfo函数来获取文件扩展名?
$extension = pathinfo($img, PATHINFO_EXTENSION);
$id = uniqid();
$newimg = $id.'.'.$extension;