class Uploadimg{
private $_fileName=""; //檔案網域名稱稱 如 'userfile'
private $_uploadDir = ''; //上傳路徑 如 ./upload/
/*上傳參數配置*/
private $_config = array(
'type'=>array('image/jpeg','image/jpg',
'image/pjpeg','image/gif'), //上傳的類型
'size'=>1, //檔案最大容量單位是M
'width'=>1000, //圖片的最大寬度
'height'=>800 //圖片的最大高度
);
/**
* 建構函式
*
* @param string $fileName
* @param string $uploadDir
* @param array $config
*/
function __construct($fileName,$uploadDir,$config='')
{
$this->_fileName = $fileName;
$this->_uploadDir = $uploadDir;
if($config == "" or empty($config) or !is_array($config)){
$this->_config = $this->_config;
}else{
$this->_config = $config;
}
}
/**
* 檢測容量是否超過
*
* @return boolean
*/
function checkSize()
{
if($_FILES[$this->_fileName]['size'] > $this->_config['size']*1024*1024){
return false;
}else{
return true;
}
}
/**
* 擷取圖片資訊
*
* @return boolean
*/
function getInfo()
{
return @getimagesize($_FILES[$this->_fileName]['tmp_name']);
}
/**
* 檢測尾碼名
*
* @return boolean
*/
function checkExt()
{
$imageInfo = $this->getInfo();
if(in_array($imageInfo['mime'],$this->_config['type'])){
return true;
}else{
return false;
}
}
/**
* 擷取尾碼名
*
* @return boolean
*/
function getExt()
{
$imageInfo = $this->getInfo();
switch($imageInfo['mime']){
case 'image/jpeg':$filenameExt = '.jpg';break;
case 'image/jpg':$filenameExt = '.jpg';break;
case 'image/pjpeg':$filenameExt = '.jpg';break;
case 'image/gif':$filenameExt = '.gif';break;
default:break;
}
return $filenameExt;
}
/**
* 檢測尺寸
*
* @return boolean
*/
function checkWh()
{
$imageInfo = $this->getInfo();
if(($imageInfo[0] > $this->_config['width']) or ($imageInfo[1] > $this->_config['height'])){
return false;
}else{
return true;
}
}
/**
* 上傳一張圖片
*
* @return string or int
*/
function uploadSingleImage()
{
if($this->checkSize() == false){
return (-3); /*上傳容量過大*/
exit();
}
if($this->checkExt() == true){
$filenameExt = $this->getExt();
}else{
return (-2); /*上傳格式錯誤*/
exit();
}
if($this->checkWh() == false){
return (-1); /*上傳圖片太寬或太高*/
exit();
}
$file_new_name = date('YmdHis').$filenameExt;
$file_new_name_upload = rtrim($_SERVER['DOCUMENT_ROOT'],'/').$this->_uploadDir.$file_new_name;
if(@move_uploaded_file($_FILES[$this->_fileName]['tmp_name'],$file_new_name_upload)){
return $file_new_name;
}else{
return (0); /*上傳失敗*/
}
}
/**
* 刪除圖片
*
* @param string $imageName
* @return boolen
*/
function delImage($imageName)
{
$path = rtrim($_SERVER['DOCUMENT_ROOT'],'/').$this->_uploadDir.$imageName;
if(unlink($path) == true){
return true;
}else{
return false;
}
}
}