---
title: "php封装图片上传类"
author: "mywebcode"
date: "2014-04-22T23:17:00Z"
tags: []
slug: "php"
draft: false
lastmod: "2014-04-30T09:12:56Z"
id: 2058162
url: "https://mywebcode.iteye.com/blog/2058162"
---

PHP中的类和对象十分有用，今天就来分享一下用PHP的封装的图片上传的类，妈妈再也不担心我上传图片了。哄哄

![大笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)

---------------》废话不多说，直接走代码《-------------------

```
<?php
header('content-type:text/html;charset=utf-8');
class UpImg{
	public $arrimg;//上传文件用到的数组。
	function __construct($ai){
		$this->arrimg=$ai;
	}
	function checktype(){//上传文件类型判断
		$extname=end(explode(".",$this->arrimg['name']));
		//取出上传文件的扩展名
		$brr=array("jpg","gif","png","jpeg");
		if(in_array($extname,$brr)){
			return $extname;
		}else{
			echo "上传文件类型错误，请修改正后上传。";
			exit;
		}
	}
	function checksize(){
		if($this->arrimg['size']>2000000){
			echo "文件太大，请调整后再上传。";
			exit;
		}
	}
	function createdir(){
		$filepath="upload/";
		if(!is_dir($filepath)){//目录不存在就创建它
			mkdir($filepath);	
		}
		$filepath=$filepath.date("Ymd")."/";
		if(!is_dir($filepath)){
			mkdir($filepath);
		}
		$filename=$filepath.uniqid("is_ref_",true).".".$extname;
		return $filename;
	}
	function uploadimg(){
		if($this->arrimg['error']==0){
			$extname=$this->checktype();//判断类型
			$this->checksize();//判断大小
			$filename=$this->createdir();
			move_uploaded_file($this->arrimg["tmp_name"],$filename);
			return $filename;
		}else{
			echo "文件上传失败。";
		}
	}
}
?>
```

![](http://img.blog.csdn.net/20140422231612406?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvcGhwNTkyMQ=%3D%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70%2Fgravity%2FCenter)