2、打开错误提示
6、计算数组的交集 / 判断一个数组中是否包含另一个数组 / 追加数组 / 添加元素到数组的第一位
8、检测数据类型 (数字,字母,数字+字母,数字+字母+下划线,数字+字母+下划线+点)
12、统计运行时间( 运行时间及内存使用)
- $in = "2019-1-10 14:23:00";
- if($in){
- $in = strtotime($in);
- $newIn = "";
- if (date("H", $in) <= 12) {
- $newIn .= "上午:";
- } else {
- $newIn .= "下午:";
- }
- $newIn .= date("h:i", $in);
- $in = $newIn;
- }
- echo $in;
- $out = "2019-1-10 14:00:00"; //出场时间
- $in = "2019-1-10 9:00:00"; //进场时间
- $t = strtotime($out) - strtotime($in);
- $presenceTime = "";
- if ($t && $t > 0) {
- $sec = round($t / 60);
- if ($sec >= 60) {
- $hour = floor($sec / 60);
- // $min = $sec % 60;
- $presenceTime = $hour . '小时';
- // $min != 0 && $presenceTime .= $min . '分钟';
- } else {
- $presenceTime = $sec . '分钟';
- }
- }
- /**
- * 获取指定日期段内每一天的日期
- * @param Date $startdate 开始日期
- * @param Date $enddate 结束日期
- * @return Array
- */
- function getDateFromRange($startdate, $enddate){
- $stimestamp = strtotime($startdate);
- $etimestamp = strtotime($enddate);
- // 计算日期段内有多少天
- $days = ($etimestamp-$stimestamp)/86400+1;
- // 保存每天日期
- $date = array();
- for($i=0; $i<$days; $i++){
- $date[] = date('Y-m-d', $stimestamp+(86400*$i));
- }
- return $date;
- }
- $startdate = '2016-08-29';
- $enddate = '2016-09-29';
- // demo
- $date = getDateFromRange($startdate,$enddate);
- print_r($date);
PHP发送POST请求curl方法
- public function get($url, $params=array()) {
- $real_url = $url;
- if (!emptyempty($params) && is_array($params)) {
- $query = http_build_query($params);
- $real_url = $url ."?". $query;
- }else{
- }
- $process = curl_init($real_url);
- curl_setopt($process, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json'));
- curl_setopt($process, CURLOPT_HEADER, 0);
- curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);//TODO Curl证书处理
- curl_setopt($process, CURLOPT_TIMEOUT, 30);
- curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
- return json_decode(curl_exec($process));
- }
- protected function post($url, $params = '', $header = array(), $timeout = 5)
- {
- //curl
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- $header = array_merge($header, ['Accept: application/json', 'Content-Type: application/json']);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- $restRe = curl_exec($ch);
- $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- curl_close($ch);
- return $restRe;
- }
- function post($url, $params = '', $timeout = 5){//curl
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
- curl_setopt($ch,CURLOPT_POST,true);
- curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json'));
- $restRe = curl_exec($ch);
- $status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
- curl_close($ch);
- return $restRe;
- }
- function getHttpResponsePOST($url, $params ) {
- $ch = curl_init ();
- // print_r($ch);
- curl_setopt ( $ch, CURLOPT_URL, $url );
- curl_setopt ( $ch, CURLOPT_POST, 1 );
- curl_setopt ( $ch, CURLOPT_HEADER, 0 );
- curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
- curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
- $return = curl_exec ( $ch );
- curl_close ( $ch );
- return $return;
- }
CURL 详解
- <php
- $cookie_file=dirname(__FILE__)."/cookie_".md5(basename(__FILE__)).".txt";//设置Cookie文件保存路径及文件名
- functionvlogin($url,$data){//模拟登录获取Cookie函数$curl=curl_init();//启动一个CURL会话
- curl_setopt($curl,CURLOPT_URL,$url);//要访问的地址
- curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);//对认证证书来源的检查
- curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,1);//从证书中检查SSL加密算法是否存在
- curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);//模拟用户使用的浏览器
- curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);//使用自动跳转
- curl_setopt($curl,CURLOPT_AUTOREFERER,1);//自动设置Referer
- curl_setopt($curl,CURLOPT_POST,1);//发送一个常规的Post请求
- curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//Post提交的数据包
- curl_setopt($curl,CURLOPT_COOKIEJAR,$GLOBALS['cookie_file']);//存放Cookie信息的文件名称
- curl_setopt($curl,CURLOPT_COOKIEFILE,$GLOBALS['cookie_file']);//读取上面所储存的Cookie信息
- curl_setopt($curl,CURLOPT_TIMEOUT,30);//设置超时限制防止死循环
- curl_setopt($curl,CURLOPT_HEADER,0);//显示返回的Header区域内容
- curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//获取的信息以文件流的形式返回
- $tmpInfo=curl_exec($curl);//执行操作if(curl_errno($curl)){
- echo'Errno'.curl_error($curl);}
- curl_close($curl);//关闭CURL会话return$tmpInfo;//返回数据}
- functionvget($url){//模拟获取内容函数
- $curl=curl_init();//启动一个CURL会话
- curl_setopt($curl,CURLOPT_URL,$url);//要访问的地址
- curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);//对认证证书来源的检查
- curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,1);//从证书中检查SSL加密算法是否存在
- curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);//模拟用户使用的浏览器
- curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);//使用自动跳转
- curl_setopt($curl,CURLOPT_AUTOREFERER,1);//自动设置Referer
- curl_setopt($curl,CURLOPT_HTTPGET,1);//发送一个常规的Post请求
- curl_setopt($curl,CURLOPT_COOKIEFILE,$GLOBALS['cookie_file']);//读取上面所储存的Cookie信息
- curl_setopt($curl,CURLOPT_TIMEOUT,30);//设置超时限制防止死循环
- curl_setopt($curl,CURLOPT_HEADER,0);//显示返回的Header区域内容
- curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//获取的信息以文件流的形式返回
- $tmpInfo=curl_exec($curl);//执行操作if(curl_errno($curl)){
- echo'Errno'.curl_error($curl);}
- curl_close($curl);//关闭CURL会话return$tmpInfo;//返回数据}
- functionvpost($url,$data){//模拟提交数据函数$curl=curl_init();//启动一个CURL会话
- curl_setopt($curl,CURLOPT_URL,$url);//要访问的地址
- curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);//对认证证书来源的检查
- curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,1);//从证书中检查SSL加密算法是否存在
- curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);//模拟用户使用的浏览器
- curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);//使用自动跳转
- curl_setopt($curl,CURLOPT_AUTOREFERER,1);//自动设置Referer
- curl_setopt($curl,CURLOPT_POST,1);//发送一个常规的Post请求
- curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//Post提交的数据包
- curl_setopt($curl,CURLOPT_COOKIEFILE,$GLOBALS['cookie_file']);//读取上面所储存的Cookie信息
- curl_setopt($curl,CURLOPT_TIMEOUT,30);//设置超时限制防止死循环
- curl_setopt($curl,CURLOPT_HEADER,0);//显示返回的Header区域内容
- curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);//获取的信息以文件流的形式返回
- $tmpInfo=curl_exec($curl);//执行操作if(curl_errno($curl)){
- echo'Errno'.curl_error($curl);}
- curl_close($curl);//关键CURL会话return$tmpInfo;//返回数据}
- functiondelcookie($cookie_file){//删除Cookie函数@unlink($cookie_file);//执行删除}
- //使用实例
- if(!file_exists($cookie_file)){//检测Cookie是否存在
- $str=vget('http://www.kalvin.cn/action=login');//获取登录随机值
- preg_match("/name=\"formhash\"value=\"(.*)\"/is",$str,$hash);//提取登录随机值
- vlogin('http://www.kalvin.cn/post.php','action=dologin&formhash='.$hash[1].'&username=aaa&password=bbb&clientcode=ccc');//登录获取Cookie}
- echovget('http://www.kalvin.cn/');>
json与数组的相互转化形式 / 转为json / 数组转为json / json转为数组 / 数组转json / json转数组
- $json_arr = array('WebName'=>'yoyo个人笔记','WebSite'=>'http://www.yoyo88.cn');
- $php_json = json_encode($json_arr); //把php数组格式转换成 json 格式的数据
- echo $php_json;
- $php_json = json_decode($php_json); //再把json格式的数据转换成php数组
- print_r($php_json);
将json转为数组会出现 stdclass object
在转换的时候,多加一个true 则正常
- print_r(json_decode($php_json,true));
PHP用Json_encode转换数组中文乱码
- <?php
- $id = $_GET['id'];//get接受传值
- api($id);//执行函数
- //定义函数
- function api($id){
- //函数体
- $array= array(1,2,3);//这是只是示意,表示$array是数组
- $json=jsons_encode($array);//通过jsons_encode函数输出数组的json格式
- echo $json;
- }
- ?>
通过jsons_encode函数把数组转换成json格式时,会发现形如这样的中文乱码:
\u901a\u8baf\u5f55\uff0c\u662f\u738b\u67cf\u5143\u81ea\u4e3b\u5f00\
原因分析:
在存储到数据库时!MySQL 不会存储 unicode 字符:MySQL 仅支持从基本的多语种平面字符 (0×0000-0xFFFF)。请尝试存储一个同义词相反:)
更新: MySQL 5.5.3 上 (其中尚未 GA), 支持补充字符如果您使用 UTF8MB4 编码。
json_encode中文的时候,会把每个中文字符encode成“uxxxx”,而存进数据库的时候,“”被屏蔽了,直接变成”uxxxx”
解决方案一:PHP版本>5.4
- $json = json_encode($array,JSON_UNESCAPED_UNICODE);
解决方案二:
- <?php
- function jsons_encode($array){
- //遍历已有数组,将每个值 urlencode 一下
- foreach($array as $key=>$value){
- $array[$key]=urlencode($value);
- }
- //用urldecode将值反解
- return urldecode(json_encode($array));
- }
- /**注意:中间省略了数组获取的代码,
- 你可以使用上面的jsons_encode函数对你的数组进行转换
- */
- $json=jsons_encode($array);
- echo $json;
- ?>
json_encode 去掉键值:
- $a = array(
- 0 => array('name' => 1),
- 5 => array('name' => 2),
- 6 => array('name' => 3),
- );
- echo json_encode($a); //{"0":{"name":1},"5":{"name":2},"6":{"name":3}}
- echo json_encode(array_values($a)); //[{"name":1},{"name":2},{"name":3}]
- array_values($array)
计算数组的交集 / 判断一个数组中是否包含另一个数组 / 追加数组 / 添加元素到数组的第一位
1、输出交集的数组
- <?php
- $array1 = array("a" => "green", "red", "blue");
- $array2 = array("b" => "green", "yellow", "red");
- $result = array_intersect($array1, $array2);
- print_r($result);
- ?>
- // 输出结果:
- Array
- (
- [a] => green
- [0] => red
- )
输出交集部分
2、(PHP 4 >= 4.0.1, PHP 5, PHP 7)
array_diff — 计算数组的差集
- <?php
- $array1 = array("a" => "green", "red", "blue", "red");
- $array2 = array("b" => "green", "yellow", "red");
- $result = array_diff($array1, $array2);
- print_r($result);
- ?>
- // 输出:
- Array
- (
- [1] => blue
- )
array_push追加数组,到数组的尾部:
- $array_push = array("西瓜","苹果");//定义数组
- array_push($array_push,"香蕉","梨子");//添加元素
- print_r($array_push);// 输出数组结果
- //[
- // "西瓜",
- // "苹果",
- // "香蕉",
- // "梨子"
- //]
array_unshift头部添加元素
- $names = ['andy', 'tom', 'jack'];
- array_unshift($names, 'joe', 'hank');
- print_r($names);
- //[
- // "joe",
- // "hank",
- // "andy",
- // "tom",
- // "jack"
- //]
- In PHP 7 there are a few ways to create an emptyempty object:
- <?php
- $obj1 = new \stdClass; // Instantiate stdClass object
- $obj2 = new class{}; // Instantiate anonymous class
- $obj3 = (object)[]; // Cast empty array to object
- var_dump($obj1); // object(stdClass)#1 (0) {}
- var_dump($obj2); // object(class@anonymous)#2 (0) {}
- var_dump($obj3); // object(stdClass)#3 (0) {}
- ?>
- $obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:
- <?php
- echo json_encode([
- new \stdClass,
- new class{},
- (object)[],
- ]);
- ?>
- Outputs: [{},{},{}]
参考:http://www.php.net/manual/zh/language.types.object.php
合并数组
array_merge()函数将数组合并到一起,返回一个联合的数组。所得到的数组以第一个输入数组参数开始,按后面数组参数出现的顺序依次迫加。其形式为:
- array array_merge (array array1 array2…,arrayN)
将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。
示例:
- $face = array("J","Q","K","A");
- $numbered = array("2","3","4","5","6","7","8","9");
- $cards = array_merge($face, $numbered);
- shuffle($cards);
- print_r($cards);
返回:
- Array ( [0] => A [1] => 4 [2] => 9 [3] => 3 [4] => K [5] => 7 [6] => 5 [7] => Q [8] => 6 [9] => 8 [10] => 2 [11] => J )
递归追加数组
array_merge_recursive()函数与array_merge()相同,可以将两个或多个数组合并在一起,形成一个联合的数组.两者之间 的区别在于,当某个输入数组中的某个键己经存在于结果数组中时该函数会采取不同的处理方式.array_merge()会覆盖前面存在的键/值对,替换为 当前输入数组中的键/值对,而array_merge_recursive()将把两个值合并在一起,形成一个新的数组,并以原有的键作为数组名。还有一 个数组合并的形式,就是递归追加数组。其形式为:
- array array_merge_recursive( array key,array values )
示例:
- $class1 = array("John" => 100, "James" => 85);
- $class2 = array("Micky" => 78, "John" => 45);
- $classScores = array_merge_recursive($class1, $class2);
- print_r($classScores);
返回:
- Array ( [John] => Array ( [0] => 100 [1] => 45 ) [James] => 85 [Micky] => 78 )
连接两个数组
array_combine()函数会得到一个新数组,它由一组提交的键和对应的值组成。其形式为:
- array array_combine(array array1,array array2[…,array arrayN])
示例:
- $abbreviations = array("AL","AK","AZ","AR");
- $states = array("Alabama","Alaska","Arizona","Arkansas");
- $stateMap = array_combine($abbreviations,$states);
- print_r($stateMap);
返回:
- Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona [AR] => Arkansas )
重组数组
两组数组:
将两组数组拆分,合并为一个数组,对于orderid有的是以逗号分割了,其实有两组order,对应的也有两组purchaseYns,purchaseYnNeeds,purchaseNums 等
- $orderId = explode(',',$item['orderIds']);
- $purchaseYn = explode(',',$item['purchaseYns']);
- $purchaseNum = explode(',',$item['purchaseNums']);
- $purchaseYnNeed = explode(',',$item['purchaseYnNeeds']);
- $n = count($orderId);
- $newAry = [];
- for($i=0;$i<=$n-1;$i++)
- {
- $newAry[] = [
- 'orderId' => $orderId[$i],
- 'purchaseYn' => $purchaseYn[$i],
- 'purchaseNum' => $purchaseNum[$i],
- 'purchaseYnNeed' => $purchaseYnNeed[$i]
- ];
- }
最终输出的效果为:
默认情况下,是没有错误提示的,最多一片空白:
- error_reporting(E_ALL);
- ini_set('display_errors', '1');
- //将出错信息输出到一个文本文件
- ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
- echo ini_get('error_reporting');
- /**
- * 将异常输出到日志里面
- * Note: port from CApplication::handleException()
- *
- * @param Exception $exception 需要写入日志的异常
- */
- public static function logException($exception) {
- // disable error capturing to avoid recursive errors
- restore_error_handler();
- restore_exception_handler();
- $category = 'exception.' . get_class($exception);
- // php <5.2 doesn't support string conversion auto-magically
- $message = $exception->__toString();
- if (isset($_SERVER['REQUEST_URI'])) {
- $message .= "\nREQUEST_URI=" . $_SERVER['REQUEST_URI'];
- }
- if (isset($_SERVER['HTTP_REFERER'])) {
- $message .= "\nHTTP_REFERER=" . $_SERVER['HTTP_REFERER'];
- }
- $message .= "\n---";
- Yii::log($message, CLogger::LEVEL_ERROR, $category);
- }
PHPIN 设置错误级别为严格:
- display_errors = On
- error_reporting = E_ALL
API中,筛选条件往往传递成数组,将数组拆解,并拼成筛选条件:
- //过滤筛选条件
- $filter = array(
- 'id' => $orderId,
- 'user_id' => $orderType,
- 'uid' => $userId
- );
- //排除条件为空时
- foreach ($filter as $k => $v) {
- if (emptyempty($v)) {
- unset($filter[$k]);
- }
- }
- $s = ' where del_flag=0';
- foreach ($filter as $k=>$v){
- if (is_string($v)) {
- $v = addslashes($v);
- }
- $s .= " and `$k`='$v'";
- }
- return $s;
- $filter = $_POST;
- //7.2排除hash
- foreach ($filter as $k => $v) {
- $exp='/(ehash_|rhash_)/';
- if(preg_match($exp,$k)) {
- unset($filter[$k]);
- }
- }
- foreach ($filter as $k=>$v){
- if(is_string($v)) {
- $v = addslashes($v);
- }
- if (emptyempty($s)) {
- $s = "`$k`='$v'";
- } else {
- $s .= ",`$k`='$v'";
- }
- }
- $r = $empire->query("update {$dbtbpre}comments_widget_config set ".$s." where `id`=$_POST[id]");
- define('ECMS_PATH',substr(dirname(__FILE__),0,-7));
获取当前文件所在的文件夹+文件名:
- echo __FILE__;
- //C:\work\ceshi\trunk\api\open\alipayRefund\alipay.config.php
获取当前文件名:
- echo basename(__FILE__);
- //如:alipay.config.php
获取不含后缀名的文档名称:
- echo basename(__FILE__, '.php');
- //如:alipay.config
获取当前文档所在的目录绝对路径,不含文件名:
- echo dirname(__FILE__);
- //如:C:\work\ceshi\trunk\api\open\alipayRefund
获取当前文档所在的上一层目录的绝对路径:
- echo dirname(dirname(__FILE__));
- //如:C:\work\ceshi\trunk\api\open\alipayRefund
PHP获取当前所有页面的url:
- #测试网址: http://localhost/blog/testurl.php?id=5
- //获取域名或主机地址
- echo $_SERVER['HTTP_HOST']."<br>"; #localhost
- //获取网页地址
- echo $_SERVER['PHP_SELF']."<br>"; #/blog/testurl.php
- //获取网址参数
- echo $_SERVER["QUERY_STRING"]."<br>"; #id=5
- //获取用户代理
- echo $_SERVER['HTTP_REFERER']."<br>";
- //获取完整的url
- echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
- echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
- #http://localhost/blog/testurl.php?id=5
- //包含端口号的完整url
- echo 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
- #http://localhost:80/blog/testurl.php?id=5
- //只取路径
- $url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
- echo dirname($url);
- #http://localhost/blog
- $file = "c:/webroot/index.php";
- $fileWebAddress = 'http://'.str_replace($_SERVER['DOCUMENT_ROOT'],$_SERVER['HTTP_HOST'],$file);
- <?php
- $path = "/usr/www/html/index.php";
- $pathinfo = pathinfo($path);
- echo "目录名称:$pathinfo[dirname]<br>";
- echo "文件名称:$pathinfo[basename]<br>";
- echo "扩展名:$pathinfo[extension]";
- ?>
使用php获取时间今天明天昨天时间戳
- 2013-06-20 11:12
- <?php
- echo "今天:".date("Y-m-d")."<br>";
- echo "昨天:".date("Y-m-d",strtotime("-1 day")), "<br>";
- echo "明天:".date("Y-m-d",strtotime("+1 day")). "<br>";
- echo "一周后:".date("Y-m-d",strtotime("+1 week")). "<br>";
- echo "一周零两天四小时两秒后:".date("Y-m-d G:H:s",strtotime("+1 week 2 days 4 hours 2 seconds")). "<br>";
- echo "下个星期四:".date("Y-m-d",strtotime("next Thursday")). "<br>";
- echo "上个周一:".date("Y-m-d",strtotime("last Monday"))."<br>";
- echo "一个月前:".date("Y-m-d",strtotime("last month"))."<br>";
- echo "一个月后:".date("Y-m-d",strtotime("+1 month"))."<br>";
- echo "十年后:".date("Y-m-d",strtotime("+10 year"))."<br>";
- strtotime()函数的作用是将日期时间描述解析为 Unix 时间戳
- int strtotime ( string time [, int now] )
- $date3=date('Y-m-d H:i:s',"1228348800");
- ?>
时间戳转化,上月,本月,下月,下下月
- /*
- $type: 需要获取的时间戳类型:M为月 W为周 D为天。
- $value: 需要的值。+ 或者 - 数值。
- $time:返回为包含开始时间和结束时间的数组。
- */
- function ReturnUtime($type='',$value=''){
- $type=strtoupper($type);
- switch ($type) {
- case 'M':
- $t = strtotime((date('Y-m',time()) . '-01 00:00:01')); // 20151031修复strtotime按30天计算的BUG
- $time[] = strtotime(date("Y-m-01 00:00:00", strtotime("{$value} month",$t)));//月开始时间
- $time[] = strtotime(date("Y-m-t 23:59:59", strtotime("{$value} month",$t)));//月结束时间
- break;
- case 'W':
- $time[] = mktime(0,0,0,date('m'),date('d')-date('w')+1+($value),date('Y'));//周开始时间
- $time[] = mktime(23,59,59,date('m'),date('d')-date('w')+7+($value),date('Y'));//周结束时间
- break;
- case 'D':
- $time[] = mktime(0,0,0,date('m'),date('d')+($value),date('Y'));//天开始时间
- $time[] = mktime(23,59,59,date('m'),date('d')+($value),date('Y'));//天结束时间
- break;
- default:
- $time[] = mktime(0,0,0,date('m'),date('d'),date('Y'));//默认为当天
- $time[] = mktime(23,59,59,date('m'),date('d'),date('Y'));//默认为当天
- break;
- }
- return $time;
- }
- $aa=ReturnUtime('M','-0');
- echo date("Y-m-d H:i:s",$aa[0]);//开始时间
- echo '<br />';
- echo date("Y-m-d H:i:s",$aa[1]);//结束时间
- /*
- $aa=ReturnUtime('w','+7');
- echo date("Y-m-d H:i:s",$aa[0]);//开始时间
- echo '<br />';
- echo date("Y-m-d H:i:s",$aa[1]);//结束时间
- $aa=ReturnUtime('D','-1');
- echo date("Y-m-d H:i:s",$aa[0]);//开始时间
- echo '<br />';
- echo date("Y-m-d H:i:s",$aa[1]);//结束时间
- */
调用示例:
- //部分例子:
- echo date("Y-m-d H:i:s",ReturnUtime('M','-1')[0]).'<br>';//上个月第一天
- echo date("Y-m-d H:i:s",ReturnUtime('M','-1')[1]).'<br>';//上个月最后一天
- echo date("Y-m-d H:i:s",ReturnUtime('W','-7')[0]).'<br>';//上周第一天
- echo date("Y-m-d H:i:s",ReturnUtime('W','-7')[1]).'<br>';//上周最后一天
- echo date("Y-m-d H:i:s",ReturnUtime('D','-1')[0]).'<br>';//昨天开始时间
- echo date("Y-m-d H:i:s",ReturnUtime('D','-1')[1]).'<br>';//昨天结束时间
php 根据开始日期和结束日期得到之间所有日期集合
- /**
- * 获取指定日期段内每一天的日期
- * @param Date $startdate 开始日期
- * @param Date $enddate 结束日期
- * @return Array
- */
- function getDateFromRange($startdate, $enddate){
- $stimestamp = strtotime($startdate);
- $etimestamp = strtotime($enddate);
- // 计算日期段内有多少天
- $days = ($etimestamp-$stimestamp)/86400+1;
- // 保存每天日期
- $date = array();
- for($i=0; $i<$days; $i++){
- $date[] = date('Y-m-d', $stimestamp+(86400*$i));
- }
- return $date;
- }
php取得几天星期几以及这个星期的星期一和下周一对应的日期
- $today=date("Y-m-d");
- echo $today; //即可获取今天是几号。输出2014-9-29
- $rows=array("日","一","二","三","四","五","六");//先定义一个数组
- echo "今天是星期 ".$rows[date("w")]." ";
- <?php
- echo "<li>今天是星期".$rows[date("w")]."</li>";
- echo "<li>本周一是".date('Y-m-d H:i:s',strtotime("this Monday"))."</li>";
- echo "<li>本周二是".date('Y-m-d H:i:s',strtotime("this Tuesday"))."</li>";
- echo "<li>本周三是".date('Y-m-d',strtotime("this Wednesday"))."</li>";
- echo "<li>本周四是".date('Y-m-d',strtotime("this Thursday"))."</li>";
- echo "<li>本周五是".date('Y-m-d',strtotime("this Friday"))."</li>";
- echo "<li>本周六是".date('Y-m-d',strtotime("this Saturday"))."</li>";
- ?>
- echo "本周一是".date('Y-m-d',strtotime("next Monday"))."";//快速获取下周一对应的日期输出2014-10-6
- PS:strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
- 附上星期对应的英文:
- 周一 Monday
- 周二 Tuesday
- 周三 Wednesday
- 周四 Thursday
- 周五 Friday
- 周六 Saturday
- 周日 Sunday
- //这里是写一个数组,然后循环显示出来
- <ul>
- <?php
- $rows=array("日","一","二","三","四","五","六");
- foreach($rows as $v){
- $ads=$v==$rows[date("w")]?' class="on"':'';
- echo '<li'.$ads.'>'.$v.'</li>';
- }
- ?>
- </ul>
- //输出时间在本周日和本周一之间的信息 即输出周日一天的信息
- <?php
- $i=1;
- $sql=$empire->query("select * from {$dbtbpre}ecms_news where classid not in (31) and newstime between ".strtotime('this Sunday')." and ".strtotime('this Monday')." order by onclick desc limit 9");
- while($zr=$empire->fetch($sql)){
- $i++;
- ?>
- <li><span><i class="icon iconfont"></i> <?=$zr['onclick']?></span><a href="<?=$zr['titleurl']?>" target="_blank"><?=$zr['title']?></a></li>
- <?php
- }
- ?>
- //输出时间在本周一和本周二之间的信息 即输出周一一天的信息
- $sql=$empire->query("select * from {$dbtbpre}ecms_news where classid not in (31) and newstime between ".strtotime('this Monday')." and ".strtotime('this Tuesday')." order by onclick desc limit 9");
- <?php
- $start = microtime(true); // 开始计数
- //你的代码
- $end = microtime(true); // 结束计数
- $time=$end-$start; // 得到时间差
- echo number_format($time, 10, '.', '')." 秒";//精确到十位小数,可自行调节
- ?>
- static function convert($size)
- {
- $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
- return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
- }
- static function test()
- {
- set_time_limit(0); // 设置脚本最大执行时间 为0 永不过期
- $startTime = microtime(true);
- $start = memory_get_usage();
- echo self::convert($start) . PHP_EOL;
- // do something
- $endTime = microtime(true);
- $memoryUse = memory_get_usage();
- echo "内存占用:" . self::convert($memoryUse) . "; 用时:" . ($endTime - $startTime) . PHP_EOL;
- ;
- class Test{
- /**
- * 字符型处理 —— 写入数据库
- * @param $val
- * @param int $ecms
- * @return string
- */
- function RepPostStr($val,$ecms=0){
- $val = $this->ehtmlspecialchars($val,ENT_QUOTES);
- if($ecms==0)
- {
- $this->CkPostStrChar($val);
- $val = $this->AddAddsData($val);
- //FireWall
- return $this->FWClearGetText($val);
- }
- return $val;
- }
- /**
- * 检查敏感字符
- * @param $str
- * @return string
- */
- private function FWClearGetText($str){
- //关键字保留,根据业务需求
- $cleargettext = "admin,党";
- if(emptyempty($cleargettext))
- {
- return '';
- }
- $r = explode(',',$cleargettext);
- $count = count($r);
- for($i=0;$i<$count;$i++)
- {
- $str = str_replace($r[$i],"*",$str); //将指定的敏感关键字替换为*
- }
- return $str;
- }
- /**
- * 提示
- * @param $msg
- */
- function FWShowMsg($msg){
- //echo $msg;
- exit();
- }
- /**
- * 增加adds
- * @param $data
- * @return string
- */
- private function AddAddsData($data){
- if(!MAGIC_QUOTES_GPC)
- {
- $data = addslashes($data); //在每个双引号(")前添加反斜杠
- }
- return $data;
- }
- /**
- * 处理编码字符
- * @param $val
- */
- private function CkPostStrChar($val){
- if(substr($val,-1)=="\\")
- {
- exit();
- }
- }
- /**
- * htmlspecialchars处理
- * @param $val
- * @param int $flags
- * @return string
- */
- private function ehtmlspecialchars($val,$flags=ENT_COMPAT){
- global $ecms_config;
- if(PHP_VERSION>='5.4.0')
- {
- if($ecms_config['sets']['pagechar']=='utf-8')
- {
- $char='UTF-8';
- }
- else
- {
- $char='ISO-8859-1';
- }
- $val=htmlspecialchars($val,$flags,$char);
- }
- else
- {
- $val=htmlspecialchars($val,$flags);
- }
- return $val;
- }
- }
- $test = new Test();
- $a = "<script>alert('admin');alert(\"党国\")</script><?php echo '123'?>";
- $a = $test->RepPostStr($a);
- echo '<pre>';
- print_r($a);
- echo '</pre>';
常用的几个工具函数:
- <?php
- /**
- * Copyright (C) 2012 Cxweb All rights reserved
- * Date: 2012-10-23
- * Description: 工具类
- */
- class Utils {
- /**
- * 判断$time是否在$startTime和$endTime之间
- * @param int $time
- * @param int $startTime
- * @param int $endTime
- * @param bool $strict 是否对0进行严格比对,false的话,当$startTime==0 && $endTime==0是返回true,
- * @return bool
- */
- public static function isTimestampBetween($time, $startTime, $endTime, $strict = false) {
- if ($strict && $startTime == 0 && $endTime == 0) {
- return false;
- }
- return ($time >= $startTime && $time <= $endTime) || ($time >= $startTime && $endTime == 0);
- }
- /**
- * 获取中英文字符的字数
- * http://bbs.cxweb.com.cn/thread-793-1-1.html
- * @param string $str
- * @return int
- */
- public static function getWordCount($str) {
- preg_replace('/[\x80-\xff]{1,3}/', ' ', $str,-1,$n);
- $n += str_word_count($str);
- return $n;
- }
- //获取当前时间
- public static function getCurrentDateTime() {
- return date("Y-m-d H:i:s");
- }
- //获取当前月份的第一天
- public static function getCurMonthFirstDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date))));
- }
- //获取当前日期
- public static function getCurrentDate() {
- return date("Y-m-d");
- }
- public static function getCurMonthLastDay($date) {
- return date('Y-m-d', strtotime(date('Y-m-01', strtotime($date)) . ' +1 month -1 day'));
- }
- public static function get_basename($filename){
- return preg_replace('/^.+[\\\\\\/]/', '', $filename);
- }
- public static function getNextTwoStr($tow_str_cur = '00') {
- $arr = array();
- $x = array(0,1,2,3,4,5,6,7,8,9,'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');
- foreach ($x as $x1) {
- foreach ($x as $y1) {
- $v = $x1.$y1;
- $arr[$v] = $v;
- }
- }
- foreach ($arr as $k=>$v) {
- next($arr);
- if ($v == $tow_str_cur) {
- return prev($arr);
- }
- }
- return false;
- }
- /**
- * Returns the url query as associative array
- *
- * @param string query
- * @return array params
- */
- public static function convertUrlQuery($query)
- {
- $queryParts = explode('&', $query);
- $params = array();
- foreach ($queryParts as $param)
- {
- $item = explode('=', $param);
- $params[$item[0]] = $item[1];
- }
- return $params;
- }
- public static function getUrlQuery($array_query)
- {
- $tmp = array();
- foreach($array_query as $k=>$param)
- {
- $tmp[] = $k.'='.$param;
- }
- $params = implode('&',$tmp);
- return $params;
- }
- public static function changeStrFromUnderlineToHump($underline_str) {
- if (strpos($underline_str , "_") !== false) {
- $humpStr = preg_replace("/(?:^|_)([a-z])/e","strtoupper('\\1')",$underline_str);
- } else {
- $humpStr = $underline_str;
- }
- $humpStr = lcfirst($humpStr);
- return $humpStr;
- }
- public static function changeStrToDomain($str) {
- $str = trim($str);
- if (emptyempty($str)) {
- return '';
- }
- $str = strtolower($str);
- $str = preg_replace('/[\s ]/', '-', $str);
- $str = preg_replace('/[\s&]/', '-', $str);
- return $str;
- }
- //将数组中的key转换为驼峰
- public static function changeArrKeyFromUnderlineToHump($arr) {
- foreach ($arr as $k=>&$v) {
- if (is_array($v)) {
- $v = Utils::changeArrKeyFromUnderlineToHump($v);
- } else {
- $nk = (Utils::changeStrFromUnderlineToHump($k));
- if ($nk != $k) {
- $arr[$nk] = $v;
- unset($arr[$k]);
- }
- }
- }
- return $arr;
- }
- //将数组中的key驼峰转换为数据库下划线字段定义模式
- public static function changeArrKeyFromHumpToDbformat($arr) {
- //去掉员工id对条件的干扰
- unset($arr['op_employee_id']);
- unset($arr['opEmployeeId']);
- foreach ($arr as $k=>&$v) {
- if (is_array($v)) {
- $v = Utils::changeArrKeyFromHumpToDbformat($v);
- } else {
- $nk = (Utils::changeStrFromHumpToDbformat($k));
- if ($nk != $k) {
- $arr[$nk] = $v;
- unset($arr[$k]);
- }
- }
- }
- return $arr;
- }
- public static function changeStrFromHumpToDbformat($hump_str) {
- if (!preg_match('/^[a-z]+$/', $hump_str)) {
- $newStr = preg_replace("/([A-Z])/e","_.strtolower('\\1')",$hump_str);
- } else {
- $newStr = $hump_str;
- }
- $newStr = lcfirst($newStr);
- return $newStr;
- }
- public static function path_info($filepath) {
- $path_parts = array();
- $path_parts ['dirname'] = rtrim(substr($filepath, 0, strrpos($filepath, '/')),"/")."/";
- $path_parts ['basename'] = ltrim(substr($filepath, strrpos($filepath, '/')),"/");
- $path_parts ['extension'] = substr(strrchr($filepath, '.'), 1);
- $path_parts ['filename'] = ltrim(substr($path_parts ['basename'], 0, strrpos($path_parts ['basename'], '.')),"/");
- return $path_parts;
- }
- public static function randStr($len=6,$format='NUMBER') {
- switch($format) {
- case 'ALL':
- $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~'; break;
- case 'CHAR':
- $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-@#~'; break;
- case 'LETTER':
- $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; break;
- case 'NUMBER':
- $chars='0123456789'; break;
- case 'LCL_NUM':
- $chars='abcdefghijklmnopqrstuvwxyz0123456789'; break;
- default :
- $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-@#~';
- break;
- }
- mt_srand((double)microtime()*1000000*getmypid());
- $password="";
- while(strlen($password)<$len)
- $password.=substr($chars,(mt_rand()%strlen($chars)),1);
- return $password;
- }
- public static function getDateWCn($date) {
- $nStr = array('日','一','二','三','四','五','六');
- $d= date("w",strtotime($date));
- return $nStr[$d];
- }
- public static function getDateDiffDay($d1,$d2) {
- $time_1=strtotime($d1);
- $time_2=strtotime($d2);
- $d=round(abs($time_1-$time_2)/3600/24);
- return $d;
- }
- public static function getDateDiffDayPM($d1,$d2) {
- $time_1=strtotime($d1);
- $time_2=strtotime($d2);
- $d=round(($time_1-$time_2)/3600/24);
- return $d;
- }
- public static function deleteHtml($str)
- {
- $str = trim($str);
- $str = strip_tags($str,"");
- $str = ereg_replace("\t","",$str);
- $str = ereg_replace("\r\n","",$str);
- $str = ereg_replace("\r","",$str);
- $str = ereg_replace("\n","",$str);
- $str = ereg_replace(" ","",$str);
- return trim($str);
- }
- public static function ToChinaseNum($num)
- {
- $char = array("零","一","二","三","四","五","六","七","八","九");
- $dw = array("","十","百","千","万","亿","兆");
- $retval = "";
- $proZero = false;
- for($i = 0;$i < strlen($num);$i++)
- {
- if($i > 0) $temp = (int)(($num % pow (10,$i+1)) / pow (10,$i));
- else $temp = (int)($num % pow (10,1));
- if($proZero == true && $temp == 0) continue;
- if($temp == 0) $proZero = true;
- else $proZero = false;
- if($proZero)
- {
- if($retval == "") continue;
- $retval = $char[$temp].$retval;
- }
- else $retval = $char[$temp].$dw[$i].$retval;
- }
- if($retval == "一十") $retval = "十";
- return $retval;
- }
- /**
- * 人民币小写转大写
- *
- * @param string $number 数值
- * @param string $int_unit 币种单位,默认"元",有的需求可能为"圆"
- * @param bool $is_round 是否对小数进行四舍五入
- * @param bool $is_extra_zero 是否对整数部分以0结尾,小数存在的数字附加0,比如1960.30,
- * 有的系统要求输出"壹仟玖佰陆拾元零叁角",实际上"壹仟玖佰陆拾元叁角"也是对的
- * @return string
- */
- public static function num2rmb($number = 0, $int_unit = '元', $is_round = TRUE, $is_extra_zero = FALSE)
- {
- // 将数字切分成两段
- $parts = explode('.', $number, 2);
- $int = isset($parts[0]) ? strval($parts[0]) : '0';
- $dec = isset($parts[1]) ? strval($parts[1]) : '';
- // 如果小数点后多于2位,不四舍五入就直接截,否则就处理
- $dec_len = strlen($dec);
- if (isset($parts[1]) && $dec_len > 2)
- {
- $dec = $is_round
- ? substr(strrchr(strval(round(floatval("0.".$dec), 2)), '.'), 1)
- : substr($parts[1], 0, 2);
- }
- // 当number为0.001时,小数点后的金额为0元
- if(emptyempty($int) && emptyempty($dec))
- {
- return '零';
- }
- // 定义
- $chs = array('0','壹','贰','叁','肆','伍','陆','柒','捌','玖');
- $uni = array('','拾','佰','仟');
- $dec_uni = array('角', '分');
- $exp = array('', '万');
- $res = '';
- // 整数部分从右向左找
- for($i = strlen($int) - 1, $k = 0; $i >= 0; $k++)
- {
- $str = '';
- // 按照中文读写习惯,每4个字为一段进行转化,i一直在减
- for($j = 0; $j < 4 && $i >= 0; $j++, $i--)
- {
- $u = $int{$i} > 0 ? $uni[$j] : ''; // 非0的数字后面添加单位
- $str = $chs[$int{$i}] . $u . $str;
- }
- //echo $str."|".($k - 2)."<br>";
- $str = rtrim($str, '0');// 去掉末尾的0
- $str = preg_replace("/0+/", "零", $str); // 替换多个连续的0
- if(!isset($exp[$k]))
- {
- $exp[$k] = $exp[$k - 2] . '亿'; // 构建单位
- }
- $u2 = $str != '' ? $exp[$k] : '';
- $res = $str . $u2 . $res;
- }
- // 如果小数部分处理完之后是00,需要处理下
- $dec = rtrim($dec, '0');
- // 小数部分从左向右找
- if(!emptyempty($dec))
- {
- $res .= $int_unit;
- // 是否要在整数部分以0结尾的数字后附加0,有的系统有这要求
- if ($is_extra_zero)
- {
- if (substr($int, -1) === '0')
- {
- $res.= '零';
- }
- }
- for($i = 0, $cnt = strlen($dec); $i < $cnt; $i++)
- {
- $u = $dec{$i} > 0 ? $dec_uni[$i] : ''; // 非0的数字后面添加单位
- $res .= $chs[$dec{$i}] . $u;
- }
- $res = rtrim($res, '0');// 去掉末尾的0
- $res = preg_replace("/0+/", "零", $res); // 替换多个连续的0
- }
- else
- {
- $res .= $int_unit . '整';
- }
- return $res;
- }
- public static function formatTime($date) {
- $str = '';
- $timer = strtotime($date);
- $diff = time() - $timer;
- $day = floor($diff / 86400);
- $free = $diff % 86400;
- if($day > 0) {
- return $day."天前";
- }else{
- if($free>0){
- $hour = floor($free / 3600);
- $free = $free % 3600;
- if($hour>0){
- return $hour."小时前";
- }else{
- if($free>0){
- $min = floor($free / 60);
- $free = $free % 60;
- if($min>0){
- return $min."分钟前";
- }else{
- if($free>0){
- return $free."秒前";
- }else{
- return '刚刚';
- }
- }
- }else{
- return '刚刚';
- }
- }
- }else{
- return '刚刚';
- }
- }
- }
- //获取客户端IP
- public static function getIP() {
- if (getenv('HTTP_CLIENT_IP')) {
- $ip = getenv('HTTP_CLIENT_IP');
- }
- elseif (getenv('HTTP_X_FORWARDED_FOR')) {
- $ip = getenv('HTTP_X_FORWARDED_FOR');
- }
- elseif (getenv('HTTP_X_FORWARDED')) {
- $ip = getenv('HTTP_X_FORWARDED');
- }
- elseif (getenv('HTTP_FORWARDED_FOR')) {
- $ip = getenv('HTTP_FORWARDED_FOR');
- }
- elseif (getenv('HTTP_FORWARDED')) {
- $ip = getenv('HTTP_FORWARDED');
- }
- else {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- return $ip;
- }
- //发送GET或POST请求
- public static function send_post($url, $timeOut, $postData, $postAction) {
- $timeOut = isset($timeOut) ? $timeOut : "20000";
- $postdata = isset($postdata) ? http_build_query($post_data) : "";
- $postAction = isset($postAction) ? $postAction : "POST";
- $options = array(
- 'http' => array(
- 'method' => $postAction,
- 'header' => 'Content-type:application/x-www-form-urlencoded',
- 'content' => $postdata,
- 'timeout' => $timeOut // 超时时间(单位:毫秒)
- )
- );
- $context = stream_context_create($options);
- $result = file_get_contents($url, false, $context);
- //print_r($url."|".$context."|".$result."|");
- return $result;
- }
- public static function getMillisecond() {
- list($s1, $s2) = explode(' ', microtime());
- return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
- }
- public static function getHttpResponsePOST($url, $cacert_url, $para, $input_charset = '') {
- if (trim($input_charset) != '') {
- $url = $url."_input_charset=".$input_charset;
- }
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
- curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
- curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
- curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
- curl_setopt($curl,CURLOPT_POST,true); // post传输数据
- curl_setopt($curl,CURLOPT_POSTFIELDS,$para);// post传输数据
- $responseText = curl_exec($curl);
- //var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
- curl_close($curl);
- return $responseText;
- }
- public static function getHttpResponseGET($url) {
- $curl = curl_init($url);
- //$this_header = array("content-type: text/html;charset=utf-8");
- curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
- curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
- $responseText = curl_exec($curl);
- //var_dump( curl_error($curl) );//如果执行curl过程中出现异常,可打开此开关,以便查看异常内容
- curl_close($curl);
- return $responseText;
- }
- }
- //替换php代码
- function RepPhpAspJspcode($string){
- global $public_r;
- if(!$public_r[candocode]){
- //$string=str_replace("<?xml","[!--ecms.xml--]",$string);
- $string=str_replace("<\\","<\\",$string);
- $string=str_replace("<?","<?",$string);
- $string=str_replace("<%","<%",$string);
- if(@stristr($string,' language'))
- {
- $string=preg_replace(array('!<script!i','!</script>!i'),array('<script','</script>'),$string);
- }
- //$string=str_replace("[!--ecms.xml--]","<?xml",$string);
- }
- return $string;
- }
- //替换php代码
- function RepPhpAspJspcodeText($string){
- //$string=str_replace("<?xml","[!--ecms.xml--]",$string);
- $string=str_replace("<\\","<\\",$string);
- $string=str_replace("<?","<?",$string);
- $string=str_replace("<%","<%",$string);
- if(@stristr($string,' language'))
- {
- $string=preg_replace(array('!<script!i','!</script>!i'),array('<script','</script>'),$string);
- }
- //$string=str_replace("[!--ecms.xml--]","<?xml",$string);
- $string=str_replace("<!--code.start-->","<!--code.start-->",$string);
- $string=str_replace("<!--code.end-->","<!--code.end-->",$string);
- return $string;
- }
- //取得IP
- function egetip(){
- if(getenv('HTTP_CLIENT_IP')&&strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown'))
- {
- $ip=getenv('HTTP_CLIENT_IP');
- }
- elseif(getenv('HTTP_X_FORWARDED_FOR')&&strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown'))
- {
- $ip=getenv('HTTP_X_FORWARDED_FOR');
- }
- elseif(getenv('REMOTE_ADDR')&&strcasecmp(getenv('REMOTE_ADDR'),'unknown'))
- {
- $ip=getenv('REMOTE_ADDR');
- }
- elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown'))
- {
- $ip=$_SERVER['REMOTE_ADDR'];
- }
- $ip=RepPostVar(preg_replace("/^([\d\.]+).*/","\\1",$ip));
- return $ip;
- }
- //取得端口
- function egetipport(){
- $ipport=(int)$_SERVER['REMOTE_PORT'];
- return $ipport;
- }
PHP生成缩略图函数
- function img_create_small($big_img, $width, $height, $small_img) {//原始大图地址,缩略图宽度,高度,缩略图地址
- $imgage = getimagesize($big_img); //得到原始大图片
- switch ($imgage[2]) { // 图像类型判断
- case 1:
- $im = imagecreatefromgif($big_img);
- break;
- case 2:
- $im = imagecreatefromjpeg($big_img);
- break;
- case 3:
- $im = imagecreatefrompng($big_img);
- break;
- }
- $src_W = $imgage[0]; //获取大图片宽度
- $src_H = $imgage[1]; //获取大图片高度
- $tn = imagecreatetruecolor($width, $height); //创建缩略图
- imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
- imagejpeg($tn, $small_img); //输出图像
- }
根据银行卡号判断银行和卡种
bankList.php
- header('Content-type:text/html;charset=utf-8');
- require_once('bankList.php');
- function bankInfo($card,$bankList)
- {
- $card_8 = substr($card, 0, 8);
- if (isset($bankList[$card_8])) {
- echo $bankList[$card_8];
- return;
- }
- $card_6 = substr($card, 0, 6);
- if (isset($bankList[$card_6])) {
- echo $bankList[$card_6];
- return;
- }
- $card_5 = substr($card, 0, 5);
- if (isset($bankList[$card_5])) {
- echo $bankList[$card_5];
- return;
- }
- $card_4 = substr($card, 0, 4);
- if (isset($bankList[$card_4])) {
- echo $bankList[$card_4];
- return;
- }
- echo '该卡号信息暂未录入';
- }
- $bankInfo = bankInfo('6228481552887309119',$bankList);
获取到卡种信息一般都是长字符,根据卡种 ,获取对应的银行
- $bank = strstr($bankInfo,'银行',true).'银行';
根据返回的$bank银行 来让银行列表的下拉框自动选中(ajax返回的$bank):
- // 设置页面Select对象的选中状态
- function getSelectState(selectId, optionValue){
- var sel = document.getElementById(selectId);
- for(var i=0;i<sel.length;i++) {
- if(sel.options[i].value == optionValue) {
- sel.selectedIndex = i;
- break;
- }
- }
- }
调用:
- //json是ajax返回的数据,其实bank则是$bank的银行信息,inputBankName是下拉框的ID值
- getSelectState("inputBankName", json.bank);
php函数serialize()与unserialize()
serialize — 产生一个可存储的值的表示
unserialize — 从已存储的表示中创建 PHP 的值
例:
- Array (
- [bankuser] => yoyo
- [bankname] => 工商银行
- [bankcard] => 6222248745145698840
- [bankPhone] => 15088888888
- [lastNum] => 8840
- )
用serialize函数将这个数组转化为一个序列化的字符串,用于存储进数据库
如:
- <?php
- $arr = serialize($arr);
- print_r($arr);
- //打印出来为:
- //a:4:{s:8:"bankuser";s:6:"yoyo";s:8:"bankname";s:12:"工商银行";s:8:"bankcard";s:19:"6222248745145698840";s:9:"bankPhone";s:11:"15088888888";}
- //
- ?>
读表的时候,读到这串字符的时候,再还原已经序列化的对象
- <?php
- $pet = unserialize($arr);
- ?>
打印出来则恢复数组对象
筛选 / 分页通用接口
- <?php
- //==================================================================
- //函数名: getReferrerIncomes
- //作者: yoyo
- //日期: 2016-09-12
- //功能: 获取提现列表
- //参数:
- //pageNo 当前页数
- //pageSize 每页条数预处理
- //startDate 提现记录的记录开始时间
- //endDate 提现记录的记录结束时间
- //filter 筛选的数据
- //返回值: array
- //修改记录:
- //==================================================================
- public function getReferrerIncomes($post){
- //转换参数形式
- foreach ($post as $kp=>$p) {
- $$kp = $p;
- }
- //页数预处理
- (isset($pageNo) && is_numeric($pageNo)) ? $pageNo = $pageNo : $pageNo = 1;
- //每页条数预处理
- (isset($pageSize) && is_numeric($pageSize)) ? $pageSize = $pageSize : $pageSize = 10;
- //查询状态只能为未审核,审核通过,和提现成功
- $whereA = ' and deleted = 0 and status in("new","success","complete")';
- if($startDate && $endDate ){
- $whereA .= ' and date_added between "'.$startDate.'" and "'.$endDate.'"';
- }
- //过滤筛选条件
- $filter = array(
- 'id' => $id,
- 'user_id' => $userId,
- 'uid' => $uid,
- 'sourse' => $sourse
- );
- //排除条件为空时
- foreach ($filter as $k => $v) {
- if (empty($v)) {
- unset($filter[$k]);
- }
- }
- $s = ' where del_flag=0';
- foreach ($filter as $k=>$v){
- if (is_string($v)) {
- $v = addslashes($v);
- }
- $s .= " and `$k`='$v'";
- }
- $sql = "SELECT count(*) as total FROM `" . DB_PREFIX . "referrer_income`" .$whereA;
- $query = $this->db->query($sql);
- $count = $query->row['total'];
- //获取最大页数
- $pages = ceil($count/$pageSize);
- //如果传递的页码大于总页数,则取最大页数
- if ($pageNo > $pages && $pages!=0) {
- $pageNo = $pages;
- }
- //开始的记录位置
- $start = ($pageNo - 1) * $pageSize;
- //记录范围
- $limit = $pageSize;
- //根据筛选条件获取记录
- $sql = "SELECT * FROM `" . DB_PREFIX . "referrer_income`".$whereA." order by date_added desc limit $start, $limit";
- $rows = $this->getRows($sql);
- foreach ($rows as $key => &$v) {
- $s = '';
- switch ($v['status']) {
- case 'new':
- $status_des = '未审核';
- break;
- case 'invalid':
- $status_des = '无效';
- break;
- case 'nopass':
- $status_des = '审核未通过';
- break;
- case 'complete':
- $status_des = '审核通过';
- break;
- case 'success':
- $status_des = '转账成功';
- break;
- };
- $v['status_des'] => $status_des;
- }
- //返回数组对象
- $res = array(
- 'count' => $count,
- 'pageNo' => $pageNo,
- 'pages' => $pages,
- 'rows' => $rows
- );
- return $res;
- }
PHP判断变量类型 / 判断类型:
- gettype()
用来取得变量的类型。返回的类型字符串可能为下列字符串其中之一:integer、double、string、array、object、unknown type
- is_numeric ( mixed var ):
- //检验测定变量是不是为数码或数码字符串
- is_bool():
- //检验测定变量是不是是布尔型
- is_float():
- //检验测定变量是不是是浮点型 和is_double,is_real()都同样的用法
- is_int():
- //检验测定变量是不是是整儿is_integer()同样的用法
- is_string():
- //检验测定变量是不是是字符串
- is_object():
- //检验测定变量是不是是一个对象
- is_array():
- //检验测定变量是不是是数组
- is_null():
- //检验测定变量是不是为 灭茬 值是不是是灭茬巨细写敏感
通用:
判断是否为对象或数组:
- $obj = [];
- if(is_object($obj)||is_array($obj)){
- return $obj;
- }
PHP实现将科学计数法转换为原始数字字符串的方法
- <?php
- function NumToStr($num){
- if (stripos($num,'e')===false) return $num;
- $num = trim(preg_replace('/[=\'"]/','',$num,1),'"');//出现科学计数法,还原成字符串
- $result = "";
- while ($num > 0){
- $v = $num - floor($num / 10)*10;
- $num = floor($num / 10);
- $result = $v . $result;
- }
- return $result;
- }
- // $bargain['tips2'] = 您今日已砍价 [!--num1--] 次,每个小伙伴每天只能参与 [!--num2--] 次砍价活动哦~
- // num = 1
- // $bargain['user_cut_number'] = 5
- $str1 = [
- "[!--num1--]",
- "[!--num2--]"
- ];
- $str2 = [
- $num,
- $bargain['user_cut_number']
- ];
- $mes = str_replace($str1,$str2,$bargain['tips2']);
- return $mes;
- $str = "[!--num--]";
- $mes = str_replace($str,$num,$bargain['tips2']);
- return $mes;
- private $api_tags_users = "https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token=ACCESS_TOKEN&tagid=TAGID";
- function test(){
- $url = str_replace(['ACCESS_TOKEN', 'TAGID'], [$this->acces->access(), $tagid], $this->api_tags_users);
- return $url;
- }
检测数据类型 (数字,字母,数字+字母,数字+字母+下划线,数字+字母+下划线+点)
- //checkstrtype
- function eCheckStrType($type,$str,$doing=0){
- $ret=0;
- if($type==1)//数字
- {
- if(preg_match('/^[0-9]+$/',$str))
- {
- $ret=1;
- }
- }
- elseif($type==2)//字母
- {
- if(preg_match('/^[A-Za-z]+$/',$str))
- {
- $ret=1;
- }
- }
- elseif($type==3)//字母+数字
- {
- if(preg_match('/^[A-Za-z0-9]+$/',$str))
- {
- $ret=1;
- }
- }
- elseif($type==4)//字母+数字+下划线
- {
- if(preg_match('/^[A-Za-z0-9_]+$/',$str))
- {
- $ret=1;
- }
- }
- elseif($type==5)//字母+数字+下划线+点
- {
- if(preg_match('/^[A-Za-z0-9\-\._]+$/',$str))
- {
- $ret=1;
- }
- }
- else
- {
- $ret=0;
- }
- if($doing)
- {
- if($ret<1)
- {
- exit();
- }
- }
- return $ret;
- }
- /*
- * @最优整数均分算法
- * @param int $number 待平分的数字
- * @param int $taotl 平分总个数
- */
- function getDivideNumber($number, $total) {
- $divide_number = bcdiv($number, $total); // 除法取平均数
- $last_number = bcsub($number, $divide_number * $total); // 获取剩余
- $number_str = str_repeat($divide_number.'|', $total - $last_number); // 拼装平分后的数据
- $number_str2 = str_repeat(($divide_number + 1).'|', $last_number); // 拼装剩下的分配
- $number_str = $number_str . $number_str2; // 组合
- return explode('|', trim($number_str, '|')); // 去掉前后多余的分隔符 返回数组
- }
场景1:在5天内,学习20道知识,平均每天学习几道
- $number = 20; // 在5天内,学习20道题,平均每天推送几道题
- $total = 5;
- $a = self::getDivideNumber($number,$total);
场景2:在6天内,学习20道知识,平均每天学习几道
- $number = 20; // 在6天内,学习20道题,平均每天推送几道题
- $total = 6;
- $a = self::getDivideNumber($number,$total);
如果需要将5放在前面,前面困难一点,后面轻松一点,加一个反向函数
- // 如果需要反向
- p(array_reverse($a));
或者换一下写法:
- /*
- * @最优整数均分算法
- * @param int $number 待平分的数字
- * @param int $taotl 平分总个数
- */
- function getDivideNumber($number, $total) {
- $divide_number = bcdiv($number, $total); // 除法取平均数
- $last_number = bcsub($number, $divide_number * $total); // 获取剩余
- $number_str = str_repeat($divide_number.'|', $total - $last_number); // 拼装平分后的数据
- $number_str2 = str_repeat(($divide_number + 1).'|', $last_number); // 拼装剩下的分配
- $number_str = $number_str2 . $number_str; // 组合
- return explode('|', trim($number_str, '|')); // 去掉前后多余的分隔符 返回数组
- }
- $arr = getDivideNumber(20, 8); //从大到小
- print_r($arr);
待签名的数组:
密钥是:ABCDEFGL
规则是:对传参的数组的key进行排行,然后key value拼接,在前面放上密钥,过程为:
1、排序过后的数组是:
4、密钥全部大写:
- private function getSign($data){
- $secret = "ABCDEFGL";
- // 字母顺序排列
- // 根据数组的键,对关联数组进行升序排列
- ksort($data);
- $signString = "";
- //
- while (list($k, $v) = each($data))
- {
- $tmp = "$k" . "$v";
- $signString .= $tmp;
- }
- $signString = $secret . $signString . $secret;
- $signString = strtoupper(md5($signString));
- return $signString;
- }
15、验证卡号输入是否正确,true是正确,false是不正确
- public function check_bankCard($card_number){
- $arr_no = str_split($card_number);
- $last_n = $arr_no[count($arr_no)-1];
- krsort($arr_no);
- $i = 1;
- $total = 0;
- foreach ($arr_no as $n){
- if($i%2==0){
- $ix = $n*2;
- if($ix>=10){
- $nx = 1 + ($ix % 10);
- $total += $nx;
- }else{
- $total += $ix;
- }
- }else{
- $total += $n;
- }
- $i++;
- }
- $total -= $last_n;
- $x = 10 - ($total % 10);
- if($x == $last_n){
- return true;
- }else{
- return false;
- }
- }