php文件上传类完整实例

这篇文章主要介绍了php文件上传类,结合完整实例形式分析了php上传文件的类型判断、大小计算机限制等技巧,需要的朋友可以参考下,本文实例讲述了php文件上传类,分享给大家供大家参考,具体如下:

  1. /**
  2. $file=new class_file($file_array,"flash/");
  3. $file->set_allow_type(array("jpg","jpeg","gif"));
  4. $file->is_limit_size();
  5. if(!$file->allow_file_size()){
  6. echo $file->error;
  7. exit;
  8. }
  9. if(!$file->allow_file_type()){
  10. echo $file->error;
  11. exit();
  12. }else if(!$file->uploadfile()){
  13. echo $file->error;
  14. exit;
  15. }
  16. **/
  17. <?php
  18. class class_file{
  19. private $file_type;
  20. private $file_size;
  21. private $save_path;
  22. private $file_path;
  23. private $allow_type=array();
  24. private $allow_size;
  25. private $file_name;
  26. private $flag=false;
  27. private $mime_type;
  28. private $is_limit_size=false;
  29. public $error;
  30. //构造函数
  31. function class_file($file_array,$save_path){
  32. $this->file_path=$file_array['tmp_name'];
  33. $this->file_size=$file_array['size'];
  34. $this->file_type=$file_array['type'];
  35. $this->save_path=$save_path;
  36. }
  37. //设置允许的文件类型
  38. function set_allow_type($allow_type){
  39. $this->allow_type=$allow_type;
  40. }
  41. //设置允许的文件大小
  42. function set_allow_size($allow_size){
  43. $this->allow_size=$allow_size;
  44. }
  45. //文件上传
  46. public function uploadfile(){
  47. if(!$this->allow_file_type()){
  48. $this->file_name();
  49. }
  50. if(move_uploaded_file($this->file_path,$this->save_path.$this->file_name)){
  51. return true;
  52. }else{
  53. $this->error="文件上传失败";
  54. return;
  55. }
  56. }
  57. //判断文件上传的类型
  58. function allow_file_type(){
  59. $this->file_name();
  60. if(in_array($this->mime_type,$this->allow_type)){
  61. return true;
  62. }else{
  63. $this->error="不允许上传的类型";
  64. exit();
  65. }
  66. }
  67. //判断文件上传的大小
  68. function allow_file_size($size=100){
  69. if($this->is_limit_size){
  70. $this->set_allow_size($size);
  71. if($this->allow_size>=$this->file_size){
  72. return true;
  73. }else{
  74. $this->error="超过文件上传大小限制";
  75. }
  76. }
  77. }
  78. //是否限制文件大小
  79. function is_limit_size(){
  80. $this->is_limit_size=true;
  81. }
  82. //文件类型和文件名称
  83. function file_name(){
  84. $this->mime_type=substr($this->file_type,strpos($this->file_type,"/")+1);
  85. if($this->mime_type=="pjpeg"){
  86. $this->mime_type="jpg";
  87. }
  88. if($this->mime_type=="x-ms-wma"){
  89. $this->mime_type="wma";
  90. }
  91. if($this->mime_type=="x-ms-wmv"){
  92. $this->mime_type="wmv";
  93. }
  94. $this->file_name=date("YmdHis").".$this->mime_type";
  95. }
  96. function _get_file_name(){
  97. return $this->file_name;
  98. }
  99. }
  100. ?>