我从http://www.w3schools.com/php/php_file_upload.asp获取了此代码,我正在玩它:
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts)
) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "Invalid file";
}
我想知道如何在上传时创建一个随机文件名,这样可以多次上传同名文件。
答案 0 :(得分:2)
见
http://php.net/manual/en/function.tempnam.php
或
http://php.net/manual/en/function.tmpfile.php
取决于您的需要
答案 1 :(得分:0)
$new_name_here = 'file_' . rand(0, 10000) . '.' . end(explode(".", $_FILES["file"]["name"]));
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $new_name_here);`
move_uploaded_file()的第二个参数选择新文件名。