常用类及函数
目录
常用函数
html截取函数
常用类
字符串加密类
程序执行时间类
验证码类
无刷新分页类
分页类
非法校验类
mysqli类
文件上传类
图片处理类
html截取函数(html_sub.php)
]+?>)/si",$content, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE); $wordrows=0; //中英字数 $outstr=""; //生成的字串 $wordend=false; //是否符合最大的长度 $beginTags=0; //除
这些短标签外,其它计算开始标签,如
$endTags=0; //计算结尾标签,如
,如果$beginTags==$endTags表示标签数目相对称,可以退出循环。 //print_r($content); foreach($content as $value){ if (trim($value)=="") continue; //如果该值为空,则继续下一个值 if (strpos(";$value","<")>0){ //如果与要载取的标签相同,则到处结束截取。 if (trim($value)==$maxlen) { $wordend=true; continue; } if ($wordend==false){ $outstr.=$value; if (!preg_match("/
]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value) && !preg_match("/]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value)) { $beginTags++; //除img,br,hr外的标签都加1 } }else if (preg_match("/<\/([^>]+?)>/is",$value,$matches)){ $endTags++; $outstr.=$value; if ($beginTags==$endTags && $wordend==true) break; //字已载完了,并且标签数相称,就可以退出循环。 }else{ if (!preg_match("/
]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value) && !preg_match("/]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value) && !preg_match("/
]+?)>/is",$value)) { $beginTags++; //除img,br,hr外的标签都加1 $outstr.=$value; } } }else{ if (is_numeric($maxlen)){ //截取字数 $curLength=getStringLength($value); $maxLength=$curLength+$wordrows; if ($wordend==false){ if ($maxLength>$maxlen){ //总字数大于要截取的字数,要在该行要截取 $outstr.=subString($value,0,$maxlen-$wordrows); $wordend=true; }else{ $wordrows=$maxLength; $outstr.=$value; } } }else{ if ($wordend==false) $outstr.=$value; } } } //循环替换掉多余的标签,如
这一类 while(preg_match("/<([^\/][^>]*?)><\/([^>]+?)>/is",$outstr)){ $outstr=preg_replace_callback("/<([^\/][^>]*?)><\/([^>]+?)>/is","strip_empty_html",$outstr); } //把误换的标签换回来 if (strpos(";".$outstr,"[html_")>0){ $outstr=str_replace("[html_<]","<",$outstr); $outstr=str_replace("[html_>]",">",$outstr); } //echo htmlspecialchars($outstr); return $outstr; } //去掉多余的空标签 function strip_empty_html($matches){ $arr_tags1=explode(" ",$matches[1]); if ($arr_tags1[0]==$matches[2]){ //如果前后标签相同,则替换为空。 return ""; }else{ $matches[0]=str_replace("<","[html_<]",$matches[0]); $matches[0]=str_replace(">","[html_>]",$matches[0]); return $matches[0]; } } //取得字符串的长度,包括中英文。 function getStringLength($text){ if (function_exists('mb_substr')) { $length=mb_strlen($text,'UTF-8'); }else if(function_exists('iconv_substr')) { $length=iconv_strlen($text,'UTF-8'); }else{ preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar); $length=count($ar[0]); } return $length; } /***********按一定长度截取字符串(包括中文)*********/ function subString($text, $start=0, $limit=12) { if (function_exists('mb_substr')) { $more = (mb_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE; $text = mb_substr($text, 0, $limit, 'UTF-8'); return $text; }else if(function_exists('iconv_substr')) { $more = (iconv_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE; $text = iconv_substr($text, 0, $limit, 'UTF-8'); //return array($text, $more); return $text; }else{ preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar); if(func_num_args() >= 3) { if (count($ar[0])>$limit) { $more = TRUE; $text = join("",array_slice($ar[0],0,$limit)); } else { $more = FALSE; $text = join("",array_slice($ar[0],0,$limit)); } } else { $more = FALSE; $text = join("",array_slice($ar[0],0)); } return $text; } } ?>
字符串加密类(syscrypt.class.php)
crypt_key = $crypt_key; } public function php_encrypt($txt) { $encrypt_key = md5(rand(0,32000)); $ctr = 0; $tmp = ''; for($i = 0;$i
crypt_key)); } public function php_decrypt($txt) { $txt = self::__key(base64_decode($txt),$this -> crypt_key); $tmp = ''; for($i = 0;$i < strlen($txt); $i++) { $md5 = $txt[$i]; $tmp .= $txt[++$i] ^ $md5; } return $tmp; } private function __key($txt,$encrypt_key) { $encrypt_key = md5($encrypt_key); $ctr = 0; $tmp = ''; for($i = 0; $i < strlen($txt); $i++) { $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr; $tmp .= $txt[$i] ^ $encrypt_key[$ctr++]; } return $tmp; } public function md520($str){ return substr(md5($str.COMSTR),8,20); } public function __destruct() { $this -> crypt_key = null; } } ?>
程序执行时间类(protime.class.php)
startTime=$startTime; $this->stopTime=$stopTime; } function proStart(){ $this->startTime=microtime(true); } function proStop(){ $this->stopTime=microtime(true); } function proTime(){ return round($this->stopTime-$this->startTime,4); } } ?>
验证码类(validatecode.class.php)
width=$width; $this->height=$height; $this->num=$num; $this->valCode=$this->createCode(); $this->pxNum=floor($this->width*$this->height/40); } private function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1) { /* 下面两行只在线段直角相交时好使 imagesetthickness($image, $thick); return imageline($image, $x1, $y1, $x2, $y2, $color); */ if ($thick == 1) { return imageline($image, $x1, $y1, $x2, $y2, $color); } $t = $thick / 2 - 0.5; if ($x1 == $x2 || $y1 == $y2) { return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color); } $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q $a = $t / sqrt(1 + pow($k, 2)); $points = array( round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a), round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a), round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a), round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a), ); imagefilledpolygon($image, $points, 4, $color); return imagepolygon($image, $points, 4, $color); } //创建背景图片 private function createImg(){ $this->img=imagecreatetruecolor($this->width,$this->height); $bgColor=imagecolorallocate($this->img,245,245,245); imagefill($this->img,0,0,$bgColor); $border=imagecolorallocate($this->img, 221, 221, 221); imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $border); } //设置干扰元素 private function setPx(){ $pxColor=imagecolorallocate($this->img,1,95,182); $this->imagelinethick($this->img,0,rand(5,$this->height-5),$this->width/5,rand(5,$this->height-5),$pxColor,2); $this->imagelinethick($this->img,$this->width/5+10,rand(5,$this->height-5),$this->width,rand(5,$this->height-5),$pxColor,2); } //创建随机字符 private function createCode(){ $str=''; $code='23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; for($i=0;$i<$this->num;$i++){ $str.=$code{rand(0,strlen($code)-1)}; } return $str; } //输出文本 private function outText(){ for($i=0;$i<$this->num;$i++){ $color=imagecolorallocate($this->img,1,95,182); $x=$this->num*5*$i+10; $y=rand(30,$this->height-5); imagettftext($this->img,35,rand(-30,30),$x,$y,$color,'simhei.ttf',$this->valCode{$i}); } } //输出图像 private function outImg(){ if(imagetypes() & IMG_GIF){ header("Content-type:gif"); imagegif($this->img); }else if(imagetypes() & IMG_PNG){ header("Content-type:png"); imagepng($this->img); }else{ header("Content-type:jpeg"); imagejpeg($this->img); } } //显示图像 function viewImg(){ $this->createImg(); $this->setPx(); $this->outText(); $this->outImg(); } //获取产生的随机数 function getCode(){ return $this->valCode; } //析构函数,销毁图像资源 function __destruct(){ imagedestroy($this->img); } } session_start(); $img=new ValidateCode(); $img->viewImg(); $_SESSION['vcode']=$img->getCode(); ?>
无刷新分页类(ajaxpage.class.php)
pageSize=$pageSize; $this->rowCount=$rowCount; $this->uri=$this->getUri($path); $this->and=strlen(strstr($this->uri,'?'))>1?'&':''; $this->pageCount=ceil($this->rowCount/$this->pageSize); $this->pageNow=!empty($_GET['p'])?$_GET['p']:1; } private function getUri($path){ $url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$path; $parse=parse_url($url); if(isset($parse["query"])){ parse_str($parse['query'],$params); unset($params["p"]); $url=$parse['path'].'?'.http_build_query($params); } return $url; } private function firstPage(){ $html=''; if($this->pageNow!=1&&$this->pageCount>1){ $html.="
首页
"; } return $html; } private function lastPage(){ $html=''; if($this->pageNow!=$this->pageCount&&$this->pageCount>1){ $html.="
pageCount,$_GET[aid])\">尾页
"; } return $html; } private function prePage(){ $html=''; if($this->pageNow!=1&&$this->pageCount>1){ $html.="
pageNow-1,$_GET[aid])\">上一页
"; } return $html; } private function nextPage(){ $html=''; if($this->pageNow!=$this->pageCount&&$this->pageCount>1){ $html.="
pageNow+1,$_GET[aid])\">下一页
"; } return $html; } private function pageList(){ $html=''; if($this->pageCount>1){ if($this->pageNow<=ceil($this->listNum/2)){ if($this->pageCount<$this->listNum) $max=$this->pageCount; else $max=$this->listNum; for($i=1;$i<=$max;$i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } }else if($this->pageNow>($this->pageCount-$this->listNum)){ for($i=($this->pageCount-$this->listNum+1); $i<=$this->pageCount; $i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } }else{ if($this->pageCount<(floor($this->listNum/2)+$this->pageNow)) $max=$this->pageCount; else $max=floor($this->listNum/2)+$this->pageNow; for($i=$this->pageNow-floor($this->listNum/2); $i<=$max; $i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } } } return $html; } private function pageInfo(){ return $this->pageNow.'/'.$this->pageCount.'页'; } function limitPage(){ $page=$this->pageSize*($this->pageNow-1); return 'limit '.$page.','.$this->pageSize; } function getPageInfo($display=array(0,1,2,3,4,5)){ if($this->pageNow<=$this->pageCount){ $str[0]=$this->firstPage(); $str[1]=$this->prePage(); $str[2]=$this->pageList(); $str[3]=$this->nextPage(); $str[4]=$this->lastPage(); $str[5]=$this->pageInfo(); $html=''; foreach($display as $index){ $html.=$str[$index]; } return $html; } } }
示例:
//查询及实例化 $total=mysql_num_rows($result); //查询总条数 $p=new AjaxPage(5,$total); //实例化 //显示 $p->getPageInfo(array(0,1,2,3,4,5))
分页类(page.class.php)
pageSize=$pageSize; $this->rowCount=$rowCount; $this->uri=$this->getUri($path); $this->and=strlen(strstr($this->uri,'?'))>1?'&':''; $this->pageCount=ceil($this->rowCount/$this->pageSize); $this->pageNow=!empty($_GET['p'])?$_GET['p']:1; } private function getUri($path){ $url=$_SERVER["REQUEST_URI"].(strpos($_SERVER["REQUEST_URI"], '?')?'':"?").$path; $parse=parse_url($url); if(isset($parse["query"])){ parse_str($parse['query'],$params); unset($params["p"]); $url=$parse['path'].'?'.http_build_query($params); } return $url; } private function firstPage(){ $html=''; if($this->pageNow!=1&&$this->pageCount>1){ $html.="
首页
"; } return $html; } private function lastPage(){ $html=''; if($this->pageNow!=$this->pageCount&&$this->pageCount>1){ $html.="
尾页
"; } return $html; } private function prePage(){ $html=''; if($this->pageNow!=1&&$this->pageCount>1){ $html.="
<< 上一页
"; } return $html; } private function nextPage(){ $html=''; if($this->pageNow!=$this->pageCount&&$this->pageCount>1){ $html.="
下一页 >>
"; } return $html; } //显示页数列表,显示的最大页数根据$this->listNum值而定 private function pageList(){ $html=''; if($this->pageCount>1){ if($this->pageNow<=ceil($this->listNum/2)){ if($this->pageCount<$this->listNum) $max=$this->pageCount; else $max=$this->listNum; for($i=1;$i<=$max;$i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } }else if($this->pageNow>($this->pageCount-$this->listNum)){ for($i=($this->pageCount-$this->listNum+1); $i<=$this->pageCount; $i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } }else{ if($this->pageCount<(floor($this->listNum/2)+$this->pageNow)) $max=$this->pageCount; else $max=floor($this->listNum/2)+$this->pageNow; for($i=$this->pageNow-floor($this->listNum/2); $i<=$max; $i++){ if($i==$this->pageNow){ $html.='
'.$i.'
'; }else{ $html.="
".$i."
"; } } } } return $html; } private function pageInfo(){ if($this->pageCount>0) return $this->pageNow.'/'.$this->pageCount.'页'; } function limitPage(){ $page=$this->pageSize*($this->pageNow-1); return 'limit '.$page.','.$this->pageSize; } function getPageInfo($display=array(0,1,2,3,4,5)){ if($this->pageNow<=$this->pageCount){ $str[0]=$this->firstPage(); $str[1]=$this->prePage(); $str[2]=$this->pageList(); $str[3]=$this->nextPage(); $str[4]=$this->lastPage(); $str[5]=$this->pageInfo(); $html=''; foreach($display as $index){ $html.=$str[$index]; } return $html; } } }
非法校验类(validate.class.php)
mysqli类(db.class.php)
mysqli=@new mysqli(HOST,USER,PASSWD,DB); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); $this->mysqli=FALSE; exit(); } } /** * 功能描述:清空所有私有属性的值,在每次增删改查执行成功后调用 * 以便不干扰下一次的数据表操作 */ private function clear(){ $this->tableName=$this->insert_value=$this->set_arr=$this->select_val=$this->order=$this->group=$this->where_case=$this->limit_str=$this->bind_param=$this->types=''; } /** * 参数:表名 类型:字符串 * 为私有属性$tableName赋值 以确定要插入数据的表 * 返回值为$this */ public function INSERT_INTO($tableName){ $this->tableName=PRETABLE.$tableName; return $this; } /** * 参数:表名 类型:字符串 * 为私有属性$tableName赋值 以确定要查询数据的表 * 返回值为$this */ public function FROM($tableName){ $this->tableName=PRETABLE.$tableName; return $this; } /** * 参数:表名 类型:字符串 * 为私有属性$tableName赋值 以确定要删除数据的表 * 返回值为$this */ public function DELETE_FROM($tableName){ $this->tableName=PRETABLE.$tableName; return $this; } /** * 参数:需要向数据表中插入的数据 类型:数组 * 返回值:$this */ public function VALUES($arr=array()){ $this->bind_param=$arr; return $this; } /** * 参数:$key=>数据表中的字段名 $value=>更新的新值 类型:数组 * 返回值:$this */ public function SET($arr=array()){ $this->set_arr=$arr; return $this; } /** * 功能描述:运算关系转换,为WHERE()、OR()、AND()函数辅助函数 * 参数:1、需拆分的字符串 2、连接条件 可空 * */ private function setCase($str, $case=''){ if(strpos($str, '>=')!==false){ $arr=explode('>=', $str); $this->where_case.=$case.$arr[0].'>=? '; array_push($this->bind_param, $arr[1]); $this->types.='s'; }else if(strpos($str, '<=')!==false){ $arr=explode('<=', $str); $this->where_case.=$case.$arr[0].'<=? '; array_push($this->bind_param, $arr[1]); $this->types.='s'; }else if(strpos($str, '!=')!==false){ $arr=explode('!=', $str); $this->where_case.=$case.$arr[0].'!=? '; array_push($this->bind_param, $arr[1]); $this->types.='s'; }else if(strpos($str, '=')!==false){ $arr=explode('=', $str); $this->where_case.=$case.$arr[0].'=? '; array_push($this->bind_param, $arr[1]); $this->types.='s'; }else if(strpos($str, '>')!==false){ $arr=explode('>', $str); $this->where_case.=$case.$arr[0].'>? '; array_push($this->bind_param, $arr[1]); $this->types.='s'; }else if(strpos($str, '<')!==false){ $arr=explode('<', $str); $this->where_case.=$case.$arr[0].' '; array_push($this->bind_param, $arr[1]); $this->types.='s'; } } /** * 参数:WHERE字句紧跟查询条件 类型:数组 * 返回值:$this */ public function WHERE($case, $arr=array()){ $this->setCase($case); if(!empty($arr)){ foreach($arr as $key=>$val){ if($key=='AND'||$key=='and'){ $this->setCase($val, 'AND '); }else if($key=='OR'||$key=='or'){ $this->setCase($val, 'OR '); } } } return $this; } /** * 参数:定义数据数据查询的排序方式 类型:字符串 * 返回值:$this */ public function ORDER_BY($val){ $this->order=$val; return $this; } /** * 参数:定义数据数据分组查询的排序方式 类型:字符串 * 返回值:$this */ public function GROUP_BY($val){ $this->group=$val; return $this; } /** * 参数:定义数据查询的限制条数 类型:字符串 * 返回值:$this */ public function LIMIT($val){ $this->limit_str=$val; return $this; } /** * 用户执行一组SQL语句 * 1、参数:一条SQL语句 数据类型:字符串 * 2、参数:一组SQL语句 数据类型:数组 * 返回值:无 */ public function execs($sqls){ $result=FALSE; if(is_array($sqls)){ $i=0; foreach($sqls as $sql){ if($this->mysqli->query($sql)){ $i++; } } if($i===count($sqls)) $result=TRUE; }else{ if($this->mysqli->query($sqls)){ $result=TRUE; } } return $result; } /** * 功能描述:返回操作影响的行数 * 为INSERT()、DELETE()、UPDATE()函数共用 */ private function affected_rows($sql, $bind_val, $val_type){ if($stmt=$this->mysqli->prepare($sql)){ $this->_bindParams($stmt,$bind_val,(array)$val_type); if($stmt->execute()){ $this->clear(); return $stmt->affected_rows; } } } /** * 功能描述:插入一条记录 * 返回值:影响行数 */ public function INSERT(){ $tabVal=''; //表明后所跟字符串 $strVal=''; //value值 foreach($this->bind_param as $key=>$val){ $tabVal.=$key.','; $strVal.='?,'; $this->types.='s'; } $tabVal=substr($tabVal,0,strlen($tabVal)-1); $strVal=substr($strVal,0,strlen($strVal)-1); $sql="INSERT INTO $this->tableName($tabVal) values ($strVal)"; return $this->affected_rows($sql, $this->bind_param, $this->types); } /** * 1、$tableName 值不为空 * 参数:表名 类型:字符串 * 为私有属性$tableName赋值 以确定要更新数据的表 * 返回值为$this * 2、$tableName 值为空 * 功能描述:更新一条记录 * 返回值:影响的行数 */ public function UPDATE($tableName=''){ if(!empty($tableName)){ $this->tableName=PRETABLE.$tableName; return $this; }else{ $setVal=''; //set字串 foreach($this->set_arr as $key=>$val){ $setVal.=$key.'=?,'; $this->types.='s'; //默认所有数据的类型为字符串类型 } if(!empty($this->where_case)){ $this->where_case='WHERE '.$this->where_case; } $setVal=substr($setVal,0,strlen($setVal)-1); $sql="UPDATE $this->tableName SET $setVal $this->where_case"; //echo $sql; $arr=array_merge($this->set_arr, $this->bind_param); //print_r($arr); return $this->affected_rows($sql, $arr, $this->types); } } /** * 功能描述:删除一条记录 * 返回值:影响函数 */ public function DELETE(){ if(!empty($this->where_case)){ $this->where_case='WHERE '.$this->where_case; } $sql="DELETE FROM $this->tableName $this->where_case"; //echo $sql; //print_r($this->bind_param); return $this->affected_rows($sql, $this->bind_param, $this->types); } /** * 1、$val 值不为空 * 参数:查询条件 类型:数组[普通查询] 字符串[聚集函数查询] * 为私有属性$select_val赋值 * 返回值为$this * 2、$val 值为空 * 功能描述:查询一组数据,根据$select_val的数据类型,确定使用普通查询或者聚集函数查询 * 返回值:查询结果 * */ public function SELECT($val=''){ if(!empty($val)){ $this->select_val=$val; return $this; }else{ //执行查询语句 $result=array(); //查询返回二维数组 $select_str=''; //需要查询字段 $fields=array(); //绑定的结果集 if(!empty($this->where_case)){ $this->where_case='WHERE '.$this->where_case; } if(!empty($this->order)){ $this->order='ORDER BY '.$this->order; } if(!empty($this->group)){ $this->group='GROUP BY '.$this->group; } if(!empty($this->limit_str)){ $this->limit_str='LIMIT '.$this->limit_str; } if(is_array($this->select_val)){ //普通查询 foreach($this->select_val as $key=>$value){ $select_str.=$value.','; $fields[$value]=''; } $select_str=rtrim($select_str, ', '); }else{ //聚集函数查询 $select_str=$this->select_val; } $sql="SELECT $select_str FROM $this->tableName $this->where_case $this->order $this->group $this->limit_str"; //echo $sql; if($stmt=$this->mysqli->prepare($sql)){ if(!empty($this->where_case)){ $this->_bindParams($stmt, $this->bind_param, (array)$this->types); } $stmt->execute(); $field=$this->toBtArray($fields); if(is_array($this->select_val)){ call_user_func_array(array($stmt,'bind_result'), $field); }else{ $stmt->bind_result($result); } while($stmt->fetch()){ if(is_array($this->select_val)){ $a=array(); foreach($field as $key=>$value){ $a[$key]=$value; } $result[]=$a; } } } $this->clear(); return $result; } } /** * 格式化数组 * php5.3后问题 */ private function toBtArray(&$arr){ $fields=array(); //结果集绑定数组 foreach($arr as $key=>$value){ $fields[$key]=&$arr[$key]; } return $fields; } /** * 封装mysqli_bind_param函数 * 参数类型为引用传递 * 第一个参数:绑定对象 * 第二个参数:绑定值,类型为数组 * 第三个参数:绑定值类型 * 变量绑定成功返回真 */ private function _bindParams(&$stmt,$valsArray=array(),$valsType=array()){ $result=FALSE; if (count($valsArray) > 0){ $params = array_merge($valsType, $valsArray); $tmpArray = array(); foreach ($params as $key => $value){ $tmpArray[$key] = &$params[$key]; } $result = call_user_func_array(array($stmt,'bind_param'), $tmpArray); } return $result; } //关闭数据库连接 private function close(){ if($this->mysqli){ $this->mysqli->close(); } $this->mysqli=FALSE; } //析构方法、自动关闭连接 public function __destruct(){ $this->close(); } }
文件上传类(fileupload.class.php)
path=$path; $this->type=$type; $this->maxSize=$maxSize; } //文件上传方法 function upload($name){ $result=false; $errorNum=$_FILES[$name]['error']; $types=explode('.',$_FILES[$name]['name']); $this->fileType=strtolower($types[count($types)-1]); $this->fileName=$_FILES[$name]['name']; $this->tempName=$_FILES[$name]['tmp_name']; $this->fileSize=$_FILES[$name]['size']; if($this->checkPath()){ if($this->checkFileSize()&&$this->checkFileType()){ $this->setNewFileName(); if($this->getNewFile()){ $result=true; } } } if($result==false) $this->errorMsg=$this->getError(); return $result; } //获取上传后的新文件名 function getNewFileName(){ return $this->newFileName; } //获取上传过程中的错误信息 function getError(){ $errorStr="
文件{$this->fileName}上传出错
"; switch($this->errorNum){ case 1: $errorStr.='上传的文件超过了php.ini中upload_max_filesize选项限制的值'; break; case 2: $errorStr.='上传文件的大小超过了HTML表单中MAX_FILE_SIZE选项指定的值'; break; case 3: $errorStr.='文件只有部分被上传'; break; case 4: $errorStr.='没有文件被上传'; break; case -1: $errorStr.='文件类型不允许'; break; case -2: $errorStr.="文件过大,超出了允许上传的最大文件尺寸"; break; case -3: $errorStr.='文件上传目录创建失败,请从新指定'; break; case -4: $errorStr.='文件拷贝失败'; break; default: $errorStr.='未知的文件上传错误'; } return $errorStr; } //辅助上传方法,检查文件上传路径 private function checkPath(){ if(!file_exists($this->path)){ if(!@mkdir($this->path,0755)){ $this->errorNum=-3; return false; } } return true; } //辅助上传方法,检查文件后缀名 private function checkFileType(){ if(!in_array($this->fileType,$this->type)){ $this->errorNum=-1; return false; } return true; } //辅助上传方法,检查文件大小 private function checkFileSize(){ if($this->fileSize>$this->maxSize){ $this->errorNum=-2; return false; } return true; } /** * 辅助上传方法,设置新的随机文件名 * 文件名格式为:年月日时分秒连接三位随机数,长度为21个字符 */ private function setNewFileName(){ $fname=date('YmdHis').rand(100,999); $this->newFileName=$fname.'.'.$this->fileType; } //辅助上传方法,将文件从临时目录拷贝到指定的上传目录,并指定新文件名 private function getNewFile(){ $this->path=rtrim($this->path,'/').'/'.$this->newFileName; if(!move_uploaded_file($this->tempName,$this->path)){ $this->errorNum=-4; return false; } return true; } }
示例:(upload.php)
upload('pic')){ echo $file->getNewFileName(); }else{ echo $file->getError(); } ?>
图片处理类(img.class.php)
path=rtrim($path,'/').'/'; } /** * 对图片进行缩放 * 参数对应:文件名 缩放后宽度 缩放后高度 缩放后图片名前缀 */ function thumb($name,$width,$height,$pre="th_"){ if(file_exists($this->path.$name)){ $imgInfo=$this->getInfo($name); $img=$this->getImg($name,$imgInfo); $newSize=$this->getNewSize($name,$width,$height,$imgInfo); $newImg=$this->getNewInfo($img,$newSize,$imgInfo); return $this->createNewImage($newImg, $pre.$name, $imgInfo); }else{ echo '图片'.$this->path.$name.'不存在,请检查文件名及路径是否填写正确'; } } //辅助图片处理,获取图片的宽、高、类型属性 private function getInfo($name){ $temp=getImageSize($this->path.$name); $imgInfo['width']=$temp[0]; $imgInfo['height']=$temp[1]; $imgInfo['type']=$temp[2]; return $imgInfo; } //辅助图片处理,获取创建的图片资源 private function getImg($name,$imgInfo){ $src=$this->path.$name; switch($imgInfo['type']){ case 1: $img=imagecreatefromgif($src); break; case 2: $img=imagecreatefromjpeg($src); break; case 3: $img=imagecreatefrompng($src); break; } return $img; } //辅助图片处理,获取创建的图片资源 private function getNewSize($name,$width,$height,$imgInfo){ $newSize['width']=$imgInfo['width']; $newSize['height']=$imgInfo['height']; if($width<$imgInfo['width']){ $newSize['width']=$width; } if($height<$imgInfo['height']){ $newSize['height']=$height; } if($imgInfo["width"]*$newSize["width"] > $imgInfo["height"] * $newSize["height"]){ $newSize["height"]=round($imgInfo["height"]*$newSize["width"]/$imgInfo["width"]); }else{ $newSize["width"]=round($imgInfo["width"]*$newSize["height"]/$imgInfo["height"]); } print_r($newSize); return $newSize; } //辅助图片处理,获取缩放的图片资源 private function getNewInfo($img,$newSize,$imgInfo){ $newImg=imagecreatetruecolor($newSize['height'],$newSize['height']); $otsc=imagecolortransparent($img); if($otsc >=0 && $otsc <= imagecolorstotal($img)){ $tran=imagecolorsforindex($img, $otsc); $newt=imagecolorallocate($newImg, $tran["red"], $tran["green"], $tran["blue"]); imagefill($newImg, 0, 0, $newt); imagecolortransparent($newImg, $newt); } imagecopyresized($newImg, $img, 0, 0, 0, 0, $newSize["width"], $newSize["height"], $imgInfo["width"], $imgInfo["height"]); imagedestroy($img); return $newImg; } //辅助图片处理,创建新的图片 private function createNewImage($newImg, $newName, $imgInfo){ switch($imgInfo["type"]){ case 1://gif $result=imageGif($newImg, $this->path.$newName); break; case 2://jpg $result=imageJPEG($newImg, $this->path.$newName); break; case 3://png $return=imagepng($newImg, $this->path.$newName); break; } imagedestroy($newImg); return $newName; } /** * 对图片加水印 * 参数对应:需水印图片 水印图片 加水印后图片名前缀 */ function waterMark($name,$wname,$pre="wa_"){ if(file_exists($this->path.$name)){ if(file_exists($this->path.$wname)){ $info=$this->getInfo($name); $winfo=$this->getInfo($wname); if($p=$this->getPosition($info,$winfo)){ $img=$this->getImg($name,$info); $wImg=$this->getImg($wname,$winfo); imagecopy($img, $wImg, $p["x"], $p["y"], 0, 0, $winfo["width"], $winfo["height"]); imagedestroy($wImg); return $this->createNewImage($img,$pre.$name,$info); }else{ echo '水印图片尺寸大于原图片尺寸'; } }else{ echo '水印图片'.$this->path.$wname.'不存在,请检查文件名及路径是否填写正确'; } }else{ echo '图片'.$this->path.$name.'不存在,请检查文件名及路径是否填写正确'; } } //辅助图片处理,获取水印图片应处坐标 private function getPosition($info,$winfo){ if($info['width']<$winfo['width']||$info['height']<$winfo['height']){ return false; } $x=$info['width']-$winfo['width']; $y=$info['height']-$winfo['height']; return array('x'=>$x,'y'=>$y); } /** * 图片剪切函数 * 对应参数:原图片 X坐标 Y坐标 宽度 高度 */ function cut($name,$x,$y,$width,$height,$pre='cx_'){ $imgInfo=$this->getInfo($name); $img=$this->getImg($name,$imgInfo); $newImg=imagecreatetruecolor($width,$height); imagecopyresampled($newImg,$img,0,0,$x,$y,$width,$height,$width,$height); return $this->createNewImage($newImg, $pre.$name, $imgInfo); } }
示例:(img.php)
cut('20121025184159795.jpg',0,0,500,300); ?>