File.php 11 KB

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