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 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. * @return $string
  89. */
  90. public function hash($type = 'sha1')
  91. {
  92. if (!isset($this->hash[$type])) {
  93. $this->hash[$type] = hash_file($type, $this->filename);
  94. }
  95. return $this->hash[$type];
  96. }
  97. /**
  98. * 检查目录是否可写
  99. * @param string $path 目录
  100. * @return boolean
  101. */
  102. protected function checkPath($path)
  103. {
  104. if (is_dir($path)) {
  105. return true;
  106. }
  107. if (mkdir($path, 0755, true)) {
  108. return true;
  109. } else {
  110. $this->error = "目录 {$path} 创建失败!";
  111. return false;
  112. }
  113. }
  114. /**
  115. * 获取文件类型信息
  116. * @return string
  117. */
  118. public function getMime()
  119. {
  120. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  121. return finfo_file($finfo, $this->filename);
  122. }
  123. /**
  124. * 设置文件的命名规则
  125. * @param string $rule 文件命名规则
  126. * @return $this
  127. */
  128. public function rule($rule)
  129. {
  130. $this->rule = $rule;
  131. return $this;
  132. }
  133. /**
  134. * 设置上传文件的验证规则
  135. * @param array $rule 验证规则
  136. * @return $this
  137. */
  138. public function validate($rule = [])
  139. {
  140. $this->validate = $rule;
  141. return $this;
  142. }
  143. /**
  144. * 检测是否合法的上传文件
  145. * @return bool
  146. */
  147. public function isValid()
  148. {
  149. if ($this->isTest) {
  150. return is_file($this->filename);
  151. }
  152. return is_uploaded_file($this->filename);
  153. }
  154. /**
  155. * 检测上传文件
  156. * @param array $rule 验证规则
  157. * @return bool
  158. */
  159. public function check($rule = [])
  160. {
  161. $rule = $rule ?: $this->validate;
  162. /* 检查文件大小 */
  163. if (isset($rule['size']) && !$this->checkSize($rule['size'])) {
  164. $this->error = '上传文件大小不符!';
  165. return false;
  166. }
  167. /* 检查文件Mime类型 */
  168. if (isset($rule['type']) && !$this->checkMime($rule['type'])) {
  169. $this->error = '上传文件MIME类型不允许!';
  170. return false;
  171. }
  172. /* 检查文件后缀 */
  173. if (isset($rule['ext']) && !$this->checkExt($rule['ext'])) {
  174. $this->error = '上传文件后缀不允许';
  175. return false;
  176. }
  177. /* 检查图像文件 */
  178. if (!$this->checkImg()) {
  179. $this->error = '非法图像文件!';
  180. return false;
  181. }
  182. return true;
  183. }
  184. /**
  185. * 检测上传文件后缀
  186. * @param array|string $ext 允许后缀
  187. * @return bool
  188. */
  189. public function checkExt($ext)
  190. {
  191. if (is_string($ext)) {
  192. $ext = explode(',', $ext);
  193. }
  194. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  195. if (!in_array($extension, $ext)) {
  196. return false;
  197. }
  198. return true;
  199. }
  200. /**
  201. * 检测图像文件
  202. * @return bool
  203. */
  204. public function checkImg()
  205. {
  206. $extension = strtolower(pathinfo($this->getInfo('name'), PATHINFO_EXTENSION));
  207. /* 对图像文件进行严格检测 */
  208. if (in_array($extension, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']) && !in_array($this->getImageType($this->filename), [1, 2, 3, 4, 6])) {
  209. return false;
  210. }
  211. return true;
  212. }
  213. // 判断图像类型
  214. protected function getImageType($image)
  215. {
  216. if (function_exists('exif_imagetype')) {
  217. return exif_imagetype($image);
  218. } else {
  219. $info = getimagesize($image);
  220. return $info[2];
  221. }
  222. }
  223. /**
  224. * 检测上传文件大小
  225. * @param integer $size 最大大小
  226. * @return bool
  227. */
  228. public function checkSize($size)
  229. {
  230. if ($this->getSize() > $size) {
  231. return false;
  232. }
  233. return true;
  234. }
  235. /**
  236. * 检测上传文件类型
  237. * @param array|string $mime 允许类型
  238. * @return bool
  239. */
  240. public function checkMime($mime)
  241. {
  242. if (is_string($mime)) {
  243. $mime = explode(',', $mime);
  244. }
  245. if (!in_array(strtolower($this->getMime()), $mime)) {
  246. return false;
  247. }
  248. return true;
  249. }
  250. /**
  251. * 移动文件
  252. * @param string $path 保存路径
  253. * @param string|bool $savename 保存的文件名 默认自动生成
  254. * @param boolean $replace 同名文件是否覆盖
  255. * @return false|File false-失败 否则返回File实例
  256. */
  257. public function move($path, $savename = true, $replace = true)
  258. {
  259. // 文件上传失败,捕获错误代码
  260. if (!empty($this->info['error'])) {
  261. $this->error($this->info['error']);
  262. return false;
  263. }
  264. // 检测合法性
  265. if (!$this->isValid()) {
  266. $this->error = '非法上传文件';
  267. return false;
  268. }
  269. // 验证上传
  270. if (!$this->check()) {
  271. return false;
  272. }
  273. $path = rtrim($path, DS) . DS;
  274. // 文件保存命名规则
  275. $saveName = $this->buildSaveName($savename);
  276. $filename = $path . $saveName;
  277. // 检测目录
  278. if (false === $this->checkPath(dirname($filename))) {
  279. return false;
  280. }
  281. /* 不覆盖同名文件 */
  282. if (!$replace && is_file($filename)) {
  283. $this->error = '存在同名文件' . $filename;
  284. return false;
  285. }
  286. /* 移动文件 */
  287. if ($this->isTest) {
  288. rename($this->filename, $filename);
  289. } elseif (!move_uploaded_file($this->filename, $filename)) {
  290. $this->error = '文件上传保存错误!';
  291. return false;
  292. }
  293. // 返回 File对象实例
  294. $file = new self($filename);
  295. $file->setSaveName($saveName);
  296. $file->setUploadInfo($this->info);
  297. return $file;
  298. }
  299. /**
  300. * 获取保存文件名
  301. * @param string|bool $savename 保存的文件名 默认自动生成
  302. * @return string
  303. */
  304. protected function buildSaveName($savename)
  305. {
  306. if (true === $savename) {
  307. // 自动生成文件名
  308. if ($this->rule instanceof \Closure) {
  309. $savename = call_user_func_array($this->rule, [$this]);
  310. } else {
  311. switch ($this->rule) {
  312. case 'date':
  313. $savename = date('Ymd') . DS . md5(microtime(true));
  314. break;
  315. default:
  316. if (in_array($this->rule, hash_algos())) {
  317. $hash = $this->hash($this->rule);
  318. $savename = substr($hash, 0, 2) . DS . substr($hash, 2);
  319. } elseif (is_callable($this->rule)) {
  320. $savename = call_user_func($this->rule);
  321. } else {
  322. $savename = date('Ymd') . DS . md5(microtime(true));
  323. }
  324. }
  325. }
  326. } elseif ('' === $savename) {
  327. $savename = $this->getInfo('name');
  328. }
  329. if (!strpos($savename, '.')) {
  330. $savename .= '.' . pathinfo($this->getInfo('name'), PATHINFO_EXTENSION);
  331. }
  332. return $savename;
  333. }
  334. /**
  335. * 获取错误代码信息
  336. * @param int $errorNo 错误号
  337. */
  338. private function error($errorNo)
  339. {
  340. switch ($errorNo) {
  341. case 1:
  342. case 2:
  343. $this->error = '上传文件大小超过了最大值!';
  344. break;
  345. case 3:
  346. $this->error = '文件只有部分被上传!';
  347. break;
  348. case 4:
  349. $this->error = '没有文件被上传!';
  350. break;
  351. case 6:
  352. $this->error = '找不到临时文件夹!';
  353. break;
  354. case 7:
  355. $this->error = '文件写入失败!';
  356. break;
  357. default:
  358. $this->error = '未知上传错误!';
  359. }
  360. }
  361. /**
  362. * 获取错误信息
  363. * @return mixed
  364. */
  365. public function getError()
  366. {
  367. return $this->error;
  368. }
  369. public function __call($method, $args)
  370. {
  371. return $this->hash($method);
  372. }
  373. }