Uploader.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. /**
  3. * Simple Ajax Uploader
  4. * Version 2.6.2
  5. * https://github.com/LPology/Simple-Ajax-Uploader
  6. *
  7. * Copyright 2012-2017 LPology, LLC
  8. * Released under the MIT license
  9. *
  10. * View the documentation for an example of how to use this class.
  11. */
  12. class FileUpload {
  13. private $fileName; // Filename of the uploaded file
  14. private $fileSize; // Size of uploaded file in bytes
  15. private $fileExtension; // File extension of uploaded file
  16. private $fileNameWithoutExt;
  17. private $savedFile; // Path to newly uploaded file (after upload completed)
  18. private $errorMsg; // Error message if handleUpload() returns false (use getErrorMsg() to retrieve)
  19. private $isXhr;
  20. public $uploadDir; // File upload directory (include trailing slash)
  21. public $allowedExtensions; // Array of permitted file extensions
  22. public $sizeLimit = 10485760; // Max file upload size in bytes (default 10MB)
  23. public $newFileName; // Optionally save uploaded files with a new name by setting this
  24. public $corsInputName = 'XHR_CORS_TARGETORIGIN';
  25. public $uploadName = 'uploadfile';
  26. function __construct($uploadName = null) {
  27. if ($uploadName !== null) {
  28. $this->uploadName = $uploadName;
  29. }
  30. if (isset($_FILES[$this->uploadName])) {
  31. $this->isXhr = false;
  32. if ($_FILES[$this->uploadName]['error'] === UPLOAD_ERR_OK) {
  33. $this->fileName = $_FILES[$this->uploadName]['name'];
  34. $this->fileSize = $_FILES[$this->uploadName]['size'];
  35. } else {
  36. $this->setErrorMsg($this->errorCodeToMsg($_FILES[$this->uploadName]['error']));
  37. }
  38. } elseif (isset($_SERVER['HTTP_X_FILE_NAME']) || isset($_GET[$this->uploadName])) {
  39. $this->isXhr = true;
  40. $this->fileName = isset($_SERVER['HTTP_X_FILE_NAME']) ?
  41. $_SERVER['HTTP_X_FILE_NAME'] : $_GET[$this->uploadName];
  42. if (isset($_SERVER['CONTENT_LENGTH'])) {
  43. $this->fileSize = (int)$_SERVER['CONTENT_LENGTH'];
  44. } else {
  45. throw new Exception('Content length is empty.');
  46. }
  47. }
  48. if ($this->fileName) {
  49. $this->fileName = $this->sanitizeFilename($this->fileName);
  50. //弃用原生pathinfo(),原因在低版本的php环境下无法正确读取文件名称。
  51. //$pathinfo = pathinfo($this->fileName);
  52. $pathinfo = $this->mb_pathinfo($this->fileName);
  53. if (isset($pathinfo['extension']) &&
  54. isset($pathinfo['filename']))
  55. {
  56. $this->fileExtension = strtolower($pathinfo['extension']);
  57. $this->fileNameWithoutExt = $pathinfo['filename'];
  58. }
  59. }
  60. }
  61. private function sanitizeFilename($name) {
  62. $name = trim($this->basename(stripslashes($name)), ".\x00..\x20");
  63. // Use timestamp for empty filenames
  64. if (!$name) {
  65. $name = str_replace('.', '-', microtime(true));
  66. }
  67. return $name;
  68. }
  69. private function basename($filepath, $suffix = null) {
  70. $splited = preg_split('/\//', rtrim($filepath, '/ '));
  71. return substr(basename('X'.$splited[count($splited)-1], $suffix), 1);
  72. }
  73. private function mb_pathinfo($filepath) {
  74. preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im',$filepath,$m);
  75. if($m[1]) $ret['dirname']=$m[1];
  76. if($m[2]) $ret['basename']=$m[2];
  77. if($m[5]) $ret['extension']=$m[5];
  78. if($m[3]) $ret['filename']=$m[3];
  79. return $ret;
  80. }
  81. public function getFileName() {
  82. return $this->fileName;
  83. }
  84. public function getFileSize() {
  85. return $this->fileSize;
  86. }
  87. public function getFileNameWithoutExt() {
  88. return $this->fileNameWithoutExt;
  89. }
  90. public function getExtension() {
  91. return $this->fileExtension;
  92. }
  93. public function getErrorMsg() {
  94. return $this->errorMsg;
  95. }
  96. public function getSavedFile() {
  97. return $this->savedFile;
  98. }
  99. private function errorCodeToMsg($code) {
  100. switch($code) {
  101. case UPLOAD_ERR_INI_SIZE:
  102. $message = '文件大小超出限制。';
  103. break;
  104. case UPLOAD_ERR_PARTIAL:
  105. $message = '上传的文件只是部分上传。';
  106. break;
  107. case UPLOAD_ERR_NO_FILE:
  108. $message = '没有上传文件。';
  109. break;
  110. case UPLOAD_ERR_NO_TMP_DIR:
  111. $message = '缺少临时文件夹。';
  112. break;
  113. case UPLOAD_ERR_CANT_WRITE:
  114. $message = '无法将文件写入磁盘。';
  115. break;
  116. case UPLOAD_ERR_EXTENSION:
  117. $message = '通过扩展停止文件上传。';
  118. break;
  119. default:
  120. $message = '未知上传错误。';
  121. break;
  122. }
  123. return $message;
  124. }
  125. private function checkExtension($ext, $allowedExtensions) {
  126. if (!is_array($allowedExtensions))
  127. return false;
  128. if (!in_array(strtolower($ext), array_map('strtolower', $allowedExtensions)))
  129. return false;
  130. return true;
  131. }
  132. private function setErrorMsg($msg) {
  133. if (empty($this->errorMsg))
  134. $this->errorMsg = $msg;
  135. }
  136. private function fixDir($dir) {
  137. if (empty($dir))
  138. return $dir;
  139. $slash = DIRECTORY_SEPARATOR;
  140. $dir = str_replace('/', $slash, $dir);
  141. $dir = str_replace('\\', $slash, $dir);
  142. return substr($dir, -1) == $slash ? $dir : $dir . $slash;
  143. }
  144. // escapeJS and jsMatcher are adapted from the Escaper component of
  145. // Zend Framework, Copyright (c) 2005-2013, Zend Technologies USA, Inc.
  146. // https://github.com/zendframework/zf2/tree/master/library/Zend/Escaper
  147. private function escapeJS($string) {
  148. return preg_replace_callback('/[^a-z0-9,\._]/iSu', $this->jsMatcher, $string);
  149. }
  150. private function jsMatcher($matches) {
  151. $chr = $matches[0];
  152. if (strlen($chr) == 1)
  153. return sprintf('\\x%02X', ord($chr));
  154. if (function_exists('iconv'))
  155. $chr = iconv('UTF-16BE', 'UTF-8', $chr);
  156. elseif (function_exists('mb_convert_encoding'))
  157. $chr = mb_convert_encoding($chr, 'UTF-8', 'UTF-16BE');
  158. return sprintf('\\u%04s', strtoupper(bin2hex($chr)));
  159. }
  160. public function corsResponse($data) {
  161. if (isset($_REQUEST[$this->corsInputName])) {
  162. $targetOrigin = $this->escapeJS($_REQUEST[$this->corsInputName]);
  163. $targetOrigin = htmlspecialchars($targetOrigin, ENT_QUOTES, 'UTF-8');
  164. return "<script>window.parent.postMessage('$data','$targetOrigin');</script>";
  165. }
  166. return $data;
  167. }
  168. public function getMimeType($path) {
  169. $finfo = new finfo(FILEINFO_MIME_TYPE);
  170. $fileContents = file_get_contents($path);
  171. $mime = $finfo->buffer($fileContents);
  172. $fileContents = null;
  173. return $mime;
  174. }
  175. public function isWebImage($path) {
  176. $pathinfo = pathinfo($path);
  177. if (isset($pathinfo['extension'])) {
  178. if (!in_array(strtolower($pathinfo['extension']), array('gif', 'png', 'jpg', 'jpeg')))
  179. return false;
  180. }
  181. $type = exif_imagetype($path);
  182. if (!$type)
  183. return false;
  184. return ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG);
  185. }
  186. private function saveXhr($path) {
  187. if (false !== file_put_contents($path, fopen('php://input', 'r')))
  188. return true;
  189. return false;
  190. }
  191. private function saveForm($path) {
  192. if (move_uploaded_file($_FILES[$this->uploadName]['tmp_name'], $path))
  193. return true;
  194. return false;
  195. }
  196. private function save($path) {
  197. if (true === $this->isXhr)
  198. return $this->saveXhr($path);
  199. return $this->saveForm($path);
  200. }
  201. public function handleUpload($uploadDir = null, $allowedExtensions = null) {
  202. if (!$this->fileName) {
  203. $this->setErrorMsg('上传文件不正确或没有上传文件');
  204. return false;
  205. }
  206. if ($this->fileSize == 0) {
  207. $this->setErrorMsg('文件是空的');
  208. return false;
  209. }
  210. if ($this->fileSize > $this->sizeLimit) {
  211. $this->setErrorMsg('文件大小超出限制');
  212. return false;
  213. }
  214. if (!empty($uploadDir))
  215. $this->uploadDir = $uploadDir;
  216. $this->uploadDir = $this->fixDir($this->uploadDir);
  217. if (!file_exists($this->uploadDir)) {
  218. $this->setErrorMsg('上传目录不存在');
  219. return false;
  220. } else if (!is_writable($this->uploadDir)) {
  221. $this->setErrorMsg('上载目录存在,但不可写。');
  222. return false;
  223. }
  224. if (is_array($allowedExtensions))
  225. $this->allowedExtensions = $allowedExtensions;
  226. if (!empty($this->allowedExtensions)) {
  227. if (!$this->checkExtension($this->fileExtension, $this->allowedExtensions)) {
  228. $this->setErrorMsg('无效的文件类型');
  229. return false;
  230. }
  231. }
  232. $this->savedFile = $this->uploadDir . $this->fileName;
  233. if (!empty($this->newFileName)) {
  234. $this->fileName = $this->newFileName;
  235. $this->savedFile = $this->uploadDir . $this->fileName;
  236. $this->fileNameWithoutExt = null;
  237. $this->fileExtension = null;
  238. $pathinfo = pathinfo($this->fileName);
  239. if (isset($pathinfo['filename']))
  240. $this->fileNameWithoutExt = $pathinfo['filename'];
  241. if (isset($pathinfo['extension']))
  242. $this->fileExtension = strtolower($pathinfo['extension']);
  243. }
  244. if (!$this->save($this->savedFile)) {
  245. $this->setErrorMsg('文件无法保存');
  246. return false;
  247. }
  248. return true;
  249. }
  250. }