~~~
<?php
header("Content-type:text/html;charset=utf-8");
/*
* 定義發送短信驗證碼方法
* 使用php自帶的SoapClient類來獲取短信接口數據
* 該接口的自動發送驗證碼方法是Submit()方法
*
*/
function phonecode($phone){
$soap=new SoapClient('http://101.201.52.251:7801/sms?wsdl');
$code='';
for($i=0;$i<6;$i++){
$code.=rand(0,9);//生成6位隨機字符的驗證碼
}
$str="【XXXX】網站注冊驗證碼:".$code.",十五分鐘內輸入有效。如非本人操作,請忽略此消息。";
$res=$soap->Submit("210007","XXXXX","XXXX",$str,$phone);
return $code;
}
/**
* 判斷用戶輸入是否存在敏感詞
* 需要在ThinkPHP的ORG擴展文件夾中,添加敏感詞類文件SensitiveFilter.php
*
*/
function sensitive($content){
//$arr=C('SENSITIVE');
import("ORG.SensitiveFilter");
$arr=SensitiveFilter::getWord();
foreach ($arr as $v) {
if (false !== strstr($content, $v)){
$content=str_replace($v,'***',$content);//內容中存在敏感詞庫中的敏感詞,則將敏感詞用*替換
}
}
return $content;
}
/**
*傳遞數據以易于閱讀的樣式格式化后輸出
*
*/
function p($data){
// 定義樣式
$str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
// 如果是boolean或者null直接顯示文字;否則print
if (is_bool($data)) {
$show_data=$data ? 'true' : 'false';
}elseif (is_null($data)) {
$show_data='null';
}else{
$show_data=print_r($data,true);
}
$str.=$show_data;
$str.='</pre>';
echo $str;
}
/**
* app 圖片上傳
* $path 上傳圖圖片的路徑
* $maxSize 上傳圖片的大小控制
* @return string 上傳后的圖片名
*
*/
function app_upload_image($path,$maxSize=52428800){
ini_set('max_execution_time', '0');
// 去除兩邊的/
$path=trim($path,'.');
$path=trim($path,'/');
$config=array(
'rootPath' =>'./', //文件上傳保存的根路徑
'savePath' =>'./'.$path.'/',
'exts' => array('jpg', 'gif', 'png', 'jpeg','bmp'),
'maxSize' => $maxSize,
'autoSub' => true,
);
$upload = new \Think\Upload($config);// 實例化上傳類
$info = $upload->upload();
if($info) {
foreach ($info as $k => $v) {
$data[]=trim($v['savepath'],'.').$v['savename'];
}
return $data;
}
}
/**
* 阿里云OSS操作
* 實例化阿里云oos
* @return object 實例化得到的對象
*
*/
function new_oss(){
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$oss=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
return $oss;
}
/**
* 阿里云OSS操作
* 上傳Object
* key 用專題的id標識本片專題
* $str 是要上傳的專題的內容
*
*/
function uploadObject($str,$id){
$id='M_Upload/zhuanti/content/'.$id;
$accessKeyId=C('ALIOSS_CONFIG.KEY_ID');
$accessKeySecret=C('ALIOSS_CONFIG.KEY_SECRET');
$endpoint=C('ALIOSS_CONFIG.END_POINT');
$bucket=C('ALIOSS_CONFIG.BUCKET');
//$oss->putObject($bucket,$id,$str);
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$ossClient=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
try {
//$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$ossClient->putObject($bucket, $id, $str);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
return $id;
}
/**
* 阿里云OSS操作
* 上傳Object
* key 用專題的id標識本片專題
* $str 是要上傳的專題的內容
*
*/
function downObject($id){
$accessKeyId=C('ALIOSS_CONFIG.KEY_ID');
$accessKeySecret=C('ALIOSS_CONFIG.KEY_SECRET');
$endpoint=C('ALIOSS_CONFIG.END_POINT');
$bucket=C('ALIOSS_CONFIG.BUCKET');
//$oss->putObject($bucket,$id,$str);
try {
vendor('Alioss.autoload');
$config=C('ALIOSS_CONFIG');
$ossClient=new \OSS\OssClient($config['KEY_ID'],$config['KEY_SECRET'],$config['END_POINT']);
$content=$ossClient->getObject($bucket, $id);
print("object content: " . $content);
} catch (OssException $e) {
print $e->getMessage();
}
}
/**
* 阿里云OSS操作
* 上傳文件到阿里云OSS并刪除本地文件
* @param string $path 文件路徑
* @return bollear 是否上傳
*
*/
function oss_upload($path){
// 獲取bucket名稱
$bucket=C('ALIOSS_CONFIG.BUCKET');
// 先統一去除左側的.或者/ 再添加./
$oss_path=ltrim($path,'./');
$path='./'.$oss_path;
if (file_exists($path)) {
// 實例化oss類
$oss=new_oss();
// 上傳到oss
$oss->uploadFile($bucket,$oss_path,$path);
// 如需上傳到oss后 自動刪除本地的文件 則刪除下面的注釋
unlink($path);
return true;
}
return false;
}
/**
* 阿里云OSS操作
* 刪除阿里云OSS上指定文件
* @param string $object 文件路徑 例如刪除 /Public/README.md文件 傳Public/README.md 即可
*
*/
function oss_delet_object($object){
// 實例化oss類
$oss=new_oss();
// 獲取bucket名稱
$bucket=C('ALIOSS_CONFIG.BUCKET');
$test=$oss->deleteObject($bucket,$object);
}
/**
* 阿里云OSS操作
* 獲取完整網絡連接
* @param string $path 文件路徑
* @return string http連接
*
*/
function get_url($path){
// 如果是空;返回空
if (empty($path)) {
return '';
}
// 如果已經有http直接返回
if (strpos($path, 'http://')!==false) {
return $path;
}
// 判斷是否使用了oss
$alioss=C('ALIOSS_CONFIG');
if (empty($alioss['KEY_ID'])) {
return 'http://'.$_SERVER['HTTP_HOST'].$path;
}else{
$path=ltrim($path,'.');
return 'http://'.$alioss['BUCKET'].'.'.$alioss['END_POINT'].$path;
}
}
/**
* app 視頻上傳
* @return string 上傳后的視頻名
*
*/
function app_upload_video($path,$maxSize=52428800){
ini_set('max_execution_time', '0');
// 去除兩邊的/
$path=trim($path,'.');
$path=trim($path,'/');
$config=array(
'rootPath' =>'./', //文件上傳保存的根路徑
'savePath' =>'./'.$path.'/',
'exts' => array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack'),
'maxSize' => $maxSize,
'autoSub' => true,
);
$upload = new \Think\Upload($config);// 實例化上傳類
$info = $upload->upload();
if($info) {
foreach ($info as $k => $v) {
$data[]=trim($v['savepath'],'.').$v['savename'];
}
return $data;
}
}
/**
* 返回文件格式
* @param string $str 文件名
* @return string 文件格式
*
*/
function file_format($str){
// 取文件后綴名
$str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
// 圖片格式
$image=array('webp','jpg','png','ico','bmp','gif','tif','pcx','tga','bmp','pxc','tiff','jpeg','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','hdri');
// 視頻格式
$video=array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack');
// 壓縮格式
$zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
// 文檔格式
$text=array('exe','doc','ppt','xls','wps','txt','lrc','wfs','torrent','html','htm','java','js','css','less','php','pdf','pps','host','box','docx','word','perfect','dot','dsf','efe','ini','json','lnk','log','msi','ost','pcs','tmp','xlsb');
// 匹配不同的結果
switch ($str) {
case in_array($str, $image):
return 'image';
break;
case in_array($str, $video):
return 'video';
break;
case in_array($str, $zip):
return 'zip';
break;
case in_array($str, $text):
return 'text';
break;
default:
return 'image';
break;
}
}
/**
* 發送友盟推送消息
* @param integer $uid 用戶id
* @param string $title 推送的標題
* @return boolear 是否成功
*
*/
function umeng_push($uid,$title){
// 獲取token
$device_tokens=D('OauthUser')->getToken($uid,2);
// 如果沒有token說明移動端沒有登錄;則不發送通知
if (empty($device_tokens)) {
return false;
}
// 導入友盟
Vendor('Umeng.Umeng');
// 自定義字段 根據實際環境分配;如果不用可以忽略
$status=1;
// 消息未讀總數統計 根據實際環境獲取未讀的消息總數 此數量會顯示在app圖標右上角
$count_number=1;
$data=array(
'key'=>'status',
'value'=>"$status",
'count_number'=>$count_number
);
// 判斷device_token 64位表示為蘋果 否則為安卓
if(strlen($device_tokens)==64){
$key=C('UMENG_IOS_APP_KEY');
$timestamp=C('UMENG_IOS_SECRET');
$umeng=new \Umeng($key, $timestamp);
$umeng->sendIOSUnicast($data,$title,$device_tokens);
}else{
$key=C('UMENG_ANDROID_APP_KEY');
$timestamp=C('UMENG_ANDROID_SECRET');
$umeng=new \Umeng($key, $timestamp);
$umeng->sendAndroidUnicast($data,$title,$device_tokens);
}
return true;
}
/**
* 返回用戶id
* @return integer 用戶id
*
*/
function get_uid(){
return $_SESSION['user']['id'];//根據自己登錄的時候保存的SESSION元素而定
}
/**
* 返回iso、Android、ajax的json格式數據
* @param array $data 需要發送到前端的數據
* @param string $error_message 成功或者錯誤的提示語
* @param integer $error_code 狀態碼: 0:成功 1:失敗
* @return string json格式的數據
*
*/
function ajax_return($data='',$error_message='成功',$error_code=1){
$all_data=array(
'error_code'=>$error_code,
'error_message'=>$error_message,
);
if ($data!=='') {
$all_data['data']=$data;
// app 禁止使用和為了統一字段做的判斷
$reserved_words=array('id','title','price','product_title','product_id','product_category','product_number');
foreach ($reserved_words as $k => $v) {
if (array_key_exists($v, $data)) {
echo 'app不允許使用【'.$v.'】這個鍵名 —— 此提示是function.php 中的ajax_return函數返回的';
die;
}
}
}
// 如果是ajax或者app訪問;則返回json數據 pc訪問直接p出來
echo json_encode($all_data);
exit(0);
}
/**
* 檢測是否登錄
* @return boolean 是否登錄
*
*/
function check_login(){
if (!empty($_SESSION['user']['id'])){
return true;
}else{
return false;
}
}
/**
* 根據配置項獲取對應的key和secret
* @return array key和secret
*
*/
function get_rong_key_secret(){
// 判斷是需要開發環境還是生產環境的key
if (C('RONG_IS_DEV')) {
$key=C('RONG_DEV_APP_KEY');
$secret=C('RONG_DEV_APP_SECRET');
}else{
$key=C('RONG_PRO_APP_KEY');
$secret=C('RONG_PRO_APP_SECRET');
}
$data=array(
'key'=>$key,
'secret'=>$secret
);
return $data;
}
/**
* 獲取融云token
* @param integer $uid 用戶id
* @return integer token
*
*/
function get_rongcloud_token($uid){
// 從數據庫中獲取token
$token=D('OauthUser')->getToken($uid,1);
// 如果有token就返回
if ($token) {
return $token;
}
// 獲取用戶昵稱和頭像
$user_data=M('Users')->field('username,avatar')->getById($uid);
// 用戶不存在
if (empty($user_data)) {
return false;
}
// 獲取頭像url格式
$avatar=get_url($user_data['avatar']);
// 獲取key和secret
$key_secret=get_rong_key_secret();
// 實例化融云
$rong_cloud=new \Org\Xb\RongCloud($key_secret['key'],$key_secret['secret']);
// 獲取token
$token_json=$rong_cloud->getToken($uid,$user_data['username'],$avatar);
$token_array=json_decode($token_json,true);
// 獲取token失敗
if ($token_array['code']!=200) {
return false;
}
$token=$token_array['token'];
$data=array(
'uid'=>$uid,
'type'=>1,
'nickname'=>$user_data['username'],
'head_img'=>$avatar,
'access_token'=>$token
);
// 插入數據庫
$result=D('OauthUser')->addData($data);
if ($result) {
return $token;
}else{
return false;
}
}
/**
* 更新融云頭像
* @param integer $uid 用戶id
* @return boolear 操作是否成功
*
*/
function refresh_rongcloud_token($uid){
// 獲取用戶昵稱和頭像
$user_data=M('Users')->field('username,avatar')->getById($uid);
// 用戶不存在
if (empty($user_data)) {
return false;
}
$avatar=get_url($user_data['avatar']);
// 獲取key和secret
$key_secret=get_rong_key_secret();
// 實例化融云
$rong_cloud=new \Org\Xb\RongCloud($key_secret['key'],$key_secret['secret']);
// 更新融云用戶頭像
$result_json=$rong_cloud->userRefresh($uid,$user_data['username'],$avatar);
$result_array=json_decode($result_json,true);
if ($result_array['code']==200) {
return true;
}else{
return false;
}
}
/**
* 刪除指定的標簽和內容
* @param array $tags 需要刪除的標簽數組
* @param string $str 數據源
* @param string $content 是否刪除標簽內的內容 0保留內容 1不保留內容
* @return string
*
*/
function strip_html_tags($tags,$str,$content=0){
if($content){
$html=array();
foreach ($tags as $tag) {
$html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';
}
$data=preg_replace($html,'',$str);
}else{
$html=array();
foreach ($tags as $tag) {
$html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
}
$data=preg_replace($html, '', $str);
}
return $data;
}
/**
* 傳遞ueditor生成的內容獲取其中圖片的路徑
* @param string $str 含有圖片鏈接的字符串
* @return array 匹配的圖片數組
*
*/
function get_ueditor_image_path($str){
//$preg='/\/Upload\/zhuanti\/u(m)?editor\/\d*\/\d*\.[jpg|jpeg|png|bmp]*/i';
$preg='<img(.*?)src=\"(.*?)\"(.*?)/>';
preg_match_all($preg, $str,$data);
return current($data);
}
/**
* 字符串截取,支持中文和其他編碼
* @param string $str 需要轉換的字符串
* @param string $start 開始位置
* @param string $length 截取長度
* @param string $suffix 截斷顯示字符
* @param string $charset 編碼格式
* @return string
*
*/
function re_substr($str, $start=0, $length, $suffix=true, $charset="utf-8") {
if(function_exists("mb_substr"))
$slice = mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
$slice = iconv_substr($str,$start,$length,$charset);
}else{
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
}
$omit=mb_strlen($str) >=$length ? '...' : '';
return $suffix ? $slice.$omit : $slice;
}
/**
* 設置驗證碼,生成驗證碼字符串
* thinkphp自帶驗證碼生成類
* @return 返回生成的驗證碼字符串
*
*/
function show_verify($config=''){
if($config==''){
$config=array(
'codeSet'=>'1234567890',
'fontSize'=>30,
'useCurve'=>false,
'imageH'=>60,
'imageW'=>240,
'length'=>4,
'fontttf'=>'4.ttf',
);
}
$verify=new \Think\Verify($config);
return $verify->entry();
}
/**
* thinkphp自帶驗證碼檢測功能
*
*/
function check_verify($code){
$verify=new \Think\Verify();
return $verify->check($code);
}
/**
* 取得根域名
* @param type $domain 域名
* @return string 返回根域名
*
*/
function get_url_to_domain($domain) {
$re_domain = '';
$domain_postfix_cn_array = array("com", "net", "org", "gov", "edu", "com.cn", "cn");
$array_domain = explode(".", $domain);
$array_num = count($array_domain) - 1;
if ($array_domain[$array_num] == 'cn') {
if (in_array($array_domain[$array_num - 1], $domain_postfix_cn_array)) {
$re_domain = $array_domain[$array_num - 2] . "." . $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
} else {
$re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
}
} else {
$re_domain = $array_domain[$array_num - 1] . "." . $array_domain[$array_num];
}
return $re_domain;
}
/**
* 按符號截取字符串的指定部分
* @param string $str 需要截取的字符串
* @param string $sign 需要截取的符號
* @param int $number 如是正數以0為起點從左向右截 負數則從右向左截
* @return string 返回截取的內容
*
*/
/* 示例
$str='123/456/789';
cut_str($str,'/',0); 返回 123
cut_str($str,'/',-1); 返回 789
cut_str($str,'/',-2); 返回 456
具體參考 http://www.baijunyao.com/index.php/Home/Index/article/aid/18
*/
function cut_str($str,$sign,$number){
$array=explode($sign, $str);
$length=count($array);
if($number<0){
$new_array=array_reverse($array);
$abs_number=abs($number);
if($abs_number>$length){
return 'error';
}else{
return $new_array[$abs_number-1];
}
}else{
if($number>=$length){
return 'error';
}else{
return $array[$number];
}
}
}
/**
* 發送郵件
* @param string $address 需要發送的郵箱地址 發送給多個地址需要寫成數組形式
* @param string $subject 標題
* @param string $content 內容
* @return boolean 是否成功
*
*/
function send_email($address,$subject,$content){
$email_smtp=C('EMAIL_SMTP');
$email_username=C('EMAIL_USERNAME');
$email_password=C('EMAIL_PASSWORD');
$email_from_name=C('EMAIL_FROM_NAME');
if(empty($email_smtp) || empty($email_username) || empty($email_password) || empty($email_from_name)){
return array("error"=>1,"message"=>'郵箱配置不完整');
}
require './ThinkPHP/Library/Org/Nx/class.phpmailer.php';
require './ThinkPHP/Library/Org/Nx/class.smtp.php';
$phpmailer=new \Phpmailer();
// 設置PHPMailer使用SMTP服務器發送Email
$phpmailer->IsSMTP();
// 設置為html格式
$phpmailer->IsHTML(true);
// 設置郵件的字符編碼'
$phpmailer->CharSet='UTF-8';
// 設置SMTP服務器。
$phpmailer->Host=$email_smtp;
// 設置為"需要驗證"
$phpmailer->SMTPAuth=true;
// 設置用戶名
$phpmailer->Username=$email_username;
// 設置密碼
$phpmailer->Password=$email_password;
// 設置郵件頭的From字段。
$phpmailer->From=$email_username;
// 設置發件人名字
$phpmailer->FromName=$email_from_name;
// 添加收件人地址,可以多次使用來添加多個收件人
if(is_array($address)){
foreach($address as $addressv){
$phpmailer->AddAddress($addressv);
}
}else{
$phpmailer->AddAddress($address);
}
// 設置郵件標題
$phpmailer->Subject=$subject;
// 設置郵件正文
$phpmailer->Body=$content;
// 發送郵件。
if(!$phpmailer->Send()) {
$phpmailererror=$phpmailer->ErrorInfo;
return array("error"=>1,"message"=>$phpmailererror);
}else{
return array("error"=>0);
}
}
/**
* 獲取一定范圍內的隨機數字
* 跟rand()函數的區別是 位數不足補零 例如
* rand(1,9999)可能會得到 465
* rand_number(1,9999)可能會得到 0465 保證是4位的
* @param integer $min 最小值
* @param integer $max 最大值
* @return string
*
*/
function rand_number ($min=1, $max=9999) {
return sprintf("%0".strlen($max)."d", mt_rand($min,$max));
}
/**
* 生成一定數量的隨機數,并且不重復
* @param integer $number 數量
* @param string $len 長度
* @param string $type 字串類型
* 0 字母 1 數字 其它 混合
* @return string
*/
function build_count_rand ($number,$length=4,$mode=1) {
if($mode==1 && $length<strlen($number) ) {
//不足以生成一定數量的不重復數字
return false;
}
$rand = array();
for($i=0; $i<$number; $i++) {
$rand[] = rand_string($length,$mode);
}
$unqiue = array_unique($rand);
if(count($unqiue)==count($rand)) {
return $rand;
}
$count = count($rand)-count($unqiue);
for($i=0; $i<$count*3; $i++) {
$rand[] = rand_string($length,$mode);
}
$rand = array_slice(array_unique ($rand),0,$number);
return $rand;
}
/**
* 生成不重復的隨機數
* @param int $start 需要生成的數字開始范圍
* @param int $end 結束范圍
* @param int $length 需要生成的隨機數個數
* @return array 生成的隨機數
*
*/
function get_rand_number($start=1,$end=10,$length=4){
$connt=0;
$temp=array();
while($connt<$length){
$temp[]=rand($start,$end);
$data=array_unique($temp);
$connt=count($data);
}
sort($data);
return $data;
}
/**
* 實例化page類
* @param integer $count 總數
* @param integer $limit 每頁數量
* @return subject page類
*
*/
function new_page($count,$limit=10){
return new \Org\Nx\Page($count,$limit);
}
/**
* 獲取分頁數據
* @param subject $model model對象
* @param array $map where條件
* @param string $order 排序規則
* @param integer $limit 每頁數量
* @return array 分頁數據
*
*/
function get_page_data($model,$map,$order='',$limit=10){
$count=$model
->where($map)
->count();
$page=new_page($count,$limit);
// 獲取分頁數據
$list=$model
->where($map)
->order($order)
->limit($page->firstRow.','.$page->listRows)
->select();
$data=array(
'data'=>$list,
'page'=>$page->show()
);
return $data;
}
/*
* @param string $path 字符串 保存文件路徑示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允許的上傳文件最大值 52428800
* @return booler 返回ajax的json格式數據
*
*/
function post_upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除兩邊的/
$path=trim($path,'/');
// 添加Upload根目錄
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上傳文件類型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上傳文件配置
$config=array(
'maxSize' => $maxSize, // 上傳文件最大為50M
'rootPath' => './', //文件上傳保存的根路徑
'savePath' => './'.$path.'/', //文件上傳的保存路徑(相對于根路徑)
'saveName' => array('uniqid',''), //上傳文件的保存規則,支持數組和字符串方式定義
'autoSub' => true, // 自動使用子目錄保存上傳文件 默認為true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 實例化上傳
$upload=new \Think\Upload($config);
// 調用上傳方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回錯誤信息
$error=$upload->getError();
$data['error_info']=$error;
return $data;
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
return $data;
}
}
}
}
/**
* 上傳文件類型控制 此方法僅限ajax上傳使用
* @param string $path 字符串 保存文件路徑示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允許的上傳文件最大值 52428800
* @return booler 返回ajax的json格式數據
*
*/
function upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除兩邊的/
$path=trim($path,'/');
// 添加Upload根目錄
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上傳文件類型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上傳文件配置
$config=array(
'maxSize' => $maxSize, // 上傳文件最大為50M
'rootPath' => './', //文件上傳保存的根路徑
'savePath' => './'.$path.'/', //文件上傳的保存路徑(相對于根路徑)
'saveName' => array('uniqid',''), //上傳文件的保存規則,支持數組和字符串方式定義
'autoSub' => true, // 自動使用子目錄保存上傳文件 默認為true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 實例化上傳
$upload=new \Think\Upload($config);
// 調用上傳方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回錯誤信息
$error=$upload->getError();
$data['error_info']=$error;
echo json_encode($data);
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
echo json_encode($data);
}
}
}
}
/**
* 使用curl獲取遠程數據
* @param string $url url連接
* @return string 獲取到的數據
*
*/
function curl_get_contents($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //設置訪問的url地址
//curl_setopt($ch,CURLOPT_HEADER,1); //是否顯示頭部信息
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //設置超時
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_); //用戶訪問代理 User-Agent
curl_setopt($ch, CURLOPT_REFERER,_REFERER_); //設置 referer
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟蹤301
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回結果
$r=curl_exec($ch);
curl_close($ch);
return $r;
}
/*
* 計算星座的函數 string get_zodiac_sign(string month, string day)
* 輸入:月份,日期
* 輸出:星座名稱或者錯誤信息
*
*/
function get_zodiac_sign($month, $day)
{
// 檢查參數有效性
if ($month < 1 || $month > 12 || $day < 1 || $day > 31)
return (false);
// 星座名稱以及開始日期
$signs = array(
array( "20" => "水瓶座"),
array( "19" => "雙魚座"),
array( "21" => "白羊座"),
array( "20" => "金牛座"),
array( "21" => "雙子座"),
array( "22" => "巨蟹座"),
array( "23" => "獅子座"),
array( "23" => "處女座"),
array( "23" => "天秤座"),
array( "24" => "天蝎座"),
array( "22" => "射手座"),
array( "22" => "摩羯座")
);
list($sign_start, $sign_name) = each($signs[(int)$month-1]);
if ($day < $sign_start)
list($sign_start, $sign_name) = each($signs[($month -2 < 0) ? $month = 11: $month -= 2]);
return $sign_name;
}
/**
* 發送 容聯云通訊 驗證碼
* @param int $phone 手機號
* @param int $code 驗證碼
* @return boole 是否發送成功
*
*/
function send_sms_code($phone,$code){
//請求地址,格式如下,不需要寫https://
$serverIP='app.cloopen.com';
//請求端口
$serverPort='8883';
//REST版本號
$softVersion='2013-12-26';
//主帳號
$accountSid=C('RONGLIAN_ACCOUNT_SID');
//主帳號Token
$accountToken=C('RONGLIAN_ACCOUNT_TOKEN');
//應用Id
$appId=C('RONGLIAN_APPID');
//應用Id
$templateId=C('RONGLIAN_TEMPLATE_ID');
$rest = new \Org\Xb\Rest($serverIP,$serverPort,$softVersion);
$rest->setAccount($accountSid,$accountToken);
$rest->setAppId($appId);
// 發送模板短信
$result=$rest->sendTemplateSMS($phone,array($code,5),$templateId);
if($result==NULL) {
return false;
}
if($result->statusCode!=0) {
return false;
}else{
return true;
}
}
/**
* 將路徑轉換加密
* @param string $file_path 路徑
* @return string 轉換后的路徑
*
*/
function path_encode($file_path){
return rawurlencode(base64_encode($file_path));
}
/**
* 將路徑解密
* @param string $file_path 加密后的字符串
* @return string 解密后的路徑
*
*/
function path_decode($file_path){
return base64_decode(rawurldecode($file_path));
}
/**
* 根據文件后綴的不同返回不同的結果
* @param string $str 需要判斷的文件名或者文件的id
* @return integer 1:圖片 2:視頻 3:壓縮文件 4:文檔 5:其他
*
*/
function file_category($str){
// 取文件后綴名
$str=strtolower(pathinfo($str, PATHINFO_EXTENSION));
// 圖片格式
$images=array('webp','jpg','png','ico','bmp','gif','tif','pcx','tga','bmp','pxc','tiff','jpeg','exif','fpx','svg','psd','cdr','pcd','dxf','ufo','eps','ai','hdri');
// 視頻格式
$video=array('mp4','avi','3gp','rmvb','gif','wmv','mkv','mpg','vob','mov','flv','swf','mp3','ape','wma','aac','mmf','amr','m4a','m4r','ogg','wav','wavpack');
// 壓縮格式
$zip=array('rar','zip','tar','cab','uue','jar','iso','z','7-zip','ace','lzh','arj','gzip','bz2','tz');
// 文檔格式
$document=array('exe','doc','ppt','xls','wps','txt','lrc','wfs','torrent','html','htm','java','js','css','less','php','pdf','pps','host','box','docx','word','perfect','dot','dsf','efe','ini','json','lnk','log','msi','ost','pcs','tmp','xlsb');
// 匹配不同的結果
switch ($str) {
case in_array($str, $images):
return 1;
break;
case in_array($str, $video):
return 2;
break;
case in_array($str, $zip):
return 3;
break;
case in_array($str, $document):
return 4;
break;
default:
return 5;
break;
}
}
/**
* 組合縮略圖
* @param string $file_path 原圖path
* @param integer $size 比例
* @return string 縮略圖
*
*/
function get_min_image_path($file_path,$width=170,$height=170){
$min_path=str_replace('.', '_'.$width.'_'.$height.'.', trim($file_path,'.'));
$min_path='http://xueba17.oss-cn-beijing.aliyuncs.com'.$min_path;
return $min_path;
}
/**
* 不區分大小寫的in_array()
* @param string $str 檢測的字符
* @param array $array 數組
* @return boolear 是否in_array
*
*/
function in_iarray($str,$array){
$str=strtolower($str);
$array=array_map('strtolower', $array);
if (in_array($str, $array)) {
return true;
}
return false;
}
/**
* 傳入時間戳,計算距離現在的時間
* @param number $time 時間戳
* @return string 返回多少以前
*
*/
function word_time($time) {
$time = (int) substr($time, 0, 10);
$int = time() - $time;
$str = '';
if ($int <= 2){
$str = sprintf('剛剛', $int);
}elseif ($int < 60){
$str = sprintf('%d秒前', $int);
}elseif ($int < 3600){
$str = sprintf('%d分鐘前', floor($int / 60));
}elseif ($int < 86400){
$str = sprintf('%d小時前', floor($int / 3600));
}else{
$str = date('Y-m-d H:i:s', $time);
}
return $str;
}
/**
* 生成縮略圖
* @param string $image_path 原圖path
* @param integer $width 縮略圖的寬
* @param integer $height 縮略圖的高
* @return string 縮略圖path
*
*/
function crop_image($image_path,$width=170,$height=170){
$image_path=trim($image_path,'.');
$min_path='.'.str_replace('.', '_'.$width.'_'.$height.'.', $image_path);
$image = new \Think\Image();
$image->open($image_path);
// 生成一個居中裁剪為$width*$height的縮略圖并保存
$image->thumb($width, $height,\Think\Image::IMAGE_THUMB_CENTER)->save($min_path);
oss_upload($min_path);
return $min_path;
}
/**
* 上傳文件類型控制 此方法僅限ajax上傳使用
* @param string $path 字符串 保存文件路徑示例: /Upload/image/
* @param string $format 文件格式限制
* @param integer $maxSize 允許的上傳文件最大值 52428800
* @return booler 返回ajax的json格式數據
*
*/
function ajax_upload($path='file',$format='empty',$maxSize='52428800'){
ini_set('max_execution_time', '0');
// 去除兩邊的/
$path=trim($path,'/');
// 添加Upload根目錄
$path=strtolower(substr($path, 0,6))==='upload' ? ucfirst($path) : 'Upload/'.$path;
// 上傳文件類型控制
$ext_arr= array(
'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
'photo' => array('jpg', 'jpeg', 'png'),
'flash' => array('swf', 'flv'),
'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
);
if(!empty($_FILES)){
// 上傳文件配置
$config=array(
'maxSize' => $maxSize, // 上傳文件最大為50M
'rootPath' => './', // 文件上傳保存的根路徑
'savePath' => './'.$path.'/', // 文件上傳的保存路徑(相對于根路徑)
'saveName' => array('uniqid',''), // 上傳文件的保存規則,支持數組和字符串方式定義
'autoSub' => true, // 自動使用子目錄保存上傳文件 默認為true
'exts' => isset($ext_arr[$format])?$ext_arr[$format]:'',
);
// 實例化上傳
$upload=new \Think\Upload($config);
// 調用上傳方法
$info=$upload->upload();
$data=array();
if(!$info){
// 返回錯誤信息
$error=$upload->getError();
$data['error_info']=$error;
echo json_encode($data);
}else{
// 返回成功信息
foreach($info as $file){
$data['name']=trim($file['savepath'].$file['savename'],'.');
echo json_encode($data);
}
}
}
}
/**
* 檢測webuploader上傳是否成功
* @param string $file_path post中的字段
* @return boolear 是否成功
*
*/
function upload_success($file_path){
// 為兼容傳進來的有數組;先轉成json
$file_path=json_encode($file_path);
// 如果有undefined說明上傳失敗
if (strpos($file_path, 'undefined') !== false) {
return false;
}
// 如果沒有.符號說明上傳失敗
if (strpos($file_path, '.') === false) {
return false;
}
// 否則上傳成功則返回true
return true;
}
/**
* 把用戶輸入的文本轉義(主要針對特殊符號和emoji表情)
*
*/
function emoji_encode($str){
if(!is_string($str))return $str;
if(!$str || $str=='undefined')return '';
$text = json_encode($str); //暴露出unicode
$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
return addslashes($str[0]);
},$text); //將emoji的unicode留下,其他不動,這里的正則比原答案增加了d,因為我發現我很多emoji實際上是\ud開頭的,反而暫時沒發現有\ue開頭。
return json_decode($text);
}
/**
* 檢測是否是手機訪問
*
*/
function is_mobile(){
$useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
function _is_mobile($substrs,$text){
foreach($substrs as $substr)
if(false!==strpos($text,$substr)){
return true;
}
return false;
}
$mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
$mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
$found_mobile=_is_mobile($mobile_os_list,$useragent_commentsblock) ||
_is_mobile($mobile_token_list,$useragent);
if ($found_mobile){
return true;
}else{
return false;
}
}
/**
* 將utf-16的emoji表情轉為utf8文字形
* @param string $str 需要轉的字符串
* @return string 轉完成后的字符串
*
*/
function escape_sequence_decode($str) {
$regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})|\\\u([\da-fA-F]{4})/sx';
return preg_replace_callback($regex, function($matches) {
if (isset($matches[3])) {
$cp = hexdec($matches[3]);
} else {
$lead = hexdec($matches[1]);
$trail = hexdec($matches[2]);
$cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
}
if ($cp > 0xD7FF && 0xE000 > $cp) {
$cp = 0xFFFD;
}
if ($cp < 0x80) {
return chr($cp);
} else if ($cp < 0xA0) {
return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
}
$result = html_entity_decode('&#'.$cp.';');
return $result;
}, $str);
}
/**
* 獲取當前訪問的設備類型
* @return integer 1:其他 2:iOS 3:Android
*
*/
function get_device_type(){
//全部變成小寫字母
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$type = 1;
//分別進行判斷
if(strpos($agent, 'iphone')!==false || strpos($agent, 'ipad')!==false){
$type = 2;
}
if(strpos($agent, 'android')!==false){
$type = 3;
}
return $type;
}
/**
* 生成pdf
* @param string $html 需要生成的內容
*
*/
function pdf($html='<h1 style="color:red">hello word</h1>'){
vendor('Tcpdf.tcpdf');
$pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 設置打印模式
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// 是否顯示頁眉
$pdf->setPrintHeader(false);
// 設置頁眉顯示的內容
$pdf->SetHeaderData('logo.png', 60, 'baijunyao.com', '白俊遙博客', array(0,64,255), array(0,64,128));
// 設置頁眉字體
$pdf->setHeaderFont(Array('dejavusans', '', '12'));
// 頁眉距離頂部的距離
$pdf->SetHeaderMargin('5');
// 是否顯示頁腳
$pdf->setPrintFooter(true);
// 設置頁腳顯示的內容
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// 設置頁腳的字體
$pdf->setFooterFont(Array('dejavusans', '', '10'));
// 設置頁腳距離底部的距離
$pdf->SetFooterMargin('10');
// 設置默認等寬字體
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// 設置行高
$pdf->setCellHeightRatio(1);
// 設置左、上、右的間距
$pdf->SetMargins('10', '10', '10');
// 設置是否自動分頁 距離底部多少距離時分頁
$pdf->SetAutoPageBreak(TRUE, '15');
// 設置圖像比例因子
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->setFontSubsetting(true);
$pdf->AddPage();
// 設置字體
$pdf->SetFont('stsongstdlight', '', 14, '', true);
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output('example_001.pdf', 'I');
}
/**
* 生成二維碼
* @param string $url url連接
* @param integer $size 尺寸 純數字
*
*/
function qrcode($url,$size=4){
Vendor('Phpqrcode.phpqrcode');
QRcode::png($url,false,QR_ECLEVEL_L,$size,2,false,0xFFFFFF,0x000000);
}
/**
* 數組轉xls格式的excel文件
* @param array $data 需要生成excel文件的數組
* @param string $filename 生成的excel文件名
*
* 示例數據:
$data = array(
array(NULL, 2010, 2011, 2012),
array('Q1', 12, 15, 21),
array('Q2', 56, 73, 86),
array('Q3', 52, 61, 69),
array('Q4', 30, 32, 0),
);
*/
function create_xls($data,$filename='simple.xls'){
ini_set('max_execution_time', '0');
Vendor('PHPExcel.PHPExcel');
$filename=str_replace('.xls', '', $filename).'.xls';
$phpexcel = new PHPExcel();
$phpexcel->getProperties()
->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$phpexcel->getActiveSheet()->fromArray($data);
$phpexcel->getActiveSheet()->setTitle('Sheet1');
$phpexcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;filename=$filename");
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
$objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
$objwriter->save('php://output');
exit;
}
/**
* 數據轉csv格式的excel
* @param array $data 需要轉的數組
* @param string $filename 生成的excel文件名
* 示例數組:
$a = array(
'1,2,3,4,5',
'6,7,8,9,0',
'1,3,5,6,7'
);
*
*/
function create_csv($data,$filename='simple.csv'){
// 防止沒有添加文件后綴
$filename=str_replace('.csv', '', $filename).'.csv';
Header( "Content-type: application/octet-stream ");
Header( "Accept-Ranges: bytes ");
Header( "Content-Disposition: attachment; filename=".$filename);
foreach( $data as $k => $v){
// 替換掉換行
$v=preg_replace('/\s*/', '', $v);
// 轉成gbk以兼容office亂碼的問題
echo iconv('UTF-8','GBK',$v)."\r\n";
}
}
/**
* 跳向支付寶付款
* @param array $order 訂單數據 必須包含 out_trade_no(訂單號)、price(訂單金額)、subject(商品名稱標題)
*
*/
function alipay($order){
vendor('Alipay.AlipaySubmit','','.class.php');
// 獲取配置
$config=C('ALIPAY_CONFIG');
$data=array(
"_input_charset" => $config['input_charset'], // 編碼格式
"logistics_fee" => "0.00", // 物流費用
"logistics_payment" => "SELLER_PAY", // 物流支付方式SELLER_PAY(賣家承擔運費)、BUYER_PAY(買家承擔運費)
"logistics_type" => "EXPRESS", // 物流類型EXPRESS(快遞)、POST(平郵)、EMS(EMS)
"notify_url" => $config['notify_url'], // 異步接收支付狀態通知的鏈接
"out_trade_no" => $order['out_trade_no'], // 訂單號
"partner" => $config['partner'], // partner 從支付寶商戶版個人中心獲取
"payment_type" => "1", // 支付類型對應請求時的 payment_type 參數,原樣返回。固定設置為1即可
"price" => $order['price'], // 訂單價格單位為元
// "price" => 0.01, // // 調價用于測試
"quantity" => "1", // price、quantity 能代替 total_fee。 即存在 total_fee,就不能存在 price 和 quantity;存在 price、quantity, 就不能存在 total_fee。 (沒繞明白;好吧;那無視這個參數即可)
"receive_address" => '1', // 收貨人地址 即時到賬方式無視此參數即可
"receive_mobile" => '1', // 收貨人手機號碼 即時到賬方式無視即可
"receive_name" => '1', // 收貨人姓名 即時到賬方式無視即可
"receive_zip" => '1', // 收貨人郵編 即時到賬方式無視即可
"return_url" => $config['return_url'], // 頁面跳轉 同步通知 頁面路徑 支付寶處理完請求后,當前頁面自 動跳轉到商戶網站里指定頁面的 http 路徑。
"seller_email" => $config['seller_email'], // email 從支付寶商戶版個人中心獲取
"service" => "create_direct_pay_by_user", // 接口名稱 固定設置為create_direct_pay_by_user
"show_url" => $config['show_url'], // 商品展示網址,收銀臺頁面上,商品展示的超鏈接。
"subject" => $order['subject'] // 商品名稱商品的標題/交易標題/訂單標 題/訂單關鍵字等
);
$alipay=new \AlipaySubmit($config);
$new=$alipay->buildRequestPara($data);
$go_pay=$alipay->buildRequestForm($new, 'get','支付');
echo $go_pay;
}
/**
* 微信掃碼支付
* @param array $order 訂單 必須包含支付所需要的參數 body(產品描述)、total_fee(訂單金額)、out_trade_no(訂單號)、product_id(產品id)
*
*/
function weixinpay($order){
$order['trade_type']='NATIVE';
Vendor('Weixinpay.Weixinpay');
$weixinpay=new \Weixinpay();
$weixinpay->pay($order);
}
/**
* geetest檢測驗證碼
*
*/
function geetest_chcek_verify($data){
$geetest_id=C('GEETEST_ID');
$geetest_key=C('GEETEST_KEY');
$geetest=new \Org\Xb\Geetest($geetest_id,$geetest_key);
$user_id=$_SESSION['geetest']['user_id'];
if ($_SESSION['geetest']['gtserver']==1) {
$result=$geetest->success_validate($data['geetest_challenge'], $data['geetest_validate'], $data['geetest_seccode'], $user_id);
if ($result) {
return true;
} else{
return false;
}
}else{
if ($geetest->fail_validate($data['geetest_challenge'],$data['geetest_validate'],$data['geetest_seccode'])) {
return true;
}else{
return false;
}
}
}
/**
* 判斷當前服務器系統
* @return string
*
*/
function getOS(){
if(PATH_SEPARATOR == ':'){
return 'Linux';
}else{
return 'Windows';
}
}
/**
* 當前微妙數
* @return number
*
*/
function microtime_float() {
list ( $usec, $sec ) = explode ( " ", microtime () );
return (( float ) $usec + ( float ) $sec);
}
/**
* 遍歷文件夾
* @param string $dir
* @param boolean $all true表示遞歸遍歷
* @return array
*
*/
function scanfDir($dir='', $all = false, &$ret = array()){
if ( false !== ($handle = opendir ( $dir ))) {
while ( false !== ($file = readdir ( $handle )) ) {
if (!in_array($file, array('.', '..', '.git', '.gitignore', '.svn', '.htaccess', '.buildpath','.project'))) {
$cur_path = $dir . '/' . $file;
if (is_dir ( $cur_path )) {
$ret['dirs'][] =$cur_path;
$all && self::scanfDir( $cur_path, $all, $ret);
} else {
$ret ['files'] [] = $cur_path;
}
}
}
closedir ( $handle );
}
return $ret;
}
/**
* 判斷字符串是utf-8 還是gb2312
* @param unknown $str
* @param string $default
* @return string
*
*/
function utf8_gb2312($str, $default = 'gb2312')
{
$str = preg_replace("/[\x01-\x7F]+/", "", $str);
if (empty($str)) return $default;
$preg = array(
"gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正則判斷是否是gb2312
"utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u", //正則判斷是否是漢字(utf8編碼的條件了),這個范圍實際上已經包含了繁體中文字了
);
if ($default == 'gb2312') {
$option = 'utf-8';
} else {
$option = 'gb2312';
}
if (!preg_match($preg[$default], $str)) {
return $option;
}
$str = @iconv($default, $option, $str);
//不能轉成 $option, 說明原來的不是 $default
if (empty($str)) {
return $option;
}
return $default;
}
/**
* utf-8和gb2312自動轉化
* @param unknown $string
* @param string $outEncoding
* @return unknown|string
*
*/
function safeEncoding($string,$outEncoding = 'UTF-8')
{
$encoding = "UTF-8";
for($i = 0; $i < strlen ( $string ); $i ++) {
if (ord ( $string {$i} ) < 128)
continue;
if ((ord ( $string {$i} ) & 224) == 224) {
// 第一個字節判斷通過
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二個字節判斷通過
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
$encoding = "UTF-8";
break;
}
}
}
if ((ord ( $string {$i} ) & 192) == 192) {
// 第一個字節判斷通過
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二個字節判斷通過
$encoding = "GB2312";
break;
}
}
}
if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
return $string;
else
return @iconv ( $encoding, $outEncoding, $string );
}
/**
* 返回二維數組中某個鍵名的所有值
* @param input $array
* @param string $key
* @return array
*
*/
function array_key_values($array =array(), $key='')
{
$ret = array();
foreach((array)$array as $k=>$v){
$ret[$k] = $v[$key];
}
return $ret;
}
/**
* 判斷 文件/目錄 是否可寫(取代系統自帶的 is_writeable 函數)
* @param string $file 文件/目錄
* @return boolean
*
*/
function is_writeable($file) {
if (is_dir($file)){
$dir = $file;
if ($fp = @fopen("$dir/test.txt", 'w')) {
@fclose($fp);
@unlink("$dir/test.txt");
$writeable = 1;
} else {
$writeable = 0;
}
} else {
if ($fp = @fopen($file, 'a+')) {
@fclose($fp);
$writeable = 1;
} else {
$writeable = 0;
}
}
return $writeable;
}
/**
* 格式化單位
*
*/
function byteFormat( $size, $dec = 2 ) {
$a = array ( "B" , "KB" , "MB" , "GB" , "TB" , "PB" );
$pos = 0;
while ( $size >= 1024 ) {
$size /= 1024;
$pos ++;
}
return round( $size, $dec ) . " " . $a[$pos];
}
/**
* 下拉框,單選按鈕 自動選擇
* @param $string 輸入字符
* @param $param 條件
* @param $type 類型
* selected checked
* @return string
*
*/
function selected( $string, $param = 1, $type = 'select' ) {
$true = false;
if ( is_array( $param ) ) {
$true = in_array( $string, $param );
}elseif ( $string == $param ) {
$true = true;
}
$return='';
if ( $true )
$return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
echo $return;
}
/**
* 下載遠程圖片
* @param string $url 圖片的絕對url
* @param string $filepath 文件的完整路徑(例如/www/images/test) ,此函數會自動根據圖片url和http頭信息確定圖片的后綴名
* @param string $filename 要保存的文件名(不含擴展名)
* @return mixed 下載成功返回一個描述圖片信息的數組,下載失敗則返回false
*
*/
function downloadImage($url, $filepath, $filename) {
//服務器返回的頭信息
$responseHeaders = array();
//原始圖片名
$originalfilename = '';
//圖片的后綴名
$ext = '';
$ch = curl_init($url);
//設置curl_exec返回的值包含Http頭
curl_setopt($ch, CURLOPT_HEADER, 1);
//設置curl_exec返回的值包含Http內容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//設置抓取跳轉(http 301,302)后的頁面
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//設置最多的HTTP重定向的數量
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
//服務器返回的數據(包括http頭信息和內容)
$html = curl_exec($ch);
//獲取此次抓取的相關信息
$httpinfo = curl_getinfo($ch);
curl_close($ch);
if ($html !== false) {
//分離response的header和body,由于服務器可能使用了302跳轉,所以此處需要將字符串分離為 2+跳轉次數 個子串
$httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
//倒數第二段是服務器最后一次response的http頭
$header = $httpArr[count($httpArr) - 2];
//倒數第一段是服務器最后一次response的內容
$body = $httpArr[count($httpArr) - 1];
$header.="\r\n";
//獲取最后一次response的header信息
preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
for ($i = 0; $i < count($matches[1]); $i++) {
if (array_key_exists($i, $matches[2])) {
$responseHeaders[$matches[1][$i]] = $matches[2][$i];
}
}
}
//獲取圖片后綴名
if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
$originalfilename = $matches[0];
$ext = $matches[1];
} else {
if (array_key_exists('Content-Type', $responseHeaders)) {
if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
$ext = $extmatches[1];
}
}
}
//保存文件
if (!empty($ext)) {
//如果目錄不存在,則先要創建目錄
if(!is_dir($filepath)){
mkdir($filepath, 0777, true);
}
$filepath .= '/'.$filename.".$ext";
$local_file = fopen($filepath, 'w');
if (false !== $local_file) {
if (false !== fwrite($local_file, $body)) {
fclose($local_file);
$sizeinfo = getimagesize($filepath);
return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
}
}
}
}
return false;
}
/**
* 查找ip是否在某個段位里面
* @param string $ip 要查詢的ip
* @param $arrIP 禁止的ip
* @return boolean
*
*/
function ipAccess($ip='0.0.0.0', $arrIP = array()){
$access = true;
$ip && $arr_cur_ip = explode('.', $ip);
foreach((array)$arrIP as $key=> $value){
if($value == '*.*.*.*'){
$access = false; //禁止所有
break;
}
$tmp_arr = explode('.', $value);
if(($arr_cur_ip[0] == $tmp_arr[0]) && ($arr_cur_ip[1] == $tmp_arr[1])) {
//前兩段相同
if(($arr_cur_ip[2] == $tmp_arr[2]) || ($tmp_arr[2] == '*')){
//第三段為* 或者相同
if(($arr_cur_ip[3] == $tmp_arr[3]) || ($tmp_arr[3] == '*')){
//第四段為* 或者相同
$access = false; //在禁止ip列,則禁止訪問
break;
}
}
}
}
return $access;
}
/**
* @param string $string 原文或者密文
* @param string $operation 操作(ENCODE | DECODE), 默認為 DECODE
* @param string $key 密鑰
* @param int $expiry 密文有效期, 加密時候有效, 單位 秒,0 為永久有效
* @return string 處理后的 原文或者 經過 base64_encode 處理后的密文
* @example
* $a = authcode('abc', 'ENCODE', 'key');
* $b = authcode($a, 'DECODE', 'key'); // $b(abc)
* $a = authcode('abc', 'ENCODE', 'key', 3600);
* $b = authcode('abc', 'DECODE', 'key'); // 在一個小時內,$b(abc),否則 $b 為空
*
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
$ckey_length = 4;
// 隨機密鑰長度 取值 0-32;
// 加入隨機密鑰,可以令密文無任何規律,即便是原文和密鑰完全相同,加密結果也會每次不同,增大破解難度。
// 取值越大,密文變動規律越大,密文變化 = 16 的 $ckey_length 次方
// 當此值為 0 時,則不產生隨機密鑰
$key = md5 ( $key ? $key : 'key' ); //這里可以填寫默認key值
$keya = md5 ( substr ( $key, 0, 16 ) );
$keyb = md5 ( substr ( $key, 16, 16 ) );
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
$cryptkey = $keya . md5 ( $keya . $keyc );
$key_length = strlen ( $cryptkey );
$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
$string_length = strlen ( $string );
$result = '';
$box = range ( 0, 255 );
$rndkey = array ();
for($i = 0; $i <= 255; $i ++) {
$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
}
for($j = $i = 0; $i < 256; $i ++) {
$j = ($j + $box [$i] + $rndkey [$i]) % 256;
$tmp = $box [$i];
$box [$i] = $box [$j];
$box [$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i ++) {
$a = ($a + 1) % 256;
$j = ($j + $box [$a]) % 256;
$tmp = $box [$a];
$box [$a] = $box [$j];
$box [$j] = $tmp;
$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
}
if ($operation == 'DECODE') {
if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
return substr ( $result, 26 );
} else {
return '';
}
} else {
return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
}
}
/**
* gbk轉utf-8格式方法
*
*/
function gbkToUtf8($str){
return iconv("GBK", "UTF-8", $str);
}
/**
* 取得輸入目錄所包含的所有目錄和文件
* 以關聯數組形式返回
* author: flynetcn
*
*/
function deepScanDir($dir)
{
$fileArr = array();
$dirArr = array();
$dir = rtrim($dir, '//');
if(is_dir($dir)){
$dirHandle = opendir($dir);
while(false !== ($fileName = readdir($dirHandle))){
$subFile = $dir . DIRECTORY_SEPARATOR . $fileName;
if(is_file($subFile)){
$fileArr[] = $subFile;
} elseif (is_dir($subFile) && str_replace('.', '', $fileName)!=''){
$dirArr[] = $subFile;
$arr = self::deepScanDir($subFile);
$dirArr = array_merge($dirArr, $arr['dir']);
$fileArr = array_merge($fileArr, $arr['file']);
}
}
closedir($dirHandle);
}
return array('dir'=>$dirArr, 'file'=>$fileArr);
}
/**
* 取得輸入目錄所包含的所有文件
* 以數組形式返回
* author: flynetcn
*
*/
function get_dir_files($dir)
{
if (is_file($dir)) {
return array($dir);
}
$files = array();
if (is_dir($dir) && ($dir_p = opendir($dir))) {
$ds = DIRECTORY_SEPARATOR;
while (($filename = readdir($dir_p)) !== false) {
if ($filename=='.' || $filename=='..') { continue; }
$filetype = filetype($dir.$ds.$filename);
if ($filetype == 'dir') {
$files = array_merge($files, self::get_dir_files($dir.$ds.$filename));
} elseif ($filetype == 'file') {
$files[] = $dir.$ds.$filename;
}
}
closedir($dir_p);
}
return $files;
}
/**
* 刪除文件夾及其文件夾下所有文件
*
*/
function deldir($dir) {
//先刪除目錄下的文件:
$dh=opendir($dir);
while ($file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
self::deldir($fullpath);
}
}
}
closedir($dh);
//刪除當前文件夾:
if(rmdir($dir)) {
return true;
} else {
return false;
}
}
/**
* js 彈窗并且跳轉
* @param string $_info
* @param string $_url
* @return js
*
*/
function alertLocation($_info, $_url) {
echo "<script type='text/javascript'>alert('$_info');location.href='$_url';</script>";
exit();
}
/**
* js 彈窗返回
* @param string $_info
* @return js
*
*/
function alertBack($_info) {
echo "<script type='text/javascript'>alert('$_info');history.back();</script>";
exit();
}
/**
* 頁面跳轉
* @param string $url
* @return js
*
*/
function headerUrl($url) {
echo "<script type='text/javascript'>location.href='{$url}';</script>";
exit();
}
/**
* 彈窗關閉
* @param string $_info
* @return js
*
*/
function alertClose($_info) {
echo "<script type='text/javascript'>alert('$_info');close();</script>";
exit();
}
/**
* 彈窗
* @param string $_info
* @return js
*
*/
function alert($_info) {
echo "<script type='text/javascript'>alert('$_info');</script>";
exit();
}
/**
* 系統基本參數上傳圖片專用
* @param string $_path
* @return null
*
*/
function sysUploadImg($_path) {
echo '<script type="text/javascript">document.getElementById("logo").value="'.$_path.'";</script>';
echo '<script type="text/javascript">document.getElementById("pic").src="'.$_path.'";</script>';
echo '<script type="text/javascript">$("#loginpop1").hide();</script>';
echo '<script type="text/javascript">$("#bgloginpop2").hide();</script>';
}
/**
* html過濾
* @param array|object $_date
* @return string
*
*/
function htmlString($_date) {
if (is_array($_date)) {
foreach ($_date as $_key=>$_value) {
$_string[$_key] = self::htmlString($_value); //遞歸
}
} elseif (is_object($_date)) {
foreach ($_date as $_key=>$_value) {
$_string->$_key = self::htmlString($_value); //遞歸
}
} else {
$_string = htmlspecialchars($_date);
}
return $_string;
}
/**
* 數據庫輸入過濾
* @param string $_data
* @return string
*
*/
function mysqlString($_data) {
$_data = trim($_data);
return !GPC ? addcslashes($_data) : $_data;
}
/**
* 清理session
*
*/
function unSession() {
if (session_start()) {
session_destroy();
}
}
/**
* 驗證是否為空
* @param string $str
* @param string $name
* @return bool (true or false)
*
*/
function validateEmpty($str, $name) {
if (empty($str)) {
self::alertBack('警告:' .$name . '不能為空!');
}
}
/**
* 驗證是否相同
* @param string $str1
* @param string $str2
* @param string $alert
* @return JS
*
*/
function validateAll($str1, $str2, $alert) {
if ($str1 != $str2) self::alertBack('警告:' .$alert);
}
/**
* 驗證ID
* @param Number $id
* @return JS
*
*/
function validateId($id) {
if (empty($id) || !is_numeric($id)) self::alertBack('警告:參數錯誤!');
}
/**
* 格式化字符串
* @param string $str
* @return string
*
*/
function formatStr($str) {
$arr = array(' ', ' ', '&', '@', '#', '%', '\'', '"', '\\', '/', '.', ',', '$', '^', '*', '(', ')', '[', ']', '{', '}', '|', '~', '`', '?', '!', ';', ':', '-', '_', '+', '=');
foreach ($arr as $v) {
$str = str_replace($v, '', $str);
}
return $str;
}
/**
* 格式化時間
* @param int $time 時間戳
* @return string
*
*/
function formatDate($time='default') {
$date = $time == 'default' ? date('Y-m-d H:i:s', time()) : date('Y-m-d H:i:s', $time);
return $date;
}
/**
* 獲得真實IP地址
* @return string
*
*/
function realIp() {
static $realip = NULL;
if ($realip !== NULL) return $realip;
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
foreach ($arr AS $ip) {
$ip = trim($ip);
if ($ip != 'unknown') {
$realip = $ip;
break;
}
}
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$realip = $_SERVER['HTTP_CLIENT_IP'];
} else {
if (isset($_SERVER['REMOTE_ADDR'])) {
$realip = $_SERVER['REMOTE_ADDR'];
} else {
$realip = '0.0.0.0';
}
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$realip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP')) {
$realip = getenv('HTTP_CLIENT_IP');
} else {
$realip = getenv('REMOTE_ADDR');
}
}
preg_match('/[\d\.]{7,15}/', $realip, $onlineip);
$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
return $realip;
}
/**
* 加載 Smarty 模板
* @param string $html
* @return null;
*
*/
function display() {
global $tpl;$html = null;
$htmlArr = explode('/', $_SERVER[SCRIPT_NAME]);
$html = str_ireplace('.php', '.html', $htmlArr[count($htmlArr)-1]);
$dir = dirname($_SERVER[SCRIPT_NAME]);
$firstStr = substr($dir, 0, 1);
$endStr = substr($dir, strlen($dir)-1, 1);
if ($firstStr == '/' || $firstStr == '\\') $dir = substr($dir, 1);
if ($endStr != '/' || $endStr != '\\') $dir = $dir . '/';
$tpl->display($dir.$html);
}
/**
* 創建目錄
* @param string $dir
*
*/
function createDir($dir) {
if (!is_dir($dir)) {
mkdir($dir, 0777);
}
}
/**
* 創建文件(默認為空)
* @param unknown_type $filename
*
*/
function createFile($filename) {
if (!is_file($filename)) touch($filename);
}
/**
* 正確獲取變量
* @param string $param
* @param string $type
* @return string
*
*/
function getData($param, $type='post') {
$type = strtolower($type);
if ($type=='post') {
return self::mysqlString(trim($_POST[$param]));
} elseif ($type=='get') {
return self::mysqlString(trim($_GET[$param]));
}
}
/**
* 刪除文件
* @param string $filename
*
*/
function delFile($filename) {
if (file_exists($filename)) unlink($filename);
}
/**
* 刪除目錄
* @param string $path
*
*/
function delDir($path) {
if (is_dir($path)) rmdir($path);
}
/**
* 刪除目錄及全部子文件
* @param string $dir
* @return bool
*
*/
function delDirOfAll($dir) {
//先刪除目錄下的文件:
if (is_dir($dir)) {
$dh=opendir($dir);
while (!!$file=readdir($dh)) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
self::delDirOfAll($fullpath);
}
}
}
closedir($dh);
//刪除當前文件夾:
if(rmdir($dir)) {
return true;
} else {
return false;
}
}
}
/**
* 驗證登陸
*
*/
function validateLogin() {
if (empty($_SESSION['admin']['user'])) header('Location:/admin/');
}
/**
* 給已經存在的圖片添加水印
* @param string $file_path
* @return bool
*
*/
function addMark($file_path) {
if (file_exists($file_path) && file_exists(MARK)) {
//求出上傳圖片的名稱后綴
$ext_name = strtolower(substr($file_path, strrpos($file_path, '.'), strlen($file_path)));
//$new_name='jzy_' . time() . rand(1000,9999) . $ext_name ;
$store_path = ROOT_PATH . UPDIR;
//求上傳圖片高寬
$imginfo = getimagesize($file_path);
$width = $imginfo[0];
$height = $imginfo[1];
//添加圖片水印
switch($ext_name) {
case '.gif':
$dst_im = imagecreatefromgif($file_path);
break;
case '.jpg':
$dst_im = imagecreatefromjpeg($file_path);
break;
case '.png':
$dst_im = imagecreatefrompng($file_path);
break;
}
$src_im = imagecreatefrompng(MARK);
//求水印圖片高寬
$src_imginfo = getimagesize(MARK);
$src_width = $src_imginfo[0];
$src_height = $src_imginfo[1];
//求出水印圖片的實際生成位置
$src_x = $width - $src_width - 10;
$src_y = $height - $src_height - 10;
//新建一個真彩色圖像
$nimage = imagecreatetruecolor($width, $height);
//拷貝上傳圖片到真彩圖像
imagecopy($nimage, $dst_im, 0, 0, 0, 0, $width, $height);
//按坐標位置拷貝水印圖片到真彩圖像上
imagecopy($nimage, $src_im, $src_x, $src_y, 0, 0, $src_width, $src_height);
//分情況輸出生成后的水印圖片
switch($ext_name) {
case '.gif':
imagegif($nimage, $file_path);
break;
case '.jpg':
imagejpeg($nimage, $file_path);
break;
case '.png':
imagepng($nimage, $file_path);
break;
}
//釋放資源
imagedestroy($dst_im);
imagedestroy($src_im);
unset($imginfo);
unset($src_imginfo);
//移動生成后的圖片
@move_uploaded_file($file_path, ROOT_PATH.UPDIR . $file_path);
}
}
/**
* 中文截取2,單字節截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的長度
* @param int $startdd 開始標記處
* @return string
*
*/
function cn_substr($str, $slen, $startdd=0){
$cfg_soft_lang = PAGECHARSET;
if($cfg_soft_lang=='utf-8') {
return self::cn_substr_utf8($str, $slen, $startdd);
}
$restr = '';
$c = '';
$str_len = strlen($str);
if($str_len < $startdd+1) {
return '';
}
if($str_len < $startdd + $slen || $slen==0) {
$slen = $str_len - $startdd;
}
$enddd = $startdd + $slen - 1;
for($i=0;$i<$str_len;$i++) {
if($startdd==0) {
$restr .= $c;
} elseif($i > $startdd) {
$restr .= $c;
}
if(ord($str[$i])>0x80) {
if($str_len>$i+1) {
$c = $str[$i].$str[$i+1];
}
$i++;
} else {
$c = $str[$i];
}
if($i >= $enddd) {
if(strlen($restr)+strlen($c)>$slen) {
break;
} else {
$restr .= $c;
break;
}
}
}
return $restr;
}
/**
* utf-8中文截取,單字節截取模式
* @access public
* @param string $str 需要截取的字符串
* @param int $slen 截取的長度
* @param int $startdd 開始標記處
* @return string
*
*/
function cn_substr_utf8($str, $length, $start=0) {
if(strlen($str) < $start+1) {
return '';
}
preg_match_all("/./su", $str, $ar);
$str = '';
$tstr = '';
//為了兼容mysql4.1以下版本,與數據庫varchar一致,這里使用按字節截取
for($i=0; isset($ar[0][$i]); $i++) {
if(strlen($tstr) < $start) {
$tstr .= $ar[0][$i];
} else {
if(strlen($str) < $length + strlen($ar[0][$i]) ) {
$str .= $ar[0][$i];
} else {
break;
}
}
}
return $str;
}
/**
* 刪除圖片,根據圖片ID
* @param int $image_id
*
*/
function delPicByImageId($image_id) {
$db_name = PREFIX . 'images i';
$m = new Model();
$data = $m->getOne($db_name, "i.id={$image_id}", "i.path as p, i.big_img as b, i.small_img as s");
foreach ($data as $v) {
@self::delFile(ROOT_PATH . $v['p']);
@self::delFile(ROOT_PATH . $v['b']);
@self::delFile(ROOT_PATH . $v['s']);
}
$m->del(PREFIX . 'images', "id={$image_id}");
unset($m);
}
/**
* 圖片等比例縮放
* @param resource $im 新建圖片資源(imagecreatefromjpeg/imagecreatefrompng/imagecreatefromgif)
* @param int $maxwidth 生成圖像寬
* @param int $maxheight 生成圖像高
* @param string $name 生成圖像名稱
* @param string $filetype文件類型(.jpg/.gif/.png)
*
*/
function resizeImage($im, $maxwidth, $maxheight, $name, $filetype) {
$pic_width = imagesx($im);
$pic_height = imagesy($im);
if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
if($maxwidth && $pic_width>$maxwidth) {
$widthratio = $maxwidth/$pic_width;
$resizewidth_tag = true;
}
if($maxheight && $pic_height>$maxheight) {
$heightratio = $maxheight/$pic_height;
$resizeheight_tag = true;
}
if($resizewidth_tag && $resizeheight_tag) {
if($widthratio<$heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio;
if($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if(function_exists("imagecopyresampled")) {
$newim = imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
} else {
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
$name = $name.$filetype;
imagejpeg($newim,$name);
imagedestroy($newim);
} else {
$name = $name.$filetype;
imagejpeg($im,$name);
}
}
/**
* 下載文件
* @param string $file_path 絕對路徑
*
*/
function downFile($file_path) {
//判斷文件是否存在
$file_path = iconv('utf-8', 'gb2312', $file_path); //對可能出現的中文名稱進行轉碼
if (!file_exists($file_path)) {
exit('文件不存在!');
}
$file_name = basename($file_path); //獲取文件名稱
$file_size = filesize($file_path); //獲取文件大小
$fp = fopen($file_path, 'r'); //以只讀的方式打開文件
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: {$file_size}");
header("Content-Disposition: attachment;filename={$file_name}");
$buffer = 1024;
$file_count = 0;
//判斷文件是否結束
while (!feof($fp) && ($file_size-$file_count>0)) {
$file_data = fread($fp, $buffer);
$file_count += $buffer;
echo $file_data;
}
fclose($fp); //關閉文件
}
?>
~~~