<?php
/**
* [普通,高密度下可能产生碰撞]生成指定长度的密码. 目前的需求只有提取码分享,只用到数字和大写字母.
* @param int $len 密码长度
* @param int $type 类型 (0:大写字母数字;1:大写字母;2:仅数字;3:小写字母数字;4:小写字母;5:大小写字母数字)
*/
public static function genSecret($len = 4, $type = 0, $extwords = '')
{
$secret = '';
switch ($type) {
case 0:
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
break;
case 1:
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 2:
$pool = '1234567890';
break;
case 3:
$pool = 'abcdefghijklmnopqrstuvwxyz1234567890';
break;
case 4:
$pool = 'abcdefghijklmnopqrstuvwxyz';
break;
case 5:
$pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz';
break;
}
$pool .= $extwords;
$lenPool = strlen($pool) - 1;
for ($i = 0; $i < $len; $i++) {
$secret .= $pool[mt_rand(0, $lenPool)];
}
return $secret;
}
/**
* [高级,碰撞较低]生成指定长度的随机字符串
* @attention 包含数字和字母,格式:[0-9a-zA-Z]
* @param $length int 字符串长度
* @param $sens bool 是否大小写敏感
* @return bool|string
*/
public static function genRandom($length = 20, $sens = TRUE)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyz';
if ($sens) {
$pool .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($length * 2);
if ($bytes === FALSE) return FALSE;
return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length);
}
}
return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}
/**
* 根据count数目来输出字符
* <code>
* echo Common::split_by_count(20, 10, 20, 30, 40, 50);
* </code>
*
* @access public
* @return string
*/
public static function split_by_count($count)
{
$sizes = func_get_args();
array_shift($sizes);
foreach ($sizes as $size) {
if ($count < $size) {
return $size;
}
}
return 0;
}
/**
* 按分割数输出字符串
*
* @access public
* @param string $param 需要输出的值
* @return integer
*/
public function split($count)
{
$args = func_get_args();
array_unshift($args, $count);
return call_user_func_array(array('Common', 'split_by_count'), $args);
}
/**
* 过滤用于搜索的字符串
*
* @access public
* @param string $query 搜索字符串
* @return string
*/
public static function filter_search($query)
{
return str_replace(array('%', '?', '*', '/', '{', '}'), '', $query);
}
/**字符串脚本注入过滤
*
* @param string $query 原始字符串
* @return string
*/
public static function inject_replace($query)
{
$string = addslashes($query);
$patterns = array();
$patterns[] = "/select/";
$patterns[] = "/insert/";
$patterns[] = "/and/";
$patterns[] = "/or/";
$patterns[] = "/update/";
$patterns[] = "/delete/";
$patterns[] = "/\'/";
$patterns[] = "/\/\*/";
$patterns[] = "/\*/";
$patterns[] = "/\.\.\//";
$patterns[] = "/\.\//";
$patterns[] = "/union/";
$patterns[] = "/into/";
$patterns[] = "/load_file/";
$patterns[] = "/outfile/";
$replacements = array();
$replacements[] = '';
return preg_replace($patterns, $replacements, $string);
}
/**
* 宽字符串截字函数
*
* @access public
* @param string $str 需要截取的字符串
* @param integer $start 开始截取的位置
* @param integer $length 需要截取的长度
* @param string $trim 截取后的截断标示符
* @param string $charset 字符串编码
* @return string
*/
public static function subStr($str, $start, $length, $trim = "...", $charset = 'UTF-8')
{
if (function_exists('mb_get_info')) {
$iLength = mb_strlen($str, $charset);
$str = mb_substr($str, $start, $length, $charset);
return ($length < $iLength - $start) ? $str . $trim : $str;
} else {
preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $info);
$str = join("", array_slice($info[0], $start, $length));
return ($length < (sizeof($info[0]) - $start)) ? $str . $trim : $str;
}
}
/**
* 获取宽字符串长度函数
*
* @access public
* @param string $str 需要获取长度的字符串
* @return integer
*/
public static function strLen($str, $charset = 'UTF-8')
{
if (function_exists('mb_get_info')) {
return mb_strlen($str, $charset);
} else {
preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $str, $info);
return sizeof($info[0]);
}
}
/**
* 修整缩略名
*
* @access public
* @param string $str 需要生成缩略名的字符串
* @param string $default 默认的缩略名
* @param integer $maxLength 缩略名最大长度
* @param string $charset 字符编码
* @return string
*/
public static function repair_slugName($str, $default = NULL, $maxLength = 200, $charset = 'UTF-8')
{
$str = str_replace(array("'", ":", "\\", "/"), "", $str);
$str = str_replace(array("+", ",", " ", ".", "?", "=", "&", "!", "<", ">", "(", ")", "[", "]", "{", "}"), "_", $str);
$str = trim($str, '_');
$str = empty($str) ? $default : $str;
return function_exists('mb_get_info') ? mb_strimwidth($str, 0, 128, '', $charset) : substr($str, $maxLength);
}
/**
* 词义化时间
*
* @access public
* @param string $from 起始时间
* @param string $now 终止时间
* @return string
*/
public static function dateWord($from, $now)
{
// 如果不是同一年
if (idate('Y', $now) != idate('Y', $from)) {
return date('Y年m月d日', $from);
}
// 以下操作同一年的日期
$seconds = $now - $from;
$days = idate('z', $now) - idate('z', $from);
// 如果是同一天
if ($days == 0) {
// 如果是一小时内
if ($seconds < 3600) {
// 如果是一分钟内
if ($seconds < 60) {
if (3 > $seconds) {
return '刚刚';
} else {
return sprintf('%d秒前', $seconds);
}
}
return sprintf('%d分钟前', intval($seconds / 60));
}
return sprintf('%d小时前', idate('H', $now) - idate('H', $from));
}
// 如果是昨天
if ($days == 1) {
return sprintf('昨天 %s', date('H:i', $from));
}
// 如果是前天
if ($days == 2) {
return sprintf('前天 %s', date('H:i', $from));
}
// 如果是7天内
if ($days < 7) {
return sprintf('%d天前', $days);
}
// 超过一周
return date('n月j日', $from);
}
/**
* 抽取多维数组的某个元素,组成一个新数组,使这个数组变成一个扁平数组
* 使用方法:
* <code>
* <?php
* $fruit = array(array('apple' => 2, 'banana' => 3), array('apple' => 10, 'banana' => 12));
* $banana = Common::arrayFlatten($fruit, 'banana');
* print_r($banana);
* //outputs: array(0 => 3, 1 => 12);
* ?>
* </code>
*
* @access public
* @param array $value 被处理的数组
* @param string $key 需要抽取的键值
* @return array
*/
public static function array_flatten($value = array(), $key)
{
$result = array();
if ($value) {
foreach ($value as $inval) {
if (is_array($inval) && isset($inval[$key])) {
$result[] = $inval[$key];
} else {
break;
}
}
}
return $result;
}
/**
* 在数组的指定序号插入元素
* 使用方法:
* <code>
* <?php
* $fruit = array('apple' => 2, 'banana' => 3);
* $banana = Common::array_insert($fruit, 1, array('aa' => 99));
* print_r($banana);
* //outputs: array('apple' => 2, 'aa' => 99, 'banana' => 3);
* ?>
* </code>
*
* @access public
* @param array $arr 原数组
* @param int $pos 要插入到原数组中指定的位置
* @param int $ins 要插入的元素
* @return array
*/
public static function array_insert(&$arr, $pos, $ins)
{
$prev = array_splice($arr, 0, $pos);
$arr = array_merge($prev, $ins, $arr);
}
/**
* 获取IP地址
* @return string
*/
public static function getRemoteIp()
{
$cip = '';
if (isset($_GET['ip'])) {
$cip = $_GET['ip'];
}
elseif (isset($_SERVER['X_SINA_IP'])) {
$cip = $_SERVER['X_SINA_IP'];
}
elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
$cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
if (FALSE !== strpos($cip, ',')) {
//多个转发IP的,取第1个,那是用户最初的IP
$arrIp = explode (', ', $cip);
$cip = $arrIp[0];
}
}
return $cip ? $cip : $_SERVER["REMOTE_ADDR"];
}
/**
* IP地址转整型
* @return string
*/
public static function getRemoteIpLong()
{
return sprintf("%u", ip2long(self::getRemoteIp()));
}
/**
* 检测内网 IP
* @param string $ip ip地址
* @return boolean
*/
static function isPrivateIp($ipString = '')
{
$ipString = empty($ipString) ? $_SERVER['REMOTE_ADDR'] : $ipString;
$ip = ip2long($ipString);
$ipRang = substr($ipString, 0, strrpos($ipString, '.'));
/**
* 局域网IP段
* A类 10.0.0.0 - 10.255.255.255
* B类 172.16.0.0 - 172.31.255.255
* C类 192.168.0.0 - 192.168.255.255
*/
if ((167772160 <= $ip && $ip <= 184549375) ||
(-1408237568 <=$ip && $ip <= -1407188993) ||
(-1062731776 <=$ip && $ip <= -1062666241) ||
(2886729728 <=$ip && $ip <= 2887778303) ||
(3232235520 <=$ip && $ip <= 3232301055) ||
(in_array($ipRang, array('61.135.152', '180.149.134', '123.125.106',))) ||
(in_array($ipString, array('127.0.0.1')))
)
{
return true;
}
return false;
}
/**
* Base64位安全加密
* 备注:将字符串中的加号+换成中划线-,并且将斜杠/换成下划线_,同时尾部保持填充等号=
* @param string $data 原始字符串
* @return string
*/
public static function urlsafe_base64_encode($data)
{
$data = base64_encode($data);
$data = str_replace(array('+', '/'), array('-', '_'), $data);
return $data;
}
/**
* 判断hash值是否相等
*
* @access public
* @param string $source 源字符串
* @param string $target 目标字符串
* @return boolean
*/
public static function hash_validate($source, $target)
{
// print_r(self::do_hash($source, $target));
// echo PHP_EOL;
// echo $target;
// die;
return (self::do_hash($source, $target) == $target);
}
/**
* 对字符串进行hash加密
*
* @access public
* @param string $string 需要hash的字符串
* @param string $salt 扰码
* @return string
*/
public static function do_hash($string, $salt = NULL)
{
if (NULL === $salt) {
$salt = substr(md5(uniqid(rand(), TRUE)), 0, SALT_LENGTH);
}
else {
$salt = substr($salt, 0, SALT_LENGTH);
}
return $salt . sha1($string . $salt);
}
/**
* 获取自定义http请求头数据
*/
public static function get_all_headers()
{
$headers = array();
// 忽略获取的header数据
$ignore = array('host', 'accept', 'content-length', 'content-type');
foreach ($_SERVER as $key => $value) {
if ('HTTP_' == substr($key, 0, 5)) {
$key = substr($key, 5);
$key = str_replace('_', ' ', $key);
$key = str_replace(' ', '-', $key);
$key = strtolower($key);
if ( ! in_array($key, $ignore)) {
$headers[$key] = $value;
}
}
}
if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
$headers['authorization'] = $_SERVER['PHP_AUTH_DIGEST'];
} elseif (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$headers['authorization'] = base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW']);
}
if (isset($_SERVER['CONTENT_LENGTH'])) {
$headers['content-length'] = $_SERVER['CONTENT_LENGTH'];
}
if (isset($_SERVER['CONTENT_TYPE'])) {
$headers['content-type'] = $_SERVER['CONTENT_TYPE'];
}
return $headers;
}
/**
* 发起HTTPS请求
*/
public static function curl_https($url, $data, $header = NULL, $post = 1)
{
// 初始化curl
$ch = curl_init();
// 参数设置
curl_setopt($ch, CURLOPT_URL, $url); // 要访问的地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_POST, $post); // 是否发送一个常规的post请求
if ($post) curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // post提交的数据包
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
if (is_object($header) OR is_array($header)) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($ch);
curl_close($ch);
return $result; // 返回数据,json格式
}
/**
* ID类型转化(字符串)
*
* @param $in mixed 需要转化的变量(string|long)
* @param $to_num boolean 转化方式: TRUE-数值,FALSE-字符串
* @param $pad_up mixed 对齐方式: int - 指定对齐的长度, false - 不指定
* @param $passKey string 加密秘钥
* @return mixed(string|long)
*/
public static function alphaID($in, $to_num = false, $pad_up = false, $passKey = null)
{
$index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ($passKey !== null) {
for ($n = 0; $n < strlen($index); $n++) {
$i[] = substr($index, $n, 1);
}
$passhash = hash('sha256',$passKey);
$passhash = (strlen($passhash) < strlen($index)) ? hash('sha512', $passKey) : $passhash;
for ($n = 0; $n < strlen($index); $n++) {
$p[] = substr($passhash, $n ,1);
}
array_multisort($p, SORT_DESC, $i);
$index = implode($i);
}
$base = strlen($index);
if ($to_num) {
$out -= pow($base, $pad_up);
$out = sprintf('%F', $out);
$out = substr($out, 0, strpos($out, '.'));
} else {
if (is_numeric($pad_up)) {
$pad_up--;
if ($pad_up > 0) {
$in += pow($base, $pad_up);
}
}
$out = "";
for ($t = floor(log($in, $base)); $t >= 0; $t--) {
$bcp = bcpow($base, $t);
$a = floor($in / $bcp) % $base;
$out = $out . substr($index, $a, 1);
$in = $in - ($a * $bcp);
}
$out = strrev($out);
}
return $out;
}
网友评论