PHP交流群:294088839
Python交流群:652376983
//二维转一维数组 不使用foreach
function arr_one($redo_ip){
$ip = array_reduce($redo_ip, function($ids, $value){
return array_merge($ids, array_values($value));
}, array());
return $ip;
}
//拼接路径
protected function lujing($url,$data){
ksort($data);
$str='';
foreach ($data as $key => $value) {
$str .= '&' . $this->percentEncode($key). '=' . $this->percentEncode($value);
}
$str=trim($str,'&');
$urlHao=$url.'?'.$str;
return $urlHao;
}
//进行Signature签名接过串加密
private function computeSignature($method,$parameters,$AccessKeySecret){
ksort($parameters);
$canonicalizedQueryString = '';
foreach ($parameters as $key => $value) {
$canonicalizedQueryString .= '&' . $this->percentEncode($key). '=' . $this->percentEncode($value);
}
$stringToSign = $method.'&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
$signature = $this->signString($stringToSign, $AccessKeySecret."&");
return $signature;
}
//解析路径里的特殊符号
protected function percentEncode($str){
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
//生成签名字符串
protected function signString($stringToSign,$AccessKeySecret){
return base64_encode(hash_hmac('sha1', $stringToSign, $AccessKeySecret, true));
}
//获取UTC格式的时间
private function utc_time(){
date_default_timezone_set('UTC');
$timestamp = new \DateTime();
$timeStr = $timestamp->format("Y-m-d\TH:i:s\Z");
return $timeStr;
}
//随机数
private function clientToken(){
return $clientToken=md5(uniqid(mt_rand(), true));
}
/**
* @param $arr
* @param $key_name
* @return array
* 将数据库中查出的列表以指定的 id 作为数组的键名
*/
function convert_arr_key($arr, $key_name)
{
$arr2 = array();
foreach($arr as $key => $val)
{
$arr2[$val[$key_name]] = $val;
}
return $arr2;
}
/**
* 对str字符串进行加密,并返回加密过后的字符串
* @param unknown $str 加密后的字符串
*/
function encrypt($str)
{
return md5($str);//'AUTH_CODE' => "TPSHOP"
}
/**
* 获取数组中的某一列
* @param type $arr 数组
* @param type $key_name 列名
* @return type 返回那一列的数组
*/
function get_arr_column($arr, $key_name)
{
$arr2 = array();
foreach($arr as $key => $val)
{
$arr2[] = $val[$key_name];
}
return $arr2;
}
/**
* 获取url 中的各个参数 类似于 pay_code=alipay&bank_code=ICBC-DEBIT
* @param type $str
* @return type
*/
function parse_url_param($str)
{
$data = array();
$parameter = explode('&',end(explode('?',$str)));
foreach($parameter as $val)
{
$tmp = explode('=',$val);
$data[$tmp[0]] = $tmp[1];
}
return $data;
}
/**
* 二维数组排序
* @param $arr
* @param $keys
* @param string $type
* @return array
*/
function array_sort($arr, $keys, $type = 'desc')
{
$key_value = $new_array = array();
foreach ($arr as $k => $v) {
$key_value[$k] = $v[$keys];
}
if ($type == 'asc') {
asort($key_value);
} else {
arsort($key_value);
}
reset($key_value);
foreach ($key_value as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
/**
* 多维数组转化为一维数组
* @param 多维数组
* @return array 一维数组
*/
function array_multi2single($array)
{
static $result_array = array();
foreach ($array as $value) {
if (is_array($value)) {
array_multi2single($value);
} else
$result_array [] = $value;
}
return $result_array;
}
/**
* 友好时间显示
* @param $time
* @return bool|string
*/
function friend_date($time)
{
if (!$time)
return false;
$fdate = '';
$d = time() - intval($time);
$ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
$md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
$byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
$yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
$dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
$td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
$atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
if ($d == 0) {
$fdate = '刚刚';
} else {
switch ($d) {
case $d < $atd:
$fdate = date('Y年m月d日', $time);
break;
case $d < $td:
$fdate = '后天' . date('H:i', $time);
break;
case $d < 0:
$fdate = '明天' . date('H:i', $time);
break;
case $d < 60:
$fdate = $d . '秒前';
break;
case $d < 3600:
$fdate = floor($d / 60) . '分钟前';
break;
case $d < $dd:
$fdate = floor($d / 3600) . '小时前';
break;
case $d < $yd:
$fdate = '昨天' . date('H:i', $time);
break;
case $d < $byd:
$fdate = '前天' . date('H:i', $time);
break;
case $d < $md:
$fdate = date('m月d日 H:i', $time);
break;
case $d < $ld:
$fdate = date('m月d日', $time);
break;
default:
$fdate = date('Y年m月d日', $time);
break;
}
}
return $fdate;
}
/**
* 返回状态和信息
* @param $status
* @param $info
* @return array
*/
function arrayRes($status, $info, $url = "")
{
return array("status" => $status, "info" => $info, "url" => $url);
}
/**
* @param $arr
* @param $key_name
* @param $key_name2
* @return array
* 将数据库中查出的列表以指定的 id 作为数组的键名 数组指定列为元素 的一个数组
*/
function get_id_val($arr, $key_name,$key_name2)
{
$arr2 = array();
foreach($arr as $key => $val){
$arr2[$val[$key_name]] = $val[$key_name2];
}
return $arr2;
}
/**
* 自定义函数 判断 用户选择 从下面的列表中选择 可选值列表:不能为空
* @param type $attr_values
* @return boolean
*/
function checkAttrValues($attr_values)
{
if((trim($attr_values) == '') && ($_POST['attr_input_type'] == '1'))
return false;
else
return true;
}
// 定义一个函数getIP() 客户端IP,
function getIP(){
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else $ip = "Unknow";
return $ip;
}
// 服务器端IP
function serverIP(){
return gethostbyname($_SERVER["SERVER_NAME"]);
}
/**
* 自定义函数递归的复制带有多级子目录的目录
* 递归复制文件夹
* @param type $src 原目录
* @param type $dst 复制到的目录
*/
//参数说明:
//自定义函数递归的复制带有多级子目录的目录
function recurse_copy($src, $dst)
{
$now = time();
$dir = opendir($src);
@mkdir($dst);
while (false !== $file = readdir($dir)) {
if (($file != '.') && ($file != '..')) {
if (is_dir($src . '/' . $file)) {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
}
else {
if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
if (!is_writeable($dst . DIRECTORY_SEPARATOR . $file)) {
exit($dst . DIRECTORY_SEPARATOR . $file . '不可写');
}
@unlink($dst . DIRECTORY_SEPARATOR . $file);
}
if (file_exists($dst . DIRECTORY_SEPARATOR . $file)) {
@unlink($dst . DIRECTORY_SEPARATOR . $file);
}
$copyrt = copy($src . DIRECTORY_SEPARATOR . $file, $dst . DIRECTORY_SEPARATOR . $file);
if (!$copyrt) {
echo 'copy ' . $dst . DIRECTORY_SEPARATOR . $file . ' failed<br>';
}
}
}
}
closedir($dir);
}
//递归删除文件夹
function delFile($dir,$file_type='')
{
if(is_dir($dir))
{
$files = scandir($dir);
//打开目录 //列出目录中的所有文件并去掉 . 和 ..
foreach($files as $filename)
{
if($filename!='.' && $filename!='..')
{
if(!is_dir($dir.'/'.$filename))
{
if(empty($file_type))
{
unlink($dir.'/'.$filename);
}
else
{
if(is_array($file_type))
{
//正则匹配指定文件
if(preg_match($file_type[0],$filename))
{
unlink($dir.'/'.$filename);
}
}
else
{
//指定包含某些字符串的文件
if(false!=stristr($filename,$file_type))
{
unlink($dir.'/'.$filename);
}
}
}
}
else
{
delFile($dir.'/'.$filename);
rmdir($dir.'/'.$filename);
}
}
}
}
else
{
if(file_exists($dir))
{
unlink($dir);
}
}
}
/**
* 多个数组的笛卡尔积
*
* @param unknown_type $data
*/
function combineDika()
{
$data = func_get_args();
$data = current($data);
$cnt = count($data);
$result = array();
$arr1 = array_shift($data);
foreach($arr1 as $key => $item)
{
$result[] = array($item);
}
foreach($data as $key => $item)
{
$result = combineArray($result,$item);
}
return $result;
}
/**
* 两个数组的笛卡尔积
* @param unknown_type $arr1
* @param unknown_type $arr2
*/
function combineArray($arr1,$arr2)
{
$result = array();
foreach ($arr1 as $item1)
{
foreach ($arr2 as $item2)
{
$temp = $item1;
$temp[] = $item2;
$result[] = $temp;
}
}
return $result;
}
/**
* 将二维数组以元素的某个值作为键 并归类数组
* array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
* array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
* @param $arr 数组
* @param $key 分组值的key
* @return array
*/
function group_same_key($arr,$key){
$new_arr = array();
foreach($arr as $k=>$v ){
$new_arr[$v[$key]][] = $v;
}
return $new_arr;
}
/**
* 获取随机字符串
* @param int $randLength 长度
* @param int $addtime 是否加入当前时间戳
* @param int $includenumber 是否包含数字
* @return string
*/
function get_rand_str($randLength=6,$addtime=1,$includenumber=0)
{
if ($includenumber)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
}
else
{
$chars = 'abcdefghijklmnopqrstuvwxyz';
}
$len = strlen($chars);
$randStr = '';
for ($i = 0;$i < $randLength;$i++)
{
$randStr .= $chars[rand(0,$len - 1)];
}
$tokenvalue = $randStr;
if ($addtime)
{
$tokenvalue = $randStr.time();
}
return $tokenvalue;
}
/**
* CURL请求
* @param $url 请求url地址
* @param $method 请求方法 get post
* @param null $postfields post数据数组
* @param array $headers 请求header信息
* @param bool|false $debug 调试开启 默认false
* @return mixed
*/
function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {
$method = strtoupper($method);
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case "POST":
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
$tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
}
break;
default:
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
break;
}
$ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
curl_setopt($ci, CURLOPT_URL, $url);
if($ssl){
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
}
//curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
/*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
$response = curl_exec($ci);
$requestinfo = curl_getinfo($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo "=====info===== \r\n";
print_r($requestinfo);
echo "=====response=====\r\n";
print_r($response);
}
curl_close($ci);
return $response;
//return array($http_code, $response,$requestinfo);
}
/**
* 过滤数组元素前后空格 (支持多维数组)
* @param $array 要过滤的数组
* @return array|string
*/
function trim_array_element($array){
if(!is_array($array))
return trim($array);
return array_map('trim_array_element',$array);
}
/**
* 检查手机号码格式
* @param $mobile 手机号码
*/
function check_mobile($mobile)
{
if(preg_match('/1[34578]\d{9}$/',$mobile))
{
return true;
}
return false;
}
/**
* 检查邮箱地址格式
* @param $email 邮箱地址
*/
function check_email($email){
if(filter_var($email,FILTER_VALIDATE_EMAIL))
return true;
return false;
}
/**
* 实现中文字串截取无乱码的方法
*/
function getSubstr($string, $start, $length) {
if(mb_strlen($string,'utf-8')>$length){
$str = mb_substr($string, $start, $length,'utf-8');
return $str.'...';
}else{
return $string;
}
}
/**
* 判断当前访问的用户是 PC端 还是 手机端 返回true 为手机端 false 为PC 端
* @return boolean
*/
function isMobile(){
$useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
function CheckSubstrs($substrs,$text){
foreach($substrs as $substr)
if(false!==strpos($text,$substr)){
return true;
}
return false;
}
$mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
$mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
$found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||
CheckSubstrs($mobile_token_list,$useragent);
if ($found_mobile){
return true;
}else{
return false;
}
}
//php获取中文字符拼音首字母
function getFirstCharter($str)
{
if(empty($str))
{
return '';
}
$fchar=ord($str{0});
if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
$s1=iconv('UTF-8','gb2312',$str);
$s2=iconv('gb2312','UTF-8',$s1);
$s=$s2==$str?$s1:$str;
$asc=ord($s{0})*256+ord($s{1})-65536;
if($asc>=-20319&&$asc<=-20284) return 'A';
if($asc>=-20283&&$asc<=-19776) return 'B';
if($asc>=-19775&&$asc<=-19219) return 'C';
if($asc>=-19218&&$asc<=-18711) return 'D';
if($asc>=-18710&&$asc<=-18527) return 'E';
if($asc>=-18526&&$asc<=-18240) return 'F';
if($asc>=-18239&&$asc<=-17923) return 'G';
if($asc>=-17922&&$asc<=-17418) return 'H';
if($asc>=-17417&&$asc<=-16475) return 'J';
if($asc>=-16474&&$asc<=-16213) return 'K';
if($asc>=-16212&&$asc<=-15641) return 'L';
if($asc>=-15640&&$asc<=-15166) return 'M';
if($asc>=-15165&&$asc<=-14923) return 'N';
if($asc>=-14922&&$asc<=-14915) return 'O';
if($asc>=-14914&&$asc<=-14631) return 'P';
if($asc>=-14630&&$asc<=-14150) return 'Q';
if($asc>=-14149&&$asc<=-14091) return 'R';
if($asc>=-14090&&$asc<=-13319) return 'S';
if($asc>=-13318&&$asc<=-12839) return 'T';
if($asc>=-12838&&$asc<=-12557) return 'W';
if($asc>=-12556&&$asc<=-11848) return 'X';
if($asc>=-11847&&$asc<=-11056) return 'Y';
if($asc>=-11055&&$asc<=-10247) return 'Z';
return null;
}
/**
* 调试函数,打印变量
*
* @param $input
* @param $inputStr
*/
function printVar($input,$inputStr)
{
echo '<br><br>' . $inputStr . ' = ';
dump($input);
echo '<br><br>';
}
/**
* 根据bookID来获取书籍的封面
*
* @param $bookID
* @return mixed|string
*/
function getBookCoverUrl($bookID)
{
$tmpImgPath = '/' . floor($bookID / 1000) . '/' . $bookID. '/' . $bookID . "s.jpg";
if(file_exists(C('IMAGE_FILE_DIR') . $tmpImgPath))
{
$imgUrl = C('IMAGE_FILE_URL') . $tmpImgPath;
}
else
{
$imgUrl = C('DEFAULT_ARTICLE_COVER');
}
return $imgUrl;
}
/**
* 根据bookID来获取书籍的信息
*
* @param $bookID
* @return mixed
*/
function getBookInfo($bookID)
{
$bookInfo = M('article_article')->where(array('articleid' => $bookID))->getField('articleid,articlename,sortid,author,size,intro,display');
$bookInfo[$bookID]['sort'] = getSortName($bookInfo[$bookID]['sortid']);
// $bookInfo[$bookID]['intro'] = getBookIntro($bookInfo[$bookID]['intro']);
$bookInfo[$bookID]['intro'] = $bookInfo[$bookID]['intro'];
$bookInfo[$bookID]['size'] = getBookWordSum($bookInfo[$bookID]['size']);
return $bookInfo;
}
/**
* 根据sortID来获取书籍分类的名称
*
* @param $sortID
* @return mixed
*/
function getSortName($sortID)
{
$filePath = C('DIR_PATH') . C('SECONDE_SORT_FILE_PATH');
include $filePath;
if(isset($jieqiSort['article']) && $jieqiSort['article'])
{
$sortName = $jieqiSort['article'][$sortID]['caption'];
}
$sortName = iconv('GBK','UTF-8',$sortName);
return $sortName;
}
/**
* 截取30个字的简介
*/
function getBookIntro($bookIntro)
{
if(strlen($bookIntro) > 40)
{
$bookIntro = mb_substr($bookIntro,0,40,'UTF-8');
$bookIntro .= '......';
}
return $bookIntro;
}
/**
* 获取书籍字数
*/
function getBookWordSum($bookSize)
{
//将字数转化为万
$integer = ($bookSize / 2) / 10000;//整数
if($integer >= 1.0)
{
$decimal = ($bookSize / 2) % 10000;//小数
$result = number_format(floatval($integer . '.' . $decimal),2) . '万字';//小说字数
}
else
{
$result = intval($bookSize / 2) . '个字';//小说字数
}
return $result;
}
/**
* 根据$bookList来获取书籍信息
*
* @param $bookList
* @return array
*/
function getBookInfoFromBookList($bookList)
{
foreach($bookList as $item)
{
$flag = articleExist($item);
if($flag)
{
$tmpBook['bookid'] = $item;
$tmpBook['cover'] = getBookCoverUrl($item);
$bookInfo = getBookInfo($item);
$tmpBook['info'] = $bookInfo[$item];
$tmpBook['url'] = U('Article/index',array('id' => $item));
$resultBookList[] = $tmpBook;
}
}
return $resultBookList;
}
/**
* 判断书籍是否存在,存在则为true,不存在为false
*
* @param $articleID
* @return bool
*/
function articleExist($articleID)
{
$count = M('article_article')->where(array('articleid' => $articleID))->count();
//echo $count;exit;
$flag = true;
if(!$count)
{
$flag = false;
}
return $flag;
}
function articleExist1($articleID){
$map['articleid'] = array('in',$articleID);
$res = M('article_article')->field('articleid')->where($map)->select();
if(count($res)==0){
$res = false;
}
return $res;
}
//通过拼接路径get传输访问 url写法
function url($url){
header("Content-type: text/html; charset=UTF-8");
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_HEADER, false);
///curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
// curl_setopt ( $ch, CURLOPT_POST, 1 ); //启用POST提交
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt( $ch, CURLOPT_POSTFIELDS, $map);
$return_str = curl_exec ( $ch );
curl_close ( $ch );
return $return_str;
// parse_str($return_str, $arr1);
// $arr2=json_encode($arr1);
}
/*
用户post的数据 访问 url
*/
function PostData($params)
{
//构造要post的字符串
$length = strlen($params);
//以下参数请按最终 API 发布地址进行修改
$apiHost = "api.22.cn";
$apiPort = 80;
$apiUrl = "/OpenAPI.aspx";
$fp = fsockopen($apiHost,$apiPort,$errno,$errstr,10) or exit($errstr."--->".$errno);
//构造post请求的头
$header = "POST ". $apiUrl . " HTTP/1.1\r\n";
$header .= "Host:" . $apiHost . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".$length."\r\n";
$header .= "Connection: Close\r\n\r\n";
//添加post的字符串
$header .= $params."\r\n";
//发送post的数据
fputs($fp,$header);
$inheader = 1;
$ret="";
while (!feof($fp)) {
$line = fgets($fp,1024); //去除请求包的头只显示页面的返回数据
if ($inheader && ($line == "\n" || $line == "\r\n")) {
$inheader = 0;
}
if ($inheader == 0) {
$ret.=$line;
}
}
fclose($fp);
// $ret = iconv("UTF-8","GB2312",$ret);
//$ret = iconv("BGK","UTF-8",$ret);
// $ret = iconv("GB2312","UTF-8",$ret);
return $ret;
}
/**
* 格式化字节大小
* @param number $size 字节数
* @param string $delimiter 数字和单位分隔符
* @return string 格式化后的带单位的大小
*/
function byteformat($size, $delimiter = '') {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 5; $i++)
$size /= 1024;
return round($size, 2) . $delimiter . $units[$i];
}
/**
* 作用:格式化参数,签名过程需要使用
*/
function formatBizQueryParaMap($paraMap, $urlencode)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v)
{
if($urlencode)
{
$v = urlencode($v);
}
//$buff .= strtolower($k) . "=" . $v . "&";
$buff .= $k . "=" . $v . "&";
}
$reqPar;
if (strlen($buff) > 0)
{
$reqPar = substr($buff, 0, strlen($buff)-1);
}
return $reqPar;
}
//将数组生成xml
function arrayToXml($arr)
{
$xml = "<xml>";
foreach ($arr as $key=>$val)
{
if (is_numeric($val))
{
$xml.="<".$key.">".$val."</".$key.">";
}
else
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
$xml.="</xml>";
return $xml;
}
/**
* 将xml转为array
* @param string $xml
* @throws WxPayException
*/
function FromXml($xml)
{
if(!$xml){
throw new WxPayException("xml数据异常!");
}
//将XML转为array
//禁止引用外部xml实体
libxml_disable_entity_loader(true);
$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $values;
}
//过滤ip
function get_now_ip_list()
{
$a = shell_exec('sudo ifconfig');
preg_match_all('/(dt_\d+)[\s\S]*?inet addr\:(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})[\s\S]*?P\-t\-P\:(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})/', $a, $ips);
unset($ips[0]);
$arr=[];
foreach($ips[1] as $val){
$arr[]= [
'name' => isset($val) ? $val : '',//网卡名字
];
}
foreach($ips[2] as $key=>$val){
$arr[$key]['ip']=isset($val) ? $val : '';
}
foreach($ips[3] as $key=>$val){
$arr[$key]['gateway']=isset($val) ? $val : '';
}
return $arr;
}
//获取随机端口号 写入文件 尽量做到打开一次 全部写入再进行关闭
function port(){
//随机生成端口号范围 (1001-65535) 防止重复
$file= fopen("/etc/squid/dt.conf", "r");
$info=fread($file,filesize("/etc/squid/dt.conf"));
$port=rand(1001,65535);
$num=strrpos($info,$port);
while(!empty($num)){
$port=rand(1001,65535);
$num=strrpos($info,$port);
}
fclose($file);
return $port;
}
//PHP遍历一个文件夹下所有文件和子文件夹的函数
function my_dir($dir) {
$files = array();
if(@$handle = opendir($dir)) { //注意这里要加一个@,不然会有warning错误提示:)
while(($file = readdir($handle)) != = false) {
if($file != ".." && $file != ".") { //排除根目录;
if(is_dir($dir."/".$file)) { //如果是子文件夹,就进行递归
$files[$file] = my_dir($dir."/".$file);
} else { //不然就将文件的名字存入数组;
$files[] = $file;
}
}
}
closedir($handle);
return $files;
}
}
/**
* @param string $dir_name 目录名
* @return mixed|string
*/
static public function dirPath($dir_name)
{
$dirname = str_ireplace("\\", "/", $dir_name);
return substr($dirname, "-1") == "/" ? $dirname : $dirname . "/";
}
/**
* 获得扩展名
* @param string $file 文件名
* @return string
*/
static public function getExt($file)
{
return strtolower(substr(strrchr($file, "."), 1));
}
/**
* 遍历目录内容
* @param string $dirName 目录名
* @param string $exts 读取的文件扩展名
* @param int $son 是否显示子目录
* @param array $list
* @return array
*/
static public function tree($dirName = null, $exts = '', $son = 0,$list = array() )
{
if (is_null($dirName)) $dirName = '.';
$dirPath = self::dirPath($dirName);
static $id = 0;
if (is_array($exts))
$exts = implode("|", $exts);
foreach (glob($dirPath . '*') as $v) {
$id++;
if (is_dir($v) || !$exts || preg_match("/\.($exts)/i", $v)) {
$list [$id] ['type'] = filetype($v);
$list [$id] ['filename'] = basename($v);
$path = str_replace("\\", "/", realpath($v)) . (is_dir($v) ? '/' : '');
$list [$id] ['path']=$path;
$list [$id] ['spath']=ltrim(str_replace(dirname($_SERVER['SCRIPT_FILENAME']),'',$path),'/');
$list [$id] ['filemtime'] = filemtime($v);
$list [$id] ['fileatime'] = fileatime($v);
$list [$id] ['size'] = is_file($v) ? filesize($v) : self::get_dir_size($v);
$list [$id] ['iswrite'] = is_writeable($v) ? 1 : 0;
$list [$id] ['isread'] = is_readable($v) ? 1 : 0;
}
if ($son) {
if (is_dir($v)) {
$list = self::tree($v, $exts, $son = 1, $list);
}
}
}
return $list;
}
/**
* 遍历目录内容【时间控制】
* @param string $dirName 目录名
* @param string $exts 读取的文件扩展名
* @param int $son 是否显示子目录
* @param array $list
* @return array
*/
static public function treeTime($dirName = null,$startDate=0 , $endDate=0, $exts = '', $son = 0,$list = array() )
{
if (is_null($dirName)) $dirName = '.';
$dirPath = self::dirPath($dirName);
static $id = 0;
if (is_array($exts))
$exts = implode("|", $exts);
foreach (glob($dirPath . '*') as $v) {
if(filemtime($v) > $startDate && filemtime($v) < $endDate){
$id++;
if (is_dir($v) || !$exts || preg_match("/\.($exts)/i", $v)) {
$list [$id] ['type'] = filetype($v);
$list [$id] ['filename'] = basename($v);
$path = str_replace("\\", "/", realpath($v)) . (is_dir($v) ? '/' : '');
$list [$id] ['path']=$path;
$list [$id] ['spath']=ltrim(str_replace(dirname($_SERVER['SCRIPT_FILENAME']),'',$path),'/');
$list [$id] ['filemtime'] = filemtime($v);
$list [$id] ['fileatime'] = fileatime($v);
$list [$id] ['size'] = is_file($v) ? filesize($v) : self::get_dir_size($v);
$list [$id] ['iswrite'] = is_writeable($v) ? 1 : 0;
$list [$id] ['isread'] = is_readable($v) ? 1 : 0;
}
if ($son) {
if (is_dir($v)) {
$list = self::tree($v, $exts, $son = 1, $list);
}
}
}
}
return $list;
}
static public function get_dir_size($f)
{
$s = 0;
foreach (glob($f . '/*') as $v) {
$s += is_file($v) ? filesize($v) : self::get_dir_size($v);
}
return $s;
}
/**
* 只显示目录树
* @param null $dirName 目录名
* @param int $son
* @param int $pid 父目录ID
* @param array $dirs 目录列表
* @return array
*/
static public function treeDir($dirName = null, $son = 0, $pid = 0, $dirs = array())
{
if (!$dirName) $dirName = '.';
static $id = 0;
$dirPath = self::dirPath($dirName);
foreach (glob($dirPath . "*") as $v) {
if (is_dir($v)) {
$id++;
$dirs [$id] = array("id" => $id, 'pid' => $pid, "dirname" => basename($v), "dirpath" => $v);
if ($son) {
$dirs = self::treeDir($v, $son, $id, $dirs);
}
}
}
return $dirs;
}
/**
* 删除目录及文件,支持多层删除目录
* @param string $dirName 目录名
* @return bool
*/
static public function del($dirName)
{
if (is_file($dirName)) {
unlink($dirName);
return true;
}
$dirPath = self::dirPath($dirName);
if (!is_dir($dirPath)) return true;
foreach (glob($dirPath . "*") as $v) {
is_dir($v) ? self::del($v) : unlink($v);
}
return @rmdir($dirName);
}
/**
* 批量创建目录
* @param $dirName 目录名数组
* @param int $auth 权限
* @return bool
*/
static public function create($dirName, $auth = 0755)
{
$dirPath = self::dirPath($dirName);
if (is_dir($dirPath))
return true;
$dirs = explode('/', $dirPath);
$dir = '';
foreach ($dirs as $v) {
$dir .= $v . '/';
if (is_dir($dir))
continue;
mkdir($dir, $auth);
}
return is_dir($dirPath);
}
/**
* 复制目录
* @param string $olddir 原目录
* @param string $newdir 目标目录
* @param bool $strip_space 去空白去注释
* @return bool
*/
static public function copy($olddir, $newdir, $strip_space = false)
{
$olddir = self::dirPath($olddir);
$newdir = self::dirPath($newdir);
if (!is_dir($olddir))
error("复制失败:" . $olddir . "目录不存在");
if (!is_dir($newdir))
self::create($newdir);
foreach (glob($olddir . '*') as $v) {
$to = $newdir . basename($v);
if (is_file($to))
continue;
if (is_dir($v)) {
self::copy($v, $to, $strip_space);
} else {
if ($strip_space) {
$data = file_get_contents($v);
file_put_contents($to, strip_space($data));
} else {
copy($v, $to);
}
chmod($to, "0777");
}
}
return true;
}
/**
* 目录下创建安全文件
* @param $dirName 操作目录
* @param bool $recursive 为true会递归的对子目录也创建安全文件
*/
static public function safeFile($dirName, $recursive = false)
{
$file = HDPHP_TPL_PATH . '/index.html';
if (!is_dir($dirName)) {
return;
}
$dirPath = self::dirPath($dirName);
/**
* 创建安全文件
*/
if (!is_file($dirPath . 'index.html')) {
copy($file, $dirPath . 'index.html');
}
/**
* 操作子目录
*/
if ($recursive) {
foreach (glob($dirPath . "*") as $d) {
is_dir($d) and self::safeFile($d);
}
}
}
/**
* 建立请求,以表单HTML形式构造(默认)
* @param $para_temp 请求参数数组
* @param $method 提交方式。两个值可选:post、get
* @param $button_name 确认按钮显示文字
* @return 提交表单HTML文本
*/
function buildRequestForm($para_temp, $method, $button_name) {
//待请求参数数组
$para = $this->buildRequestPara($para_temp);
$sHtml = "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>";
$sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='".$this->alipay_gateway_new."_input_charset=".trim(strtolower($this->alipay_config['input_charset']))."' method='".$method."'>";
while (list ($key, $val) = each ($para)) {
$sHtml.= "<input type='hidden' name='".$key."' value='".$val."'/>";
}
//submit按钮控件请不要含有name属性
$sHtml = $sHtml."<input type='submit' value='".$button_name."' style='display:none;'></form>";
$sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";
return $sHtml;
}
//加密
function encryption($parameter){
$key=get_key();
$info= base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128 ,$key,$parameter , MCRYPT_MODE_ECB, $key));
return $info;
}
//解密
function decryption($parameter){
$key=get__key();
$info= mcrypt_decrypt(MCRYPT_RIJNDAEL_128 ,$key,base64_decode($parameter) , MCRYPT_MODE_ECB, $key);
$info= str_replace("\0","",$info);
return $info;
}
//随机返回二维数组中的值
function rand_ip($ip,$num){
//数组中个数
$temp = array_rand($ip,$num);
$arr=[];
$count=count($ip);
//随机返回个数
for($i=0;$i<$count;$i++){
$arr[]=$ip[$temp[$i]];
}
$arr1=[];
foreach($arr as $v){
if(empty($v)){
unset($v);
}else{
$arr1[]=$v;
}
}
return $arr1;
}
/*
导出CSV
*/
function export_csv($data){
$string="";
foreach ($data as $key => $value)
{
foreach ($value as $k => $val)
{
$value[$k]=iconv('utf-8','gb2312',$value[$k]);
}
$string .= implode(",",$value)."\n"; //用英文逗号分开
}
$filename = date('Ymd').'.csv'; //设置文件名
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo $string;
}
/**
* 判断是否重复添加
* @param string $key 字段名
* @param string $value 字段值
* @param string $table 表名
* @param string $id_key id编号
* @param int $id_value id值
*/
function isRepeat($key,$value,$table,$id_key='',$id_value=0){
$where = $key .'="'.$value.'"';
if($id_key <> ''){
$where.=" and ".$id_key." <> ".$id_value;
}
$rs_count = Db::name($table)->where($where)->count();
return $rs_count;
}
/**
* 把返回的数据集转换成Tree
* @param array $list 要转换的数据集
* @param string $pid parent标记字段
*/
//菜单表
CREATE TABLE `idc_admin_auth_rule` (
`rule_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`rule_url` varchar(80) DEFAULT NULL COMMENT '路径',
`rule_name` varchar(30) DEFAULT NULL COMMENT '名字',
`rule_status` tinyint(1) DEFAULT '1' COMMENT '激活与禁用',
`rule_remak` varchar(100) DEFAULT NULL COMMENT '备注',
`rule_pid` int(11) DEFAULT NULL,
`rule_time` int(11) DEFAULT NULL,
`rule_level` smallint(100) DEFAULT NULL COMMENT '分类等级',
PRIMARY KEY (`rule_id`)
) ENGINE=InnoDB AUTO_INCREMENT=77 DEFAULT CHARSET=utf8;
function getTree($list, $pid = 0){
$tree = [];
if(!empty($list)){
//先修改为以id为下标的列表
$newList = [];
foreach ($list as $k => $v) {
$newList[$v['rule_id']] = $v;
}
//然后开始组装成特殊格式
foreach ($newList as $value) {
if ($pid == $value['rule_pid']) {//先取出顶级
$tree[] = &$newList[$value['rule_id']];
}
elseif (isset($newList[$value['rule_pid']])) {
//再判定非顶级的pid是否存在,如果存在,则再pid所在的数组下面加入一个字段items,来将本身存进去
$newList[$value['rule_pid']]['items'][] = &$newList[$value['rule_id']];
}
}
}
return $tree;
}
//格式化tree
function formatTree($tree){
$options = [];
$cat = [];
$prefix = [];
if (!empty($tree)){
foreach($tree as $key => $value){
$prefix = str_repeat('--',$value['rule_level']);
if($value['rule_level'] > 0){
$prefix = '|'.$prefix;
}
$prefix = str_repeat(' ',$value['rule_level']).$prefix;
$cat['rule_id'] = $value['rule_id'];
$cat['rule_pid'] = $value['rule_pid'];
if($value['rule_level'] > 0){
$cat['rule_name'] = $prefix.$value['rule_name'];
}
else{
$cat['rule_name'] = '<strong>'.$value['rule_name'].'<>';
}
$cat['rule_level'] = $value['rule_level'];
if (isset($value['items'])) {
$cat['is_disable'] = 1;
}
else{
$cat['is_disable'] = 0;
}
$options[$value['rule_id']] = $cat;
//echo "<pre>";print_r($options);echo "<pre>";
if (isset($value['items'])) {//查询是否有子节点
$optionsTmp = formatTree($value['items']);
$options = $options+$optionsTmp;
}
else{
$prefix = '';
}
}
}
return $options;
}
//字符串转十六进制
function strToHex($string)
{
$hex="";
$tmp="";
for($i=0;$i<strlen($string);$i++)
{
$tmp = dechex(ord($string[$i]));
$hex.= strlen($tmp) == 1 ? "0".$tmp : $tmp;
}
$hex=strtoupper($hex);
return $hex;
}
/**
* 获取客户端IP地址
* @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param boolean $adv 是否进行高级模式获取(有可能被伪装)
* @return mixed
*/
function get_client_ip($type = 0,$adv=false) {
$type = $type ? 1 : 0;
static $ip = NULL;
if ($ip !== NULL) return $ip[$type];
if($adv){
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$long = sprintf("%u",ip2long($ip));
$ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
return $ip[$type];
}
//格式化时间
function vtime($time) {
$output = '';
foreach (array(86400 => '天', 3600 => '小时', 60 => '分', 1 => '秒') as $key => $value) {
if ($time >= $key) $output .= floor($time/$key) . $value;
$time %= $key;
}
if($output==''){
$output=0;
}
return $output;
}
/**
* 功能:二维数组diff
* 说明:找出数组$arr1中存在的value值,
* $arr2不存在的值value
* 举例:$arr1=['a'=>1,'b'=>2];$arr2=['c'=>2,'d'=>4];
* 输出:['a'=>1];
*/
public static function deep_diff_array($arr1, $arr2)
{
try {
return array_filter($arr1, function ($v) use ($arr2) {
return !in_array($v, $arr2);
});
} catch (Exception $exception) {
return $arr1;
}
}
/**
* 功能:递归创建文件夹
* 说明:此方法跟命令 mkdir -p $dir效果相同,
* 在上级目录不存在时自动创建上级目录
* 举例:$dir='/var/local/tang/zhi/qin'
*/
public static function create_dir($dir)
{
$dirname = dirname($dir);
//判断上一个文件夹是否存在
if (!file_exists($dirname)) {
self::create_dir($dirname);
}
mkdir($dir, 0777);
}
/**
* 功能:倒计时
* 说明:$begin_time开始时间,$end_time,结束时间
* 举例:输入$begin_time=time();$end_time="2019-05-01";
*/
public static function time_diff( $begin_time, $end_time )
{
if ( $begin_time < $end_time ) {
$starttime = $begin_time;
$endtime = $end_time;
} else {
$starttime = $end_time;
$endtime = $begin_time;
}
$timediff = $endtime - $starttime;
$days = intval( $timediff / 86400 );
$remain = $timediff % 86400;
$hours = intval( $remain / 3600 );
$remain = $remain % 3600;
$mins = intval( $remain / 60 );
$secs = $remain % 60;
$res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
return $res;
}
/**
* 功能:单位换算
* 说明:$num输入数字,$unit输入的单位(默认为空),
* $point保留小数(默认两位)
* 举例:输入:$num=10000;$unit='';$point=3;
* 输出:['value'=>1.000,'unit'=>'万']
*/
public static function unit_convert($num, $unit='', $point = 2)
{
if (!$num) {
return false;
}
$neg = $num < 0?true:false;
if ($neg) {
$num = $num*pow(-1, 1);
}
if (empty($unit) || $unit == '万' || $unit == '亿' || $unit == '万亿') {
$tmp = explode('.', $num);
while(strlen(array_shift($tmp))>4) {
$num = $num/10000;
$tmp = explode('.', $num);
if (empty($unit)) {
$unit = '万';
} elseif ($unit == '万') {
$unit = '亿';
} elseif ($unit == '亿') {
$unit = '万亿';
} elseif ($unit == '万亿') {
$unit = '万兆';
} else {
$num = $num*10000;
break;
}
}
$num = sprintf('%01.'.$point.'f', $num);
} else {
$num = sprintf('%01.'.$point.'f', $num);
}
return array(
'value'=> $neg?$num*pow(-1, 1):$num,
'unit' => $unit
);
}
/**
* 功能:快速排序
* 说明:$arr数字数组,输出结果顺序为ASC
* 举例:输入:[3,2,7,9,1]
* 输出:[1,2,3,7,9]
*/
public static function quick_sort($arr)
{
if(!is_array($arr)) {
return false;
}
$len = count($arr);
if ( $len<= 1) {
return $arr;
}
//选取分界点值
$middle = $arr[0];
//接受左右值
$left=$right = array();
// 循环比较
for ($i=1; $i < $len; $i++) {
if ($middle < $arr[$i]) {
// 大于分界点值
$right[] = $arr[$i];
} else {
// 小于分界点值
$left[] = $arr[$i];
}
}
// 递归排序划分好的2边
$left = self::quick_sort($left);
$right = self::quick_sort($right);
// 合并排序后的数据
return array_merge($left, [$middle], $right);
}
/**
*获取真实IP
*/
public static function get_real_ip()
{
static $realip;
if(isset($_SERVER)){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$realip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}else if(isset($_SERVER['HTTP_CLIENT_IP'])){
$realip=$_SERVER['HTTP_CLIENT_IP'];
}else{
$realip=$_SERVER['REMOTE_ADDR'];
}
}else{
if(getenv('HTTP_X_FORWARDED_FOR')){
$realip=getenv('HTTP_X_FORWARDED_FOR');
}else if(getenv('HTTP_CLIENT_IP')){
$realip=getenv('HTTP_CLIENT_IP');
}else{
$realip=getenv('REMOTE_ADDR');
}
}
return $realip;
}
/**
*获取设备
*/
public static function get_client_device()
{
//获取USER AGENT
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
//分析数据
$is_pc = (strpos($agent, 'windows nt')) ? true : false;
$is_iphone = (strpos($agent, 'iphone')) ? true : false;
$is_ipad = (strpos($agent, 'ipad')) ? true : false;
$is_android = (strpos($agent, 'android')) ? true : false;
//输出数据
if($is_pc){
return 'pc';
}
if($is_iphone){
return 'iPhone';
}
if($is_ipad){
return "iPad";
}
if($is_android){
return "Android";
}
return "No Agent";
}
/**
* 功能:curl_get_post请求
* 说明:$url为链接,$post为字符串(例:"a=22&b=44")
*/
public static function curl_get($url, $post='')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
/*curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER, _REFERER_);*/
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
if ($post) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($post));
}
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
/**
* 功能:保持长连接post
* 说明:$url为链接,$param为key-value数组
*/
public static function curl_post($url, $param)
{
$post = array();
if ($param) {
foreach($param as $k=>$v) {
if ($v != '') {
$post[] = urlencode($k).'='.urlencode($v);
}
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
$header = array(
'Connection:Keep-Alive'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, implode('&', $post));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = unserialize(curl_exec($ch));
curl_close($ch);
return $result;
}
/**
* 功能:读取配置文件,以数组形式输出
*/
public static function get_ini_config($filename)
{
if (!file_exists($filename)) {
return false;
}
$result = parse_ini_file($filename, $true);
return $result;
}
/**
* 功能:获取目录下文件列表
* 说明:$type=all/linux,all所有系统可用
*/
public static function get_file_list($path, $type='all')
{
if (!is_dir($path)) {
return false;
}
$dir = array();
if ($type == 'all') {
if ($handle = opendir($path)) {
while ($file = readdir($handle)) {
if ($file != '.' && $file != '..') {
$dir[] = $file;
}
}
}
}
if ($type == 'linux') {
ob_start();
system("ls -m " . $path);
$dir = explode(",", preg_replace("/\s*(.*?)\s*,/", "$1,", ob_get_contents() . ','));
array_pop($dir);
ob_end_clean();
}
return $dir;
}
}
/*
*PHP 实现绝对路径文件下载
*/
public function download()
{
$famlePath = $_GET['resum'];
$file_dir = str_replace('\\','/',$famlePath); // 下载文件存放目录
$file_dir= iconv('UTF-8','GB2312',$file_dir);
// 检查文件是否存在
if (! file_exists($file_dir) ) {
$this->error('文件未找到',url("Index/index"));
}else{
// 打开文件
$file1 = fopen($file_dir, "r");
// 输入文件标签
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:".filesize($file_dir));
Header("Content-Disposition: attachment;filename=" . $file_dir);
ob_clean(); // 重点!!!
flush(); // 重点!!!!可以清除文件中多余的路径名以及解决乱码的问题:
//输出文件内容
//读取文件内容并直接输出到浏览器
echo fread($file1, filesize($file_dir));
fclose($file1);
exit();
}
}
//在图片上打验证码
private function verifyCode($session_id,$type=1,$length=4,$width=100,$height=40){
//第一步:创建画布,获取图像资源
$img = imagecreatefrompng("./bg_yzm.png");
$white = imagecolorallocate($img , 255 , 255 , 255);
imagefill($img , 0 , 0 , $white);
imagecolortransparent($img , $white );
// $img=imagecreatetruecolor($width,$height);
//第二步:操作图像资源
//分配背景色
// $backColor=imagecolorallocate($img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255));
//填充背景颜色
// imagefill($img,0,0,$backColor);
//随机生成字符串
$str=rand(1000,9999);
//将产生的随机字符串存入redis
$this->setVer($str,$session_id);
//分配文字颜色
$fontColor=imagecolorallocate($img,mt_rand(0,100),mt_rand(0,100),mt_rand(0,100));
//准备字体
$fonts=array('2.ttf');
$font='./vendor/topthink/think-captcha/assets/ttfs/'.$fonts[array_rand($fonts)];
//写入字符串
imagettftext($img,mt_rand(20,25),mt_rand(-10,10),mt_rand(5,10),mt_rand(25,30),$fontColor,$font,$str);
//写点干扰项
for($i=1;$i<=500;$i++){
imagesetpixel($img,mt_rand(0,$width),mt_rand(0,$height),imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150)));
}
//写线干扰项
for($n=1;$n<=20;$n++){
$x=mt_rand(0,$width);
$y=mt_rand(0,$height);
imageline($img,$x,$y,$x+rand(-50,50),$y+rand(-50,50),imagecolorallocate($img,mt_rand(50,150),mt_rand(50,150),mt_rand(50,150)));
}
//第三步:输出图像
header('Content-type:image/png');
imagesavealpha($img,true);
imagepng($img);
//第四步:销毁图像资源,释放内存
imagedestroy($img);
$content = ob_get_clean();
return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
}
//二维数组去重 根据key
function arr_uniq($arr,$key){
$key_arr = [];
foreach ($arr as $k => $v) {
if (in_array($v[$key],$key_arr)) {
unset($arr[$k]);
} else {
$key_arr[] = $v[$key];
}
}
return $arr;
}
/* * 获取日期对应的星期 * 参数$date为输入的日期数据,格式如:2018-6-22 */ function get_week($date) { //强制转换日期格式 $date_str = date('Y-m-d', strtotime($date)); //封装成数组 $arr = explode("-", $date_str); //参数赋值 //年 $year = $arr[0]; //月,输出2位整型,不够2位右对齐 $month = sprintf('%02d', $arr[1]); //日,输出2位整型,不够2位右对齐 $day = sprintf('%02d', $arr[2]); //时分秒默认赋值为0; $hour = $minute = $second = 0; //转换成时间戳 $strap = mktime($hour, $minute, $second, $month, $day, $year); //获取数字型星期几 $number_wk = date("w", $strap); //自定义星期数组 $weekArr = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"); //获取数字对应的星期 return $weekArr[$number_wk]; }