常用的php函数

最严格身份证号码验证,支持15位和19世纪出生的人的身份证号码
# 计算身份证校验码,根据国家标准GB 11643-1999 
function idcard_verify_number($idcard_base){ 
 if(strlen($idcard_base)!=17){ 
 return false; 
 } 
//加权因子 
$factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2); 
//校验码对应值 
$verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2'); 
$checksum=0; 
for($i=0;$i<strlen($idcard_base);$i++){ 
$checksum += substr($idcard_base,$i,1) * $factor[$i]; 
} 
$mod=$checksum % 11; 
$verify_number=$verify_number_list[$mod]; 
return $verify_number; 
} 
# 将15位身份证升级到18位 
function idcard_15to18($idcard){ 
if(strlen($idcard)!=15){ 
return false; 
}else{ 
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码 
if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){ 
$idcard=substr($idcard,0,6).'18'.substr($idcard,6,9); 
}else{ 
$idcard=substr($idcard,0,6).'19'.substr($idcard,6,9); 
} 
} 
$idcard=$idcard.idcard_verify_number($idcard); 
return $idcard; 
} 

 //循环创建目录  要用/结尾
function create_dirs($path){
if (!is_dir($path)){
$directory_path = "";
$directories = explode("/",$path);
array_pop($directories);
foreach($directories as $directory){
$directory_path .= $directory."/";
if (!is_dir($directory_path)){
mkdir($directory_path);
chmod($directory_path, 0777);
}
}
}
}

/**
* 写日志
* @param string $log 日志信息
* @param string $type 日志类型 [system|app|...]
* @param string $level 日志级别
* @return boolean
*/
function write_log($log, $type = 'default', $level = 'log'){
date_default_timezone_set('PRC');
if(!defined('INSTALL_PATH')){
return;
}
$now_time = date('H:i:s');
$target = 'log/'.date("Ym").'/' ;
mk_dir($target);
if (!path_writeable($target)){
exit('path can not write!');
}
$ext = '.log';
//.php .log;
$target .= date('Y_m_d').'_'.$level.$ext;
//检测日志文件大小, 超过配置大小则重命名
if (file_exists($target) && get_filesize($target) >= 1024*1024*10) {
$fileName = substr(basename($target),0,strrpos(basename($target),$ext)).date('H:i:s').$ext;
$re = rename($target, dirname($target) .'/'. $fileName);
}
if(!file_exists($target)){
error_log("$now_time $type $log\n", 3,$target);
}

if(is_object($log) || is_array($log)){
$log = json_encode_force($log);
}
clearstatcache();
return error_log("$now_time $type $log\n", 3, $target);
}

/**
* 循环删除目录和文件
* @param string $dir_name
* @return bool
*/
function delete_dir_file($dirName)
{
$result = false;
if ($handle = opendir($dirName)) {
while (false !== ($item = readdir($handle))) {
if ($item != "." && $item != "..") {
if (is_dir("$dirName/$item")) {
delete_dir_file("$dirName/$item");
} else {
//删除文件
unlink("$dirName/$item");
}
}
}
closedir($handle);
//删除空文件夹
if (rmdir($dirName)) {
$result = true;
}
return $result;
}
}
/**
* 判断是否为手机访问
* @return boolean
*/
function is_mobile()
{
static $is_mobile;

if (isset($is_mobile)) {
return $is_mobile;
}

if (empty($_SERVER['HTTP_USER_AGENT'])) {
$is_mobile = false;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
) {
$is_mobile = true;
} else {
$is_mobile = false;
}

return $is_mobile;
}

/**
* 手机号格式检查
* @param string $mobile
* @return bool
*/
function check_mobile_number($mobile)
{
if (!is_numeric($mobile)) {
return false;
}
$reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

return preg_match($reg, $mobile) ? true : false;
}

/**
* 友好的时间显示
*
* @param int $sTime 待显示的时间
* @param string $type 类型. normal | mohu | full | ymd | other
* @param string $alt 已失效
* @return string
*/
function friendlyDate($sTime,$type = 'normal',$alt = 'false') {
if (!$sTime)
return '';
//sTime=源时间,cTime=当前时间,dTime=时间差
$cTime = time();
$dTime = $cTime - $sTime;
$dDay = intval(date("z",$cTime)) - intval(date("z",$sTime));
//$dDay = intval($dTime/3600/24);
$dYear = intval(date("Y",$cTime)) - intval(date("Y",$sTime));
//normal:n秒前,n分钟前,n小时前,日期
if($type=='normal'){
if( $dTime < 60 ){
if($dTime < 10){
return '刚刚'; //by yangjs
}else{
return intval(floor($dTime / 10) * 10)."秒前";
}
}elseif( $dTime < 3600 ){
return intval($dTime/60)."分钟前";
//今天的数据.年份相同.日期相同.
}elseif( $dYear==0 && $dDay == 0 ){
//return intval($dTime/3600)."小时前";
return '今天'.date('H:i',$sTime);
}elseif($dYear==0){
return date("m月d日 H:i",$sTime);
}else{
return date("Y-m-d H:i",$sTime);
}
}elseif($type=='mohu'){
if( $dTime < 60 ){
return $dTime."秒前";
}elseif( $dTime < 3600 ){
return intval($dTime/60)."分钟前";
}elseif( $dTime >= 3600 && $dDay == 0 ){
return intval($dTime/3600)."小时前";
}elseif( $dDay > 0 && $dDay<=7 ){
return intval($dDay)."天前";
}elseif( $dDay > 7 && $dDay <= 30 ){
return intval($dDay/7) . '周前';
}elseif( $dDay > 30 ){
return intval($dDay/30) . '个月前';
}
//full: Y-m-d , H:i:s
}elseif($type=='full'){
return date("Y-m-d , H:i:s",$sTime);
}elseif($type=='ymd'){
return date("Y-m-d",$sTime);
}else{
if( $dTime < 60 ){
return $dTime."秒前";
}elseif( $dTime < 3600 ){
return intval($dTime/60)."分钟前";
}elseif( $dTime >= 3600 && $dDay == 0 ){
return intval($dTime/3600)."小时前";
}elseif($dYear==0){
return date("Y-m-d H:i:s",$sTime);
}else{
return date("Y-m-d H:i:s",$sTime);
}
}
}

/**
* 二维数组合并
* @param string $
* @return
*/
function arr_map($arr)
{
foreach($arr as $k => $v){
foreach($v as $k1 => $v2){
$new_arr[$k1][$k] = $v2;
}
}
return $new_arr;
}

/**
* 对一个给定的二维数组按照指定的键值进行排序
* @return array
*/
function array_sort($arr,$keys,$type='asc'){
$keysvalue = $new_array = array();
foreach ($arr as $k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type == 'asc'){
asort($keysvalue);
}else{
arsort($keysvalue);
}
reset($keysvalue);
foreach ($keysvalue as $k=>$v){
$new_array[$k] = $arr[$k];
}
return $new_array;
}

/**
* 时间日期格式化为多少天前
* @param sting|intval $date_time
* @param intval $type 1、'Y-m-d H:i:s' 2、时间戳
* @return string
*/
function format_datetime($date_time,$type=1,$format=false){
if($type == 1){
$timestamp = strtotime($date_time);
}elseif($type == 2){
$timestamp = $date_time;
$date_time = date('Y-m-d H:i:s',$date_time);
}
if($format==true){
return date($format,$timestamp);
}
$difference = time()-$timestamp;
if($difference <= 180){
return '刚刚';
}elseif($difference <= 3600){
return ceil($difference/60).'分钟前';
}elseif($difference <= 86400){
return ceil($difference/3600).'小时前';
}elseif($difference <= 2592000){
return ceil($difference/86400).'天前';
}elseif($difference <= 31536000){
return ceil($difference/2592000).'个月前';
}else{
return ceil($difference/31536000).'年前';
//return $date_time;
}
}

/*
* 获取随机字符串
*
*@param intval $len 随机长度
*
*
*/
function getRandomString($len, $chars=null)
{
if (is_null($chars)){
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
mt_srand(10000000*(double)microtime());
for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
$str .= $chars[mt_rand(0, $lc)];
}
return $str;
}

/**
* 获取文件列表(所有子目录文件)
*
* @param string $path 目录
* @param array $file_list 存放所有子文件的数组
* @param array $ignore_dir 需要忽略的目录或文件
* @return array 数据格式的返回结果
*/
function read_file_list($path, &$file_list, $ignore_dir = array())
{
$path = rtrim($path, '/');
if (is_dir($path)) {
$handle = @opendir($path);
if ($handle) {
while (false !== ($dir = readdir($handle))) {
if ($dir != '.' && $dir != '..') {
if (!in_array($dir, $ignore_dir)) {
if (is_file($path . '/' . $dir)) {
$file_list[] = $path . '/' . $dir;
}
elseif (is_dir($path . '/' . $dir)) {
read_file_list($path . '/' . $dir, $file_list, $ignore_dir);
}
}
}
}
@closedir($handle);
}
else {
return false;
}
}
else {
return false;
}
}

/**
* 字符串切割函数,一个字母算一个位置,一个字算2个位置
*
* @param string $string 待切割的字符串
* @param int $length 切割长度
* @param string $dot 尾缀
*/
function str_cut($string, $length, $dot = '')
{
$string = str_replace(array(
'&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;',
'&middot;', '&hellip;'
), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strlen = strlen($string);
if ($strlen <= $length)
return $string;
$maxi = $length - strlen($dot);
$strcut = '';

$n = $tn = $noc = 0;
while ($n < $strlen) {
$t = ord($string[$n]);
if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1;
$n++;
$noc++;
}
elseif (194 <= $t && $t <= 223) {
$tn = 2;
$n += 2;
$noc += 2;
}
elseif (224 <= $t && $t < 239) {
$tn = 3;
$n += 3;
$noc += 2;
}
elseif (240 <= $t && $t <= 247) {
$tn = 4;
$n += 4;
$noc += 2;
}
elseif (248 <= $t && $t <= 251) {
$tn = 5;
$n += 5;
$noc += 2;
}
elseif ($t == 252 || $t == 253) {
$tn = 6;
$n += 6;
$noc += 2;
}
else {
$n++;
}
if ($noc >= $maxi)
break;
}
if ($noc > $maxi)
$n -= $tn;
$strcut = substr($string, 0, $n);
$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
return $strcut . $dot;
}

/**
* 取得随机数
*
* @param int $length 生成随机数的长度
* @param int $numeric 是否只产生数字随机数 1是0否
* @return string
*/
function random($length, $numeric = 0)
{
$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
$hash = '';
$max = strlen($seed) - 1;
for ($i = 0; $i < $length; $i++) {
$hash .= $seed{mt_rand(0, $max)};
}
return $hash;
}

/**
* 将字符部分加密并输出
* @param unknown $str
* @param unknown $start 从第几个位置开始加密(从1开始)
* @param unknown $length 连续加密多少位
* @return string
*/
function encrypt_show($str, $start, $length)
{
$end = $start - 1 + $length;
$array = str_split($str);
foreach ($array as $k => $v) {
if ($k >= $start - 1 && $k < $end) {
$array[$k] = '*';
}
}
return implode('', $array);
}

/**
* CURL请求
* @param $url 请求url地址
* @param $method 请求方法 get post
* @param null $postfields post数据数组
* @param array $headers 请求header信息
* @param bool|false $debug 调试开启 默认false
* @return mixed
*/
function http_request($url, $method = "GET", $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;
}



 

posted @ 2019-11-18 17:10  离岸少年  阅读(147)  评论(0编辑  收藏  举报