适用于初学者的简易PHP文件上传类

这篇文章主要为大家分享了一个适用于初学者的简易PHP文件上传类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,本文实例讲述了PHP多文件上传类,分享给大家供大家参考,具体如下:

  1. <?php
  2. class Test_Upload{
  3. protected $_uploaded = array();
  4. protected $_destination;
  5. protected $_max = 1024000;
  6. protected $_messages = array();
  7. protected $_permited = array(
  8. 'image/gif',
  9. 'image/jpeg',
  10. 'image/pjpeg',
  11. 'image/png'
  12. );
  13. protected $_renamed = false;
  14. /**
  15. *
  16. * @param mix $path
  17. *
  18. */
  19. public function __construct($path){
  20. if (!is_dir($path) || !is_writable($path)){
  21. throw new Exception("文件名不可写,或者不是目录!");
  22. }
  23. $this->_destination = $path;
  24. $this->_uploaded = $_FILES;
  25. }
  26. /**
  27. * 移动文件
  28. *
  29. */
  30. public function move(){
  31. $filed = current($this->_uploaded);
  32. $isOk = $this->checkError($filed['name'], $filed['error']);
  33. //debug ok
  34. if ($isOk){
  35. $sizeOk = $this->checkSize($filed['name'], $filed['size']);
  36. $typeOk = $this->checkType($filed['name'], $filed['type']);
  37. if ($sizeOk && $typeOk){
  38. $success = move_uploaded_file($filed['tmp_name'], $this->_destination.$filed['name']);
  39. if ($success){
  40. $this->_messages[] = $filed['name']."文件上传成功";
  41. }else {
  42. $this->_messages[] = $filed['name']."文件上传失败";
  43. }
  44. }
  45. }
  46. }
  47. /**
  48. * 查询messages数组内容
  49. *
  50. */
  51. public function getMessages(){
  52. return $this->_messages;
  53. }
  54. /**
  55. * 检测上传的文件大小
  56. * @param mix $string
  57. * @param int $size
  58. */
  59. public function checkSize($filename, $size){
  60. if ($size == 0){
  61. return false;
  62. }else if ($size > $this->_max){
  63. $this->_messages[] = "文件超出上传限制大小".$this->getMaxsize();
  64. return false;
  65. }else {
  66. return true;
  67. }
  68. }
  69. /**
  70. * 检测上传文件的类型
  71. * @param mix $filename
  72. * @param mix $type
  73. */
  74. protected function checkType($filename, $type){
  75. if (!in_array($type, $this->_permited)){
  76. $this->_messages[] = "该文件类型是不被允许的上传类型";
  77. return false;
  78. }else {
  79. return true;
  80. }
  81. }
  82. /**
  83. * 获取文件大小
  84. *
  85. */
  86. public function getMaxsize(){
  87. return number_format($this->_max / 1024, 1).'KB';
  88. }
  89. /**
  90. * 检测上传错误
  91. * @param mix $filename
  92. * @param int $error
  93. *
  94. */
  95. public function checkError($filename, $error){
  96. switch ($error){
  97. case 0 : return true;
  98. case 1 :
  99. case 2 : $this->_messages[] = "文件过大!"; return true;
  100. case 3 : $this->_messages[] = "错误上传文件!";return false;
  101. case 4 : $this->_messages[] = "没有选择文件!"; return false;
  102. default : $this->_messages[] = "系统错误!"; return false;
  103. }
  104. }
  105. }
  106. ?>