随机字符串,用于在上载时重命名文件

时间:2013-01-09 17:55:24

标签: php file-upload

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

我想知道如何在上传时创建一个随机文件名,这样可以多次上传同名文件。

2 个答案:

答案 0 :(得分:2)

答案 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()的第二个参数选择新文件名。