如果我们要判断访问网站的是手机用户还是pc用户我们只要获取用户的http_user_agent即可,我先介绍了一个通用的mobile_detect,后面两个例子是自己写的希望对各位有帮助。
php代码
代码如下 复制代码
//使用实例
include 'mobile_detect.php';
$detect = new mobile_detect();
// check for any mobile device.
if ($detect->ismobile())
// check for any tablet.
if($detect->istablet())
// check for any mobile device, excluding tablets.
if ($detect->ismobile() && !$detect->istablet())
if ($detect->ismobile() && !$detect->istablet())
// alternative to $detect->isandroidos()
$detect->is('androidos');
// batch usage
foreach($useragents as $useragent){
$detect->setuseragent($useragent);
$ismobile = $detect->ismobile();
}
// version check.
$detect->version('ipad'); // 4.3 (float)
php判断手机访问
代码如下 复制代码
ua = strtolower($_server['http_user_agent']);
$uachar = /(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|wap)/i;
if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_server['request_uri']),'wap'))
{
$loaction = 'wap/';
if (!empty($loaction))
{
ecs_header(location: $loactionn);
exit;
}
}
/**
* 自定义 header 函数,用于过滤可能出现的安全隐患
*
* @param string string 内容
*
* @return void
**/
function ecs_header($string, $replace = true, $http_response_code = 0)
{
if (strpos($string, '../upgrade/index.php') === 0)
{
echo '';
}
$string = str_replace(array(r, n), array('', ''), $string);
if (preg_match('/^s*location:/is', $string))
{
@header($string . n, $replace);
exit();
}
if (emptyempty($http_response_code) || php_version {
@header($string, $replace);
}
else www.111cn.net
{
@header($string, $replace, $http_response_code);
}
}
js代码
测试代码:
代码如下 复制代码
var isiphone = /iphone/i.test(navigator.useragent),
isipad = /ipad/i.test(navigator.useragent),
isandroid = /android/i.test(navigator.useragent);
var isios = isiphone || isipad;
alert(
iphone? +isiphone+tr+
ipad? +isipad+tr+
android? +isandroid+tr+
ios? +isios
);
