File.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use SplFileInfo;
  13. use SplFileObject;
  14. class File extends SplFileObject
  15. {
  16. /**
  17. * 错误信息
  18. * @var string
  19. */
  20. private $error = '';
  21. // 当前完整文件名
  22. protected $filename;
  23. // 上传文件名
  24. protected $saveName;
  25. // 文件上传命名规则
  26. protected $rule = 'date';
  27. // 文件上传验证规则
  28. protected $validate = [];
  29. // 单元测试
  30. protected $isTest;
  31. // 上传文件信息
  32. protected $info;
  33. // 文件hash信息
  34. protected $hash = [];
  35. public function __construct($filename, $mode = 'r')
  36. {
  37. parent::__construct($filename, $mode);
  38. $this->filename = $this->getRealPath() ?: $this->getPathname();
  39. }
  40. /**
  41. * 是否测试
  42. * @param bool $test 是否测试
  43. * @return $this
  44. */
  45. public function isTest($test = false)
  46. {
  47. $this->isTest = $test;
  48. return $this;
  49. }
  50. /**
  51. * 设置上传信息
  52. * @param array $info 上传文件信息
  53. * @return $this
  54. */
  55. public function setUploadInfo($info)
  56. {
  57. $this->info = $info;
  58. return $this;
  59. }
  60. /**
  61. * 获取上传文件的信息
  62. * @param string $name
  63. * @return array|string
  64. */
  65. public function getInfo($name = '')
  66. {
  67. return isset($this->info[$name]) ? $this->info[$name] : $this->info;
  68. }
  69. /**
  70. * 获取上传文件的文件名
  71. * @return string
  72. */
  73. public function getSaveName()
  74. {
  75. return $this->saveName;
  76. }
  77. /**
  78. * 设置上传文件的保存文件名
  79. * @param string $saveName
  80. * @return $this
  81. */
  82. public function setSaveName($saveName)
  83. {
  84. $this->saveName = $saveName;
  85. return $this;
  86. }
  87. /**
  88. * 获取文件的哈希散列值
  89. * @return $string
  90. */
  91. public function hash($type = 'sha1')
  92. {
  93. if (!isset($this->hash[$type])) {
  94. $this->hash[$type] = hash_file($type, $this->filename);
  95. }
  96. return $this->hash[$type];
  97. }
  98. /**
  99. * 检查目录是否可写
  100. * @param string $path 目录
  101. * @return boolean
  102. */
  103. protected function checkPath($path)
  104. {
  105. if (is_dir($path)) {
  106. return true;
  107. }
  108. if (mkdir($path, 0755, true)) {
  109. return true;
  110. } else {
  111. $this->error = "目录 {$path} 创建失败!";
  112. return false;
  113. }
  114. }
  115. /**
  116. * 获取文件类型信息
  117. * @return string
  118. */
  119. public function getMime()
  120. {
  121. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  122. return finfo_file($finfo, $this->filename);
  123. }
  124. /**
  125. * 设置文件的命名规则
  126. * @param string $rule 文件命名规则
  127. * @return $this
  128. */
  129. public function rule($rule)
  130. {
  131. $this->rule = $rule;
  132. return $this;
  133. }
  134. /**
  135. * 设置上传文件的验证规则
  136. * @param array $rule 验证规则
  137. * @return $this
  138. */
  139. public function validate($rule = [])
  140. {
  141. $this->validate = $rule;
  142. return $this;
  143. }
  144. /**
  145. * 检测是否合法的上传文件
  146. * @return bool
  147. */
  148. public function isValid()
  149. {
  150. if ($this->isTest) {
  151. return is_file($this->filename);
  152. }
  153. return is_uploaded_file($this->filename);
  154. }
  155. /**
  156. * 检测上传文件
  157. * @param array $rule 验证规则
  158. * @return bool
  159. */
  160. public function check($rule = [])
  161. {
  162. $rule = $rule ?: $this->validate;
  163. /* 检查文件大小 */
  164. if (isset($rule['size']) && !$this->checkSize($rule['size'])) {
  165. $this->error = '上传文件大小不符!';
  166. return false;
  167. }
  168. /* 检查文件Mime类型 */
  169. if (isset($rule['type']) && !$this->checkMime($rule['type'])) {
  170. $this->error = '上传文件MIME类型不允许!';
  171. return false;
  172. }
  173. /* 检查文件后缀 */
  174. if (isset($rule['ext']) && !$this->checkExt($rule['ext'])) {
  175. $this->error = '上传文件后缀不允许';
  176. return false;
  177. }
  178. /* 检查图像文件 */
  179. if (!$this->checkImg()) {
  180. $this->error = '非法图像文件!';
  181. return false;
  182. }
  183. return true;
  184. }
  185. /**
  186. * 检测上传文件后缀
  187. * @param array|string $ext 允许后缀
  188. * @return bool
  189. */
  190. public function checkExt($ext)
  191. {
  192. if (is_string($ext)) {
  193. $ext = explode(',', $ext);
  194. }
  195. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  196. if (!in_array($extension, $ext)) {
  197. return false;
  198. }
  199. return true;
  200. }
  201. /**
  202. * 检测图像文件
  203. * @return bool
  204. */
  205. public function checkImg()
  206. {
  207. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  208. /* 对图像文件进行严格检测 */
  209. if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6])) {
  210. return false;
  211. }
  212. return true;
  213. }
  214. // 判断图像类型
  215. protected function getImageType($image)
  216. {
  217. if (function_exists('exif_imagetype')) {
  218. return exif_imagetype($image);
  219. } else {
  220. $info = getimagesize($image);
  221. return $info[2];
  222. }
  223. }
  224. /**
  225. * 检测上传文件大小
  226. * @param integer $size 最大大小
  227. * @return bool
  228. */
  229. public function checkSize($size)
  230. {
  231. if ($this->getSize() > $size) {
  232. return false;
  233. }
  234. return true;
  235. }
  236. /**
  237. * 检测上传文件类型
  238. * @param array|string $mime 允许类型
  239. * @return bool
  240. */
  241. public function checkMime($mime)
  242. {
  243. if (is_string($mime)) {
  244. $mime = explode(',', $mime);
  245. }
  246. if (!in_array(strtolower($this->getMime()), $mime)) {
  247. return false;
  248. }
  249. return true;
  250. }
  251. /**
  252. * 移动文件
  253. * @param string $path 保存路径
  254. * @param string|bool $savename 保存的文件名 默认自动生成
  255. * @param boolean $replace 同名文件是否覆盖
  256. * @return false|SplFileInfo false-失败 否则返回SplFileInfo实例
  257. */
  258. public function move($path, $savename = true, $replace = true)
  259. {
  260. // 文件上传失败,捕获错误代码
  261. if (!empty($this->info['error'])) {
  262. $this->error($this->info['error']);
  263. return false;
  264. }
  265. // 检测合法性
  266. if (!$this->isValid()) {
  267. $this->error = '非法上传文件';
  268. return false;
  269. }
  270. // 验证上传
  271. if (!$this->check()) {
  272. return false;
  273. }
  274. $path = rtrim($path, DS) . DS;
  275. // 文件保存命名规则
  276. $saveName = $this->buildSaveName($savename);
  277. $filename = $path . $saveName;
  278. // 检测目录
  279. if (false === $this->checkPath(dirname($filename))) {
  280. return false;
  281. }
  282. /* 不覆盖同名文件 */
  283. if (!$replace && is_file($filename)) {
  284. $this->error = '存在同名文件' . $filename;
  285. return false;
  286. }
  287. /* 移动文件 */
  288. if ($this->isTest) {
  289. rename($this->filename, $filename);
  290. } elseif (!move_uploaded_file($this->filename, $filename)) {
  291. $this->error = '文件上传保存错误!';
  292. return false;
  293. }
  294. // 返回 File对象实例
  295. $file = new self($filename);
  296. $file->setSaveName($saveName);
  297. $file->setUploadInfo($this->info);
  298. return $file;
  299. }
  300. /**
  301. * 获取保存文件名
  302. * @param string|bool $savename 保存的文件名 默认自动生成
  303. * @return string
  304. */
  305. protected function buildSaveName($savename)
  306. {
  307. if (true === $savename) {
  308. // 自动生成文件名
  309. if ($this->rule instanceof \Closure) {
  310. $savename = call_user_func_array($this->rule, [$this]);
  311. } else {
  312. switch ($this->rule) {
  313. case 'date':
  314. $savename = date('Ymd') . DS . md5(microtime(true));
  315. break;
  316. default:
  317. if (in_array($this->rule, hash_algos())) {
  318. $hash = $this->hash($this->rule);
  319. $savename = substr($hash, 0, 2) . DS . substr($hash, 2);
  320. } elseif (is_callable($this->rule)) {
  321. $savename = call_user_func($this->rule);
  322. } else {
  323. $savename = date('Ymd') . DS . md5(microtime(true));
  324. }
  325. }
  326. }
  327. } elseif ('' === $savename) {
  328. $savename = $this->getInfo('name');
  329. }
  330. if (!strpos($savename, '.')) {
  331. $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION);
  332. }
  333. return $savename;
  334. }
  335. /**
  336. * 获取错误代码信息
  337. * @param int $errorNo 错误号
  338. */
  339. private function error($errorNo)
  340. {
  341. switch ($errorNo) {
  342. case 1:
  343. case 2:
  344. $this->error = '上传文件大小超过了最大值!';
  345. break;
  346. case 3:
  347. $this->error = '文件只有部分被上传!';
  348. break;
  349. case 4:
  350. $this->error = '没有文件被上传!';
  351. break;
  352. case 6:
  353. $this->error = '找不到临时文件夹!';
  354. break;
  355. case 7:
  356. $this->error = '文件写入失败!';
  357. break;
  358. default:
  359. $this->error = '未知上传错误!';
  360. }
  361. }
  362. /**
  363. * 获取错误信息
  364. * @return mixed
  365. */
  366. public function getError()
  367. {
  368. return $this->error;
  369. }
  370. public function __call($method, $args)
  371. {
  372. return $this->hash($method);
  373. }
  374. }