file_upload.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. class FileUpload
  3. {
  4. static public function recursive_makedir($path)
  5. {
  6. return is_dir($path) or (self::recursive_makedir(dirname($path)) and @mkdir($path));
  7. }
  8. static private function clean_up($file, $result)
  9. {
  10. @unlink($file);
  11. return $result;
  12. }
  13. static public function upload($img_savedir, $is_img = true, $overwrite = false)
  14. {
  15. $tmppath = $_POST["file_path"];
  16. $sha1 = $_POST["file_sha1"];
  17. $file_name = $_POST["file_name"];
  18. $result = array();
  19. $result["ret"] = false;
  20. $result["file"] = "";
  21. if (!isset($tmppath) || empty($tmppath)) {
  22. return self::clean_up($tmppath, $result);
  23. }
  24. if (!isset($sha1) || empty($sha1)) {
  25. return self::clean_up($tmppath, $result);
  26. }
  27. if (!isset($file_name) || empty($file_name)) {
  28. return self::clean_up($tmppath, $result);
  29. }
  30. if ($is_img) {
  31. $ext_name = strtolower(pathinfo($file_name)['extension']);
  32. if (!($ext_name == 'jpg' || $ext_name == 'jpeg' || $ext_name == 'png' || $ext_name == 'gif' || $ext_name == 'bmp')) {
  33. return self::clean_up($tmppath, $result);
  34. }
  35. }
  36. if (!isset($img_savedir)) {
  37. return self::clean_up($tmppath, $result);
  38. }
  39. $timestamp = date("YmdHis", time());
  40. $dest_file = $img_savedir . "/" . substr($timestamp, 0, 4) . "/" . substr($sha1, 0, 2) . "/" . $sha1 . '.' . $ext_name;
  41. if (!self::recursive_makedir(dirname($dest_file))) {
  42. return self::clean_up($tmppath, $result);
  43. }
  44. if (!$overwrite) {
  45. if (!file_exists($dest_file)) {
  46. if (!copy($tmppath, $dest_file)) {
  47. return self::clean_up($tmppath, $result);
  48. }
  49. }
  50. } else {
  51. if (!copy($tmppath, $dest_file)) {
  52. return self::clean_up($tmppath, $result);
  53. }
  54. }
  55. $result["ret"] = true;
  56. $result["file"] = $dest_file;
  57. return self::clean_up($tmppath, $result);
  58. }
  59. }
  60. ?>