获取文件来源路径
<?php
declare (strict_types = 1);
namespace app\util;
use think\Exception;
use think\facade\Session;
class File{
public function getFileFromPath($path){
set_time_limit(0);
$ret=['code'=>400,'url'=>[],'data'=>[],'message'=>'目录不存在'];
if(is_dir($path)) {
$handler = opendir($path);
while (($filename = readdir($handler)) !== false) {
//略过linux目录的名字为'.'和‘..'的文件
if ($filename != "." && $filename != "..") {
//输出文件名
$ret['code'] = 200;
$ret['url'][] = request()->domain() . '/' . $path . '/' . $filename;
}
}
closedir($handler);
}
return $ret;
}
}
常用公共方法
<?php
// 应用公共文件
function getSysterm(){
$os='';
$Agent=Request()->header('user-agent');
setLog($Agent,'getSysterm','trace');
if (preg_match('/(Windows)/i',$Agent) && strpos($Agent, '95')){
$os='Windows 95';
}elseif(preg_match('/(Windows 9x)/i',$Agent) && strpos($Agent, '4.90')){
$os='Windows ME';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(98)/i',$Agent)){
$os='Windows 98';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(nt 5.0)/i',$Agent)){
$os='Windows 2000';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(nt 6.0)/i',$Agent)){
$os='Windows Vista';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(nt 6.1)/i',$Agent)){
$os='Windows 7';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(nt 5.1)/i',$Agent)){
$os='Windows XP';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(nt)/i',$Agent)){
$os='Windows NT';
}elseif(preg_match('/(Windows)/i',$Agent) && preg_match('/(32)/i',$Agent)){
$os='Windows 32';
}elseif(preg_match('/(linux)/i',$Agent)){
$os='Linux';
}elseif(preg_match('/(unix)/i',$Agent)){
$os='Unix';
}else if(preg_match('/(sun)/i',$Agent) && preg_match('/(os)/i',$Agent)){
$os='SunOS';
}elseif(preg_match('/(ibm)/i',$Agent) && preg_match('/(os)/i',$Agent)){
$os='IBM OS/2';
}elseif(preg_match('/(Mac)/i',$Agent) && preg_match('/(PC)/i',$Agent)){
$os='Macintosh';
}elseif(preg_match('/(PowerPC)/i',$Agent)){
$os='PowerPC';
}elseif(preg_match('/(AIX)/i',$Agent)){
$os='AIX';
}elseif(preg_match('/(HPUX)/i',$Agent)){
$os='HPUX';
}elseif(preg_match('/(NetBSD)/i',$Agent)){
$os='NetBSD';
}elseif(preg_match('/(BSD)/i',$Agent)){
$os='BSD';
}elseif(preg_match('/(OSF1)/i',$Agent)){
$os='OSF1';
}elseif(preg_match('/(IRIX)/i',$Agent)){
$os='IRIX';
}elseif(preg_match('/(FreeBSD)/i',$Agent)){
$os='FreeBSD';
}elseif($os==''){
$os='Unknown';
}
return $os;
}
/*去掉特殊符号
* $str:需要去掉特殊字符的字符串
* $type:1-仅保留数字,2-仅保留英文,3-仅保留中文,4-保留英文和数字,5-保留中英文和数字,6-中国人名,7-中文英文数字和特殊字符,8-身份证,9-仅保留数字和小数点
*
*/
function delSpecilaChar($str,$type){
$pattern='';
switch($type){
case 1:
$pattern='/[(0-9)]+/u';
break;
case 2:
$pattern='/[(a-zA-Z)]+/u';
break;
case 3:
$pattern='/[(\x{4e00}-\x{9fff})]+/u';
break;
case 4:
$pattern='/[(0-9a-zA-Z)]+/u';
break;
case 5:
$pattern='/[(\x{4e00}-\x{9fff}0-9a-zA-Z)]+/u';
break;
case 6:
$pattern='/[(\x{4e00}-\x{9fff}·)]+/u';
break;
case 7:
$pattern='/[(\x{4e00}-\x{9fff}0-9a-zA-Z_·<>\(\)\'\"-—\+\-)]+/u';
break;
case 8:
$pattern='/[(0-9Xx)]+/u';
break;
case 9:
$pattern='/[(0-9.)]+/u';
break;
default:
$pattern='/[(\x{4e00}-\x{9fff}0-9a-zA-Z_·\+\-)]+/u';
break;
}
preg_match_all($pattern, $str, $matches);
$str = join('', $matches[0]);
return $str;
}
//格式化浮点型数字,$amount:待格式化数组,$count保留的小数点位数
function getDecimal($amount,$count=2){
$str='%.'.($count+1).'f';
return substr(sprintf($str, $amount), 0, -1);
}
//生成密钥
//$type:1-全数字,2-全英文,3-英文数字,4-全小写英文,5-全大写英文,6-包含特殊符号
//$qty:密钥长度
function getKey($type,$qty){
$str='';
$chars = 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", "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", ".", ",", "+", "-", "!", "#", '$', '%',
'^', '[', '*', '(', ')', '_', '=', '~', '`', '?'
);
switch($type){
case 1:
for($i=0;$i<$qty;$i++){
$num=rand(0,9);
$str.=$chars[$num];
}
break;
case 2:
for($i=0;$i<$qty;$i++){
$num=rand(10,56);
$str.=$chars[$num];
}
break;
case 3:
for($i=0;$i<$qty;$i++){
$num=rand(0,56);
$str.=$chars[$num];
}
break;
case 4:
for($i=0;$i<$qty;$i++){
$num=rand(10,35);
$str.=$chars[$num];
}
break;
case 5:
for($i=0;$i<$qty;$i++){
$num=rand(36,56);
$str.=$chars[$num];
}
break;
case 6:
for($i=0;$i<$qty;$i++){
$num=rand(0,71);
$str.=$chars[$num];
}
break;
default:
break;
}
return $str;
}
//生成编码日期+数字
//$prex:前缀
//$qty:长度
function getCode($prex='',$qty=10){
$str=strtoupper($prex);
$slen=$qty-strlen($prex);
if($slen<=0){
$str=substr( $str, 0, $slen );
}
if($slen<8){
$str.=getKey(1,$slen);
}
if($slen==8){
$str .= date('dHis');
}
if($slen>8) {
$str .= date('Ymd');
$nqty = $slen - 8;
$blen = 9;
for ($i = 1; $i < $nqty; $i++) {
$blen = $blen*10 + 9;
}
$str .= str_pad(rand(0, $blen), $nqty, '0', STR_PAD_LEFT);
}
return $str;
}
//获取星期方法
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];
}
//获取客户端ip
function getClientIP()
{
foreach (array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key) {
if (array_key_exists($key, $_SERVER)) {
foreach (explode(',', $_SERVER[$key]) as $ip) {
$ip = trim($ip);
//会过滤掉保留地址和私有地址段的IP,例如 127.0.0.1会被过滤
//也可以修改成正则验证IP
if ((bool) filter_var($ip, FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4 |
FILTER_FLAG_NO_PRIV_RANGE |
FILTER_FLAG_NO_RES_RANGE)) {
return $ip;
}
}
}
}
return '';
}
//获取ip归属地-by 太平洋网络
function get_ip_city($ip){
$ch = curl_init();
$url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
//用curl发送接收数据
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//请求为https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$location = curl_exec($ch);
curl_close($ch);
//转码
$location = mb_convert_encoding($location, 'utf-8', 'GB2312');
//var_dump($location);
//截取{}中的字符串
$location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
//将截取的字符串$location中的‘,’替换成‘&’ 将字符串中的‘:‘替换成‘=’
$location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
//php内置函数,将处理成类似于url参数的格式的字符串 转换成数组
parse_str($location, $ip_location);
return $ip_location['addr'];
}
//获取浏览器类型
function getBrower(){
$info='';
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
$agent = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/Windows/i', $agent)) {
$partern='/Windows(.*?);/i';
$arr=[];
preg_match($partern,$agent,$arr);
if ($arr) {
switch ($arr[0]) {
case 'Windows NT 5.0;':
$info .= 'Winows 2000系统 ';
break;
case 'Windows NT 5.1;':
$info .= 'Winows XP系统 ';
break;
case 'Windows NT 6.0;':
$info .= 'Winows Vista系统 ';
break;
case 'Windows NT 6.1;':
$info .= 'Winows 7系统 ';
break;
case 'Windows NT 6.2;':
$info .= 'Winows 8系统 ';
break;
case 'Windows NT 6.3;':
$info .= 'Winows 8.1系统 ';
break;
case 'Windows NT 10.0;':
$info .= 'Winows 10系统 ';
break;
}
}
}
if (preg_match('/Linux/i', $agent)) $info.='Linux系统 ';
if (preg_match('/Macintosh/i', $agent)) $info.='macOS系统 ';
if (preg_match('/MSIE/i', $agent)) {
$info .= ' MSIE浏览器';
} else if (preg_match('/QQ/i', $agent)) {
$info .= ' QQ浏览器';
} else if (preg_match('/Edge/i', $agent)) {
$info .= ' Edge浏览器';
} else if (preg_match('/Firefox/i', $agent)) {
$info .= ' Firefox浏览器';
} else if (preg_match('/Chrome/i', $agent)) {
$info .= ' Chrome浏览器';
} else if (preg_match('/Safari/i', $agent)) {
$info .= ' Safari浏览器';
} else if (preg_match('/Opera/i', $agent)) {
$info .= ' Opera浏览器';
}else if(preg_match('/like Gecko/i',$agent)){
$info .= ' 360浏览器';
}
}
if(!$info) $info=$_SERVER['HTTP_USER_AGENT'];
return $info;
}
/**
* user:Plum
* desc: 校验设备:1pc,2mobile
*/
function checkDevice(){
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
return 2;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA'])) {
// 找不到为flase,否则为true
return stristr($_SERVER['HTTP_VIA'], "wap") ? 2 : 1;
}
// 判断手机发送的客户端标志,兼容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array (
'nokia',
'sony',
'ericsson',
'mot',
'samsung',
'htc',
'sgh',
'lg',
'sharp',
'sie-',
'philips',
'panasonic',
'alcatel',
'lenovo',
'iphone',
'ipod',
'blackberry',
'meizu',
'android',
'netfront',
'symbian',
'ucweb',
'windowsce',
'palm',
'operamini',
'operamobi',
'openwave',
'nexusone',
'cldc',
'midp',
'wap',
'mobile'
);
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
return 2;
}
}
// 协议法,因为有可能不准确,放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT'])){
// 如果只支持wml并且不支持html那一定是移动设备
// 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))){
return 2;
}
}
return 1;
}
/**
* user: Plum
* desc: 图片转base64
* @param $img_file
* @return string
*/
function imgToBase64($img_file) {
$img_base64 = '';
if (file_exists($img_file)) {
$app_img_file = $img_file; // 图片路径
$img_info = getimagesize($app_img_file); // 取得图片的大小,类型等
$fp = fopen($app_img_file, "r");
if ($fp) {
$filesize = filesize($app_img_file);
$content = fread($fp, $filesize);
$file_content = chunk_split(base64_encode($content)); // base64编码
switch ($img_info[2]) { //判读图片类型
case 1: $img_type = "gif";
break;
case 2: $img_type = "jpg";
break;
case 3: $img_type = "png";
break;
}
$img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
}
fclose($fp);
}
return $img_base64; //返回图片的base64
}
//写入修改日记
function setAction($str,$path='',$fileName='action'){
$path= app()->getRootPath() . '/public/action/' . date('Ymd').'/'.$path;
if(!is_dir($path)) mkdir($path,0755,true);
$file=$path.'/'.$fileName.'.txt';
$str=date('Y-d-d H:i:s')."\r\n------------------------".$str."\r\n";
@file_put_contents($file,$str,FILE_APPEND);
}
//写入日志
//str:写入的内容;fileName:写入的文件,默认日期;pathName:写入的目录,默认/publi/log
function setLog($str,$fileName='log',$pathName='log')
{
$path = app()->getRootPath() . '/public/' . $pathName . '/' . date('Ymd');
if(!is_dir($path)) mkdir($path,0775,true);
$file=$path.'/'.$fileName.'.txt';
$str=date('Y-m-d H:i:s')."\r\n------------------------".$str."\r\n";
@file_put_contents($file,$str,FILE_APPEND);
}
//写入调试日志
function setTrace($trace,$fname='trace_exception',$pathName='exception'){
$path = app()->getRootPath() . '/public/'.$pathName.'/' . date('Ymd');
if(!is_dir($path)) mkdir($path,0775,true);
$file=$path.'/'.$fname.'.txt';
@file_put_contents($file,date('Y-m-d H:i:s').' '.$fname.':start---------------------------------------'."\r\n",FILE_APPEND);
foreach($trace as $t){
@file_put_contents($file,json_encode($t)."\r\n",FILE_APPEND);
}
@file_put_contents($file,date('Y-m-d H:i:s').' '.$fname.':end---------------------------------------'."\r\n",FILE_APPEND);
}
//写入xml
function setXml($str,$path='',$fileName=''){
if(!$path) $path=date('Ymd');
$path=app()->getRootPath() . '/public/xml/'.$path.'/';
if(!is_dir($path)) mkdir($path,0775,true);
if(!$fileName) $fileName=date('Ymd');
$file=$path.'/'.$fileName.'.xml';
@file_put_contents($file, $str);
}
//获取13位时间戳
function msectime() {
list($msec, $sec) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
}
//参数进行urlencode+utf-8转码
function utf8Encode($str){
$cur_encoding=mb_detect_encoding($str);
if($cur_encoding!='UTF-8'){
$str=iconv($cur_encoding, "UTF-8",$str);
}
$str=urlencode($str);
return $str;
}
//数组拼接url
function arr_build_url($formdata) {
$rlt = '';
foreach ($formdata as $k => $v) {
if (is_array($v)) {
$rlt .= arr_build_url($v);
} else {
$rlt .= urlencode($k) . '=' . $v . '&';
}
}
trim($rlt,'&');
return $rlt;
}
//类型转换,1-供应商结算方式,2-供应商类型,3-使用状态,4-订单状态
function getSpayAttr($value,$type=1){
switch($type){
case 1:
$arr=[1=>'现金',2=>'月结'];
break;
case 2:
$arr=[1=>'商品',2=>'一件代发'];
break;
case 3:
$arr=[0=>'未使用',1=>'已使用'];
break;
case 4:
$arr=['草稿本','未处理','处理中','外发','异常','发货','完成','售后','暂存','取消'];
break;
default:
$arr=['不可用','未处理','处理中','已处理','处理失败','跳过处理'];
break;
}
return $arr[$value];
}
/**
* @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;
}
//字符串转数字
function strtonum($str){
$arr=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');
$num=0;
$count=strlen($str);
for($i=0;$i<$count;$i++){
$s=$str[$i];
echo $s.'--';
if(is_int($s)){
$num+=$s;
echo $s.'--';
}
if(is_string($s) && in_array($s,$arr)){
$n=array_search($s,$arr)+1;
echo $n.'--';
$num+=$n*10;
}
echo '<br />';
}
return $num;
}
//获取上月日期:
function getlastMonthDays($date){
$timestamp=strtotime($date);
$firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
$lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
return array($firstday,$lastday);
}
//根据日期,获取下一个月
function getNextMonthDays($date){
$timestamp=strtotime($date);
$arr=getdate($timestamp);
if($arr['mon'] == 12){
$year=$arr['year'] +1;
$month=$arr['mon'] -11;
$firstday=$year.'-0'.$month.'-01';
$lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
}else{
$firstday=date('Y-m-01',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)+1).'-01'));
$lastday=date('Y-m-d',strtotime("$firstday +1 month -1 day"));
}
return array($firstday,$lastday);
}
//空间文件排序
function cmp_func($a, $b) {
global $order;
if ($a['is_dir'] && !$b['is_dir']) {
return -1;
} else if (!$a['is_dir'] && $b['is_dir']) {
return 1;
} else {
if ($order == 'size') {
if ($a['filesize'] > $b['filesize']) {
return 1;
} else if ($a['filesize'] < $b['filesize']) {
return -1;
} else {
return 0;
}
} else if ($order == 'type') {
return strcmp($a['filetype'], $b['filetype']);
} else {
return strcmp($a['filename'], $b['filename']);
}
}
}
//获取两个日期的相差的时间
//type:1,天数,2-小时,3-分钟
function diffBetweenTwoDays ($day1, $day2,$type=1){
$second1 = strtotime($day1);
$second2 = strtotime($day2);
if ($second1 < $second2) {
$tmp = $second2;
$second2 = $second1;
$second1 = $tmp;
}
$divisor=86400;
if($type==2) $divisor=1440;
if($type==3) $divisor=60;
return ($second1 - $second2) / $divisor;
}
//生成一个uuid
function guid(){
if (function_exists('com_create_guid')){
return trim(com_create_guid(), '{}');
}else{
mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
$charid = md5(uniqid(rand(), true));
$hyphen = chr(45);
$uuid = substr($charid, 0, 8).$hyphen
.substr($charid, 8, 4).$hyphen
.substr($charid,12, 4).$hyphen
.substr($charid,16, 4).$hyphen
.substr($charid,20,12);
return $uuid;
}
}
//cams加密
function camsSign($data){
$key='NSCeixDrDxzKiRIDjbtbkNl60MzD7KvC';
$str='';
if($data) $str=json_encode($data,JSON_UNESCAPED_UNICODE);
$time=time();
$sign=md5($key.$str.$time.$key);
return ['MockAuth'=>$sign,'TimeSpan'=>$time,'str'=>$str];
}
//获取地址
function getAddress($parentId = 0){
$where=[];
$where[]=['parentId','=',$parentId];
$where[]=['status','=',1];
$address = app\index\model\Address::where($where)->cache('address_'.$parentId,'10')->select();
if (count($address)==0) $address = [];
return $address;
}
//图片转base64
function base64EncodeImage ($image_file,$type=0) {
$image_info = getimagesize($image_file);
$image_data = fread(fopen($image_file, 'r'), filesize($image_file));
$base64_image = base64_encode($image_data);
if($type=1) return 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
return $base64_image;
}
//校验字段值是否已存在
public static function checkValue($userId,$field,$value){
$check = UserInfo::alias('a')
->leftJoin('user b','a.userId=b.id')
->where([
['b.status','=',1],
['a.'.$field,'=',$value]
])
->order('a.id desc')
->find();
$result = !empty($check) && ($check['userId'] != $userId) ? 1 : 0;
if(in_array($field,['mobile','email','qq'])){
$check = User::where($field,$value)->order('id desc')->find();
$result = (!empty($check) && ($check['id'] != $userId)&& $check['status'] == 1) ?1 :0;
}
return $result;
}
//手机号校验
public static function checkMobile($phone){
if(strlen($phone) == 11){
if(!preg_match("/^1[3456789]\d{9}$/",$phone)){
throw new Exception('请填写正确的手机号码');
}
}else{
throw new Exception('手机号码为11位数字!请正确填写!');
}
}
//邮箱格式校验
public static function checkEmail($email){
if(filter_var(strtolower($email),FILTER_VALIDATE_EMAIL)){
return true;
}else{
return false;
}
}