上传具有唯一名称的图片

时间:2015-01-11 14:48:18

标签: php html file-upload

所以我尝试使用下面的脚本将一些图像上传到我服务器上的文件夹中,但它会将每个图像保存为" image.jpg"如果我尝试上传多个,它会覆盖最后上传的图像。如你所见,我评论了检查文件是否已存在的部分让我上传文件并覆盖最新的文件。帮助!我需要修改一些内容随机化名称或获取原始图像名称。

<?php
$target_dir = "wp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
/*if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}*/
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "png" && $imageFileType != "jpg") {
    echo "Sorry, only PNG and JPG files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

2 个答案:

答案 0 :(得分:1)

获取唯一文件名的一种简单方法是以毫秒为单位获取当前的Unix时间并将其附加(或预先添加)到文件名。要使用的命令是microtime()

例如:

$target_file = $target_dir . microtime() . basename($_FILES["fileToUpload"]["name"]);

您还可以尝试对文件进行哈希处理,以获得具有较低碰撞概率的唯一哈希值,但这样更快,效果更好。

答案 1 :(得分:1)

您可以实施类似Windows的自动文件重命名:

$try = 1;
while($file_exists($target_file)) {
    $target_file = preg_replace('/(\(\\d+\))*(\.[^\\(\\)]+)$/',
        "({$try})\\2", $target_file);
    $try++;
}

这将取代文件&#34; duplicate.jpg&#34;使用&#34;复制(1).jpg&#34;,然后&#34;复制(2).jpg&#34;,依此类推。

仍然不太可能出现竞争条件,就像使用uniqid()microtime()一样(冲突方面,两者都更好)。

否则,请始终使用tempnam()。您可以查看this answer