0

我从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";
}

我想知道如何让它在上传时创建一个随机文件名,以便可以多次上传具有相同名称的文件。

4

2 回答 2

2

http://php.net/manual/en/function.tempnam.php

或者

http://php.net/manual/en/function.tmpfile.php

取决于你的需要

于 2013-01-09T17:57:20.337 回答
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()的第二个参数选择新文件名。

于 2013-01-09T17:57:37.713 回答