upload.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. require_once 'conn.php';
  3. checkLogin();
  4. /**
  5. * File upload handler for PHP 8
  6. * @author Original ASP version by Yanis.Wang<yanis.wang@gmail.com>
  7. * @version 1.0.0
  8. */
  9. // Configuration
  10. $inputName = 'filedata'; // Form file field name
  11. $attachDir = 'system/u'; // Upload directory path
  12. $dirType = 2; // 1: by day, 2: by month, 3: by extension
  13. $maxAttachSize = 5242880; // Max file size (5MB)
  14. $allowedExt = ['txt', 'rar', 'zip', 'jpg', 'jpeg', 'gif', 'png', 'swf', 'wmv', 'avi', 'wma', 'mp3', 'mid', 'pdf'];
  15. $msgType = 2; // Return format: 1 = only URL, 2 = parameter array
  16. $immediate = $_GET['immediate'] ?? '0';
  17. $err = '';
  18. $msg = "''";
  19. // Check if file was uploaded
  20. if (!isset($_FILES[$inputName])) {
  21. $err = "无数据提交";
  22. } else {
  23. $file = $_FILES[$inputName];
  24. // Check file size
  25. if ($file['size'] > $maxAttachSize) {
  26. $err = "文件大小超过 " . $maxAttachSize . "字节";
  27. } else {
  28. // Get file extension
  29. $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
  30. // Check if extension is allowed
  31. if (!in_array($extension, $allowedExt)) {
  32. $err = "上传文件扩展名必需为:" . implode(',', $allowedExt);
  33. } else {
  34. // Create subdirectory based on dirType
  35. switch ($dirType) {
  36. case 1:
  37. $attachSubdir = "day_" . date('ymd');
  38. break;
  39. case 2:
  40. $attachSubdir = "m" . date('ym');
  41. break;
  42. case 3:
  43. $attachSubdir = "ext_" . $extension;
  44. break;
  45. }
  46. $attachPath = $attachDir . '/' . $attachSubdir;
  47. // Create directory if it doesn't exist
  48. if (!file_exists($attachPath)) {
  49. mkdir($attachPath, 0777, true);
  50. }
  51. // Generate random filename
  52. $filename = date('dHis') . rand(10000, 99999) . '.' . $extension;
  53. $target = $attachPath . '/' . $filename;
  54. // Move uploaded file
  55. if (move_uploaded_file($file['tmp_name'], $target)) {
  56. $imgurl = $target;
  57. $target = str_replace('\\', '/', $target);
  58. if ($immediate == "1") {
  59. $target = "!" . $target;
  60. }
  61. if ($msgType == 1) {
  62. $msg = "'" . $target . "'";
  63. } else {
  64. $msg = "{
  65. 'url': '/" . $target . "',
  66. 'localname': '" . addslashes($file['name']) . "',
  67. 'id': '1'
  68. }";
  69. }
  70. } else {
  71. $err = "文件上传失败";
  72. }
  73. }
  74. }
  75. }
  76. // Output response
  77. if (isset($_GET['act']) && $_GET['act'] == 's') {
  78. echo "<script>parent.document.getElementById('infoimgurl').value='/system/" . $imgurl . "';location.href='uploadfile.php'</script>";
  79. } else {
  80. echo "{'err':'" . addslashes($err) . "','msg':" . $msg . "}";
  81. }