在codeigniter中将上传的每个文件的用户文件上传到随机生成的路径

时间:2016-06-20 07:26:45

标签: php codeigniter

我试图将用户文件放到必须为每个上传的文件生成的目录中。如何通过编辑配置文件中的upload_path直接执行此操作。

以下是我的config / upload.php的样子:     

    $config=array('upload_path' => './uploads/','allowed_types' => 'jpg|png|gif|doc|xml|zip|pdf|ppt
        docx|txt|mp4|m3u8|ts|3gp|mov|avi|wmv|mp3|aif|aifc|aiff|aac|m4a|mp1|mp2|mpeg|wav|ogg',
        'max_size' => '102400','detect_mime'=>TRUE);
?>

我希望以下函数的输出是随机目录名:

    public function crypto_rand_secure($min, $max)
{
     $range = $max - $min;
     if ($range < 1) return $min; // not so random...
     $log = ceil(log($range, 2));
     $bytes = (int) ($log / 8) + 1; // length in bytes
     $bits = (int) $log + 1; // length in bits
    $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
    do 
    {
          $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
         $rnd = $rnd & $filter; // discard irrelevant bits
    }
     while ($rnd >= $range);
    return $min + $rnd;
}

public function getRandom($length)
{
    $token = "";
     $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
     $codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
     $codeAlphabet.= "0123456789";
     $max = strlen($codeAlphabet) - 1;
     for ($i=0; $i < $length; $i++) 
     {
         $token .= $codeAlphabet[$this->crypto_rand_secure(0, $max)];
    }
    return $token;
}
public $random='./uploads/'.$this->getRandom(32);
mkdir($random);

如何将这个随机目录传递到config / upload.php文件中的upload_path?

或者如何编辑config / upload.php到

$config=array('upload_path' => *random_value_here*,'allowed_types' => 'jpg|png|gif|doc|xml|zip|pdf|ppt
        docx|txt|mp4|m3u8|ts|3gp|mov|avi|wmv|mp3|aif|aifc|aiff|aac|m4a|mp1|mp2|mpeg|wav|ogg',
        'max_size' => '102400','detect_mime'=>TRUE);

这样它应该从某个地方获取随机值而不会导致重复的对象生成(即重复的目录生成)

1 个答案:

答案 0 :(得分:1)

你是如此多的允许文件扩展名。整理您的文件和随机生成的子目录路径。

if(isset($_FILES['File'])){
   $Ext = end((explode(".", $_FILES['File']["name"])));
   $UploadPath = 'uploads/'.$Ext.'/'.rand(1, 1000).'/'; 

   if(!is_dir($upload_path)) {
       mkdir(FCPATH.$UploadPath, 0777, TRUE);
       chmod(FCPATH.$UploadPath, 0777);
   }
   $UploadPath = FCPATH.$UploadPath;
   // And encrypt your file name
   $config = ['upload_path'=>$UploadPath,'allowed_types'=>'jpg|png|gif|doc|xml|zip|pdf|ppt|docx|txt|mp4|m3u8|ts|3gp|mov|avi|wmv|mp3|aif|aifc|aiff|aac|m4a|mp1|mp2|mpeg|wav|ogg','encrypt_name'=>true]
}