file_upload.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. class FileUpload
  3. {
  4. const upload_store_path = BASE_ROOT_PATH . '/data/upload/uploadtmp';
  5. static private function recursive_makedir($path)
  6. {
  7. return is_dir($path) or (self::recursive_makedir(dirname($path)) and @mkdir($path));
  8. }
  9. static private function get_random_string($length) {
  10. $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  11. $max = strlen($strPol)-1;
  12. $str = '';
  13. for($i=0; $i < $length; $i++) {
  14. $str.=$strPol[rand(0,$max)];
  15. }
  16. return $str;
  17. }
  18. static private function upload_normal($src_file,$dest_dir,&$file_path)
  19. {
  20. if(!file_exists($src_file)) {
  21. return false;
  22. }
  23. $file_name = strtolower(pathinfo($src_file)['basename']);
  24. return self::do_upload($src_file,$file_name,$dest_dir,$file_path);
  25. }
  26. static public function upload_avatar(&$file_path)
  27. {
  28. return self::upload_nginx(BASE_AVATAR_PATH,$_SESSION['member_id'],$file_path);
  29. }
  30. static private function upload_nginx($dest_dir,$member_id,&$file_path)
  31. {
  32. $tmppath = $_POST["file_path"];
  33. $file_name = $_POST["src_name"];
  34. return self::do_upload($tmppath,$file_name,$dest_dir,$member_id,$file_path);
  35. }
  36. static private function do_upload($src_path,$file_name,$dest_dir,$member_id,&$file_path)
  37. {
  38. if (!isset($src_path) || empty($src_path)) {
  39. return false;
  40. }
  41. $src_path = self::upload_store_path . $src_path;
  42. if(!file_exists($src_path)) {
  43. return false;
  44. }
  45. if (!isset($dest_dir) || empty($dest_dir)) {
  46. @unlink($src_path);
  47. return false;
  48. }
  49. if (!isset($member_id) || empty($member_id)) {
  50. @unlink($src_path);
  51. return false;
  52. }
  53. $ext_name = strtolower(pathinfo($file_name)['extension']);
  54. $dest_fn = strval($member_id) . self::get_random_string(10) . '.' . $ext_name;
  55. $dest_file = $dest_dir . "/" . sprintf("%03d", intval(intval($member_id) / 2000)) . "/" . $dest_fn;
  56. if (!self::recursive_makedir(dirname($dest_file))) {
  57. @unlink($src_path);
  58. return false;
  59. }
  60. if (!copy($src_path, $dest_file)) {
  61. @unlink($src_path);
  62. return false;
  63. } else {
  64. $file_path = $dest_file;
  65. return true;
  66. }
  67. }
  68. }
  69. ?>