PHP常用代码片段
/**
* @Author xiadmin
* 获取客户端IP地址
* @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
* @param bool $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];
}
/**
* @Author xiadmin
* 获取服务器端IP地址
* @return array|false|string
*/
function get_server_ip(){
if(isset($_SERVER)){
if($_SERVER['SERVER_ADDR']){
$server_ip = $_SERVER['SERVER_ADDR'];
}else{
$server_ip = $_SERVER['LOCAL_ADDR'];
}
}else{
$server_ip = getenv('SERVER_ADDR');
}
return $server_ip;
}
/**
* @Author xiadmin
* 生成随机字符串
* @param int $length 生成长度
* @param int $type 生成类型:0-小写字母+数字,1-小写字母,2-大写字母,3-数字,4-小写+大写字母,5-小写+大写+数字
* @return string
*/
function generate_rand_str($length = 8, $type = 0) {
$a = 'abcdefghijklmnopqrstuvwxyz';
$A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$n = '0123456789';
switch ($type) {
case 1: $chars = $a; break;
case 2: $chars = $A; break;
case 3: $chars = $n; break;
case 4: $chars = $a.$A; break;
case 5: $chars = $a.$A.$n; break;
default: $chars = $a.$n;
}
$str = '';
for ($i = 0; $i < $length; $i++) {
$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
return $str;
}
/**
* @Author xiadmin
* 获取浏览器类型
* @return string
*/
function get_browser_type(){
$agent = $_SERVER["HTTP_USER_AGENT"];
if(strpos($agent,'MSIE') !== false || strpos($agent,'rv:11.0')) return "ie";
if(strpos($agent,'Firefox') !== false) return "firefox";
if(strpos($agent,'Chrome') !== false) return "chrome";
if(strpos($agent,'Opera') !== false) return 'opera';
if((strpos($agent,'Chrome') == false) && strpos($agent,'Safari') !== false) return 'safari';
if(false!==strpos($_SERVER['HTTP_USER_AGENT'],'360SE')) return '360SE';
return 'unknown';
}