版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1333609
此为近期使用比较频繁的PHP公用代码,为了开发效率,方便以后的功能参考使用,整理一下,多谢指摘...
//通用增加
function add($dataName,$data){
return M($dataName)->add($data);
}
//通用删除
function del($dataName,$where){
return M($dataName)->where($where)->delete();
}
//通用修改
function edit($dataName,$where,$data){
return M($dataName)->where($where)->save($data);
//echo M($dataName)->_sql();die;//输出sql语句
}
/**
* 用户二维码图片
* @param $user_id [用户id]
* @param $recommend[推荐码]
* @param $data[链接地址]
*/
//生成图片二维码 $data链接 $id user_id;
function code($url,$user_id,$recommend){
$user=M('users')->field('user_name')->where('user_id='.$user_id)->find();
$user_name=$user['user_name'];
$canshu="?r_ec=$recommend";
$url=$url.$canshu;
vendor("phpqrcode.phpqrcode");
// 纠错级别:L、M、Q、H
$level = 'H';
// 点的大小:1到10,用于手机端4就可以了
$size = 4;
// 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
$path = "Public/code/".date("ymd")."/";
if(!is_dir($path))
{
mkdir($path);
}
$fileName = $path.$user_name.'.png';
$data['code']=$fileName;
M('users')->where('user_id='.$user_id)->save($data);
ob_end_clean();//清空缓冲区
QRcode::png($url, $fileName, $level, $size,1);
$furl=C('REMOTE_ROOT').$fileName;
ftp_upload($furl,$fileName);
}
/**
* 商品历史浏览记录
* $data 商品记录信息
*/
function _history($data)
{
if(!$data || !is_array($data))
{
return false;
}
//判断cookie类里面是否有浏览记录
if(!empty($_COOKIE['history']))
{
$history = unserialize($_COOKIE['history']);
array_unshift($history, $data); //在浏览记录顶部加入
/* 去除重复记录 */
$rows = array();
foreach ($history as $v)
{
if(in_array($v, $rows))
{
continue;
}
$rows[] = $v;
}
/* 如果记录数量多余5则去除 */
while (count($rows) > 5)
{
array_pop($rows); //弹出
}
setcookie('history',serialize($rows),time() + 3600 * 24 * 30,'/');
}
else
{
$history = serialize(array($data));
setcookie('history',$history,time() + 3600 * 24 * 30,'/');
}
}
//ue编辑器通过FTP上传图片($str代表从表单接收到的content字符串),返回处理后的content字符串
function ftp_image_upload($str){
$local_root = $_SERVER['DOCUMENT_ROOT'];
$host = C('FTP_SEVER');
$remote_root = C('REMOTE_ROOT');
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg|\.mp4]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$str,$match);
foreach ($match[1] as $k => $v) {
$localfile = $local_root.$v;
$remotefile = $remote_root.$v;
ftp_upload($remotefile,$localfile);
}
return str_replace("src=\"/Public", "src=\"$host/Public", $str);
}
//FTP上传文件函数
function ftp_upload($remotefile,$localfile){
$ftp = new \Think\Ftp();
$data['server'] = C('FTP_HOST');
$data['username'] = C('FTP_NAME');//ftp帐户
$data['password'] = C('FTP_PWD');//ftp密码
$data['port'] = C('FTP_PORT');//ftp端口,默认为21
$data['pasv'] = C('FTP_PASV');//是否开启被动模式,true开启,默认不开启
$data['ssl'] = C('FTP_SSL');//ssl连接,默认不开启
$data['timeout'] = C('FTP_TIMEOUT');//超时时间,默认60,单位 s
$info = $ftp->start($data);
if($info){
if($ftp->put($remotefile,$localfile)){}
}
$ftp->close();
}
/**
* $param 数组 传入的参数需要与API的模板对应
*
* $mobile 手机号码
*/
function send_verify($mobile='18831605741'){
$rand=md5(rand(000000,999999));
cookie('code',$rand,time()+6000,"/");
$param['code']=$rand;
$appkey = "23496841";
$secret = "f3b9840f579585feeb37b02474fe6bd0";
vendor('Alimsg.top.TopClient');
vendor('Alimsg.top.ResultSet');
vendor('Alimsg.top.RequestCheckUtil');
vendor('Alimsg.top.TopLogger');
vendor('Alimsg.top.request.AlibabaAliqinFcSmsNumSendRequest');
vendor('Alimsg.TopSdk.php');
$c = new \TopClient;
$c->appkey = $appkey;
$c->secretKey = $secret;
$req = new \AlibabaAliqinFcSmsNumSendRequest;
$req->setSmsTemplateCode("SMS_24575052");
$req->setExtend("3");
$req->setSmsType("normal");
$req->setSmsFreeSignName("简单主义");
$req->setSmsParam($param);
$req->setRecNum($mobile);
$resp = $c->execute($req);
}
/**
* 微信扫码支付
* @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();
return $weixinpay->pay($order);
}
/**
* 生成二维码
* @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);
}
function is_weixin(){
if(strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') === false ){
return false;
}else{
return ture;
}
}
/**
* 使用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, $_SERVER['HTTP_USER_AGENT']); //用户访问代理 User-Agent
curl_setopt($ch, CURLOPT_REFERER,$_SERVER['HTTP_HOST']); //设置 referer
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1); //跟踪301
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
$r=curl_exec($ch);
curl_close($ch);
return $r;
}
//获取用户ip地址
function get_ip() {
static $ip;
if (isset($_SERVER)) {
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$ip = $_SERVER["HTTP_CLIENT_IP"];
} else {
$ip = $_SERVER["REMOTE_ADDR"];
}
} else {
if (getenv("HTTP_X_FORWARDED_FOR")) {
$ip = getenv("HTTP_X_FORWARDED_FOR");
} else if (getenv("HTTP_CLIENT_IP")) {
$ip = getenv("HTTP_CLIENT_IP");
} else {
$ip = getenv("REMOTE_ADDR");
}
}
if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/', $ip)) {
return $ip;
} else {
return '127.0.0.1';
}
}
//显示图片
function showImage($url, $width = '', $height = '')
{
$ic = C('FTP_SEVER').C('REMOTE_ROOT');
if($width)
$width = "width='$width'";
if($height)
$height = "height='$height'";
echo "<img ".$width. " ".$height." src="."'".$ic.$url."' />";
}
**
* 公用的方法 进行信息的提示
*/
function showMsg($status,$message,$data=array()){
$result = array(
'status' => $status,
'message' =>$message,
'data' =>$data
);
exit(json_encode($result));
}
/**
* 对象转化为数组
* @param $e
* @return array|void
*/
function objectToArray($e){
$e=(array)$e;
foreach($e as $k=>$v){
if( gettype($v)=='resource' ) return;
if( gettype($v)=='object' || gettype($v)=='array' )
$e[$k]=(array)objectToArray($v);
}
return $e;
}
function trimall($str)//删除空格
{
$qian=array(" "," ","\t","\n","\r");$hou=array("","","","","");
return str_replace($qian,$hou,$str);
}
/**
* excel表数据转化为数组
* @param string $filePath
* @param int $sheet
* @return array|void
*/
function format_excel2array($filePath='',$sheet=0){
if(empty($filePath) or !file_exists($filePath)){die('file not exists');}
$PHPReader = new PHPExcel_Reader_Excel2007(); //建立reader对象
if(!$PHPReader->canRead($filePath)){
$PHPReader = new PHPExcel_Reader_Excel5();
if(!$PHPReader->canRead($filePath)){
echo 'no Excel';
return ;
}
}
$PHPExcel = $PHPReader->load($filePath); //建立excel对象
$currentSheet = $PHPExcel->getSheet($sheet); //**读取excel文件中的指定工作表*/
$allColumn = $currentSheet->getHighestColumn(); //**取得最大的列号*/
$allRow = $currentSheet->getHighestRow(); //**取得一共有多少行*/
$data = array();
for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){ //循环读取每个单元格的内容。注意行从1开始,列从A开始
for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
$addr = $colIndex.$rowIndex;
$cell = $currentSheet->getCell($addr)->getValue();
if($cell instanceof PHPExcel_RichText){ //富文本转换字符串
$cell = $cell->__toString();
}
$data[$rowIndex][$colIndex] = $cell;
}
}
return $data;
}
/*--------------------------------------2017.01.20 补充 -----------------------------------*/
/**
* 判断当前数组中的数据是否有 空
* @param $arr
* @return int
*/
public function isNo($arr){
$tag = 0;
foreach ($arr as $key => $value){
$what = trim($value);
if ($what == '' || $what == null){
$tag = 1;
break;
}
}
return $tag;
}
-----------------------------------------------------------------------------------------------
/**
*加密
* @param $text[要加密的内容]
* @param $key[添加的额外字符串]
*/
function getEncrypt($txt, $key){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
$ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
$nh1 = rand(0,64);
$nh2 = rand(0,64);
$nh3 = rand(0,64);
$ch1 = $chars{$nh1};
$ch2 = $chars{$nh2};
$ch3 = $chars{$nh3};
$nhnum = $nh1 + $nh2 + $nh3;
$knum = 0;$i = 0;
while(isset($key{$i})) $knum +=ord($key{$i++});
$mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
$txt = base64_encode($txt);
$txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
$tmp = '';
$j=0;$k = 0;
$tlen = strlen($txt);
$klen = strlen($mdKey);
for ($i=0; $i<$tlen; $i++) {
$k = $k == $klen ? 0 : $k;
$j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
$tmp .= $chars{$j};
}
$tmplen = strlen($tmp);
$tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
$tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
$tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
return $tmp;
}
/**
*解密
* @param $text[要加密的内容]
* @param $key[添加的额外字符串和加密额外添加的字符串一致]
*/
function getDecrypt($txt, $key)
{
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
$ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
$knum = 0;$i = 0;
$tlen = strlen($txt);
while(isset($key{$i})) $knum +=ord($key{$i++});
$ch1 = $txt{$knum % $tlen};
$nh1 = strpos($chars,$ch1);
$txt = substr_replace($txt,'',$knum % $tlen--,1);
$ch2 = $txt{$nh1 % $tlen};
$nh2 = strpos($chars,$ch2);
$txt = substr_replace($txt,'',$nh1 % $tlen--,1);
$ch3 = $txt{$nh2 % $tlen};
$nh3 = strpos($chars,$ch3);
$txt = substr_replace($txt,'',$nh2 % $tlen--,1);
$nhnum = $nh1 + $nh2 + $nh3;
$mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
$tmp = '';
$j=0; $k = 0;
$tlen = strlen($txt);
$klen = strlen($mdKey);
for ($i=0; $i<$tlen; $i++) {
$k = $k == $klen ? 0 : $k;
$j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
while ($j<0) $j+=64;
$tmp .= $chars{$j};
}
$tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
return trim(base64_decode($tmp));
}