|
$ext = pathinfo($_FILES[&#39;file&#39;][&#39;name&#39;]); // 依据pid生成的盐 if(getmypid()!=false){ $pid_salt = getmypid() . substr(md5(mt_rand()),-3); }else{ $pid_salt = &#39;&#39;; } $filepath = sprintf(&#39;Fold/%s%s.%s&#39;, uniqid(mt_rand()), $pid_salt, $ext[&#39;extension&#39;]); // file_exists --> 递归函数检测(抵抗时钟回拨问题),最终返回一个不存在的文件。 // 考虑多进程问题 --> 增加pid_salt盐 $filepath = check_file($filepath); if (!move_uploaded_file( $_FILES[&#39;file&#39;][&#39;tmp_name&#39;], $filepath )) { throw new RuntimeException(&#39;Failed to move uploaded file.&#39;); } /*检测文件是否存在<-->递归函数*/ function check_file($filepath){ if(file_exists($filepath)){ // echo $file.&#39; 存在!&#39;; $ext = pathinfo($filepath); $filepath = sprintf(&#39;File_Stor_Fold/%s_%s.%s&#39;, uniqid(),mt_rand(), $ext[&#39;extension&#39;]); check_file($filepath); }else{ // echo $file.&#39; 不存在!&#39;; return $filepath; } }
上传到临时文件那里是 操作系统mk函数保障的线程安全Thread Safe 的;但不能确保生成的文件名(move file)环节的唯一性,因此使用如上的机制来消除重复。
其实微服务环境下, 应该使用 单进程模型,来处理文件上传服务, 做排队。 |
|