为上传的图像创建唯一id



如何使用此代码为上传的文件创建唯一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;

您可以使用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;

相关内容

  • 没有找到相关文章

最新更新