如何使用此代码为上传的文件创建唯一ID。
代码上传图片,但是当您使用iPhone上传图片时,所有图片都会显示为image.jpg。所以我需要一个函数来重命名现有文件,或者只为每个文件创建唯一的id。
<form enctype="multipart/form-data" action="" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form>
<?php
function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; }
$ext = findexts ($_FILES['uploaded']['name']) ;
$ran = rand () ;
$ran2 = $ran.".";
$target = "uploads/";
if(file_exists("uploads/$filename")) unlink("uploads/$filename");move_uploaded_file($target, "uploads/$filename");
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; }
$target = $target . $ran2.$ext;
答案 0 :(得分:0)
您可以将uniqid()
功能用于唯一的图像名称。它有两个参数。第一:前缀,第二:更多熵。
请在此处查看详细信息:http://php.net/manual/en/function.uniqid.php
<form enctype="multipart/form-data" action="" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form>
<?php
function findexts ($filename) {
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n]; return $exts;
}
$ext = findexts ($_FILES['uploaded']['name']) ;
//unique image
$new_image_name = uniqid("IMG_",false);
$final_name = $new_image_name.".".$ext;
//Target directory
$target = "uploads/";
if(file_exists("uploads/$final_name")) unlink("uploads/$final_name");move_uploaded_file($target,"uploads/$final_name");
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$final_name; } else { echo "Sorry, there was a problem uploading your file."; }
$target = $target . $final_name;