php简单文件上传类

时间:2023-03-22 12:04:26
  1. <?php
  2. header("Content-Type:text/html; charset=utf-8");
  3. if($_POST['submit']){
  4. $upfiles = new Upload();
  5. $upfiles->upload_file();
  6. }
  7. class Upload{
  8. /*作者:mckee 来自:www.phpddt.com*/
  9. public $upload_name; //上传文件名
  10. public $upload_tmp_name; //上传临时文件名
  11. public $upload_final_name; //上传文件的最终文件名
  12. public $upload_target_dir; //文件被上传到的目标目录
  13. public $upload_target_path; //文件被上传到的最终路径
  14. public $upload_filetype ; //上传文件类型
  15. public $allow_uploadedfile_type; //允许的上传文件类型
  16. public $upload_file_size; //上传文件的大小
  17. public $allow_uploaded_maxsize=10000000; //允许上传文件的最大值
  18. //构造函数
  19. public function __construct()
  20. {
  21. $this->upload_name = $_FILES["file"]["name"]; //取得上传文件名
  22. $this->upload_filetype = $_FILES["file"]["type"];
  23. $this->upload_tmp_name = $_FILES["file"]["tmp_name"];
  24. $this->allow_uploadedfile_type = array('jpeg','jpg','png','gif','bmp','doc','zip','rar','txt','wps');
  25. $this->upload_file_size = $_FILES["file"]["size"];
  26. $this->upload_target_dir="./upload";
  27. }
  28. //文件上传
  29. public function upload_file()
  30. {
  31. $upload_filetype = $this->getFileExt($this->upload_name);
  32. if(in_array($upload_filetype,$this->allow_uploadedfile_type))
  33. {
  34. if($this->upload_file_size < $this->allow_uploaded_maxsize)
  35. {
  36. if(!is_dir($this->upload_target_dir))
  37. {
  38. mkdir($this->upload_target_dir);
  39. chmod($this->upload_target_dir,0777);
  40. }
  41. $this->upload_final_name = date("YmdHis").rand(0,100).'.'.$upload_filetype;
  42. $this->upload_target_path = $this->upload_target_dir."/".$this->upload_final_name;
  43. if(!move_uploaded_file($this->upload_tmp_name,$this->upload_target_path))
  44. echo "<font color=red>文件上传失败!</font>";
  45. }
  46. else
  47. {
  48. echo("<font color=red>文件太大,上传失败!</font>");
  49. }
  50. }
  51. else
  52. {
  53. echo("不支持此文件类型,请重新选择");
  54. }
  55. }
  56. /**
  57. *获取文件扩展名
  58. *@param String $filename 要获取文件名的文件
  59. */
  60. public function getFileExt($filename){
  61. $info = pathinfo($filename);
  62. return $info["extension"];
  63. }
  64. }
  65. ?>
  66. <form enctype="multipart/form-data" method="POST" action="">
  67. <input type="file" name="file"><input type="submit" name="submit" value="上传">
  68. </form>