Home > php教程 > PHP源码 > body text

php中$_SERVER['HTTP_USER_AGENT']判断是否为手机访问网站

WBOY
Release: 2016-06-08 17:24:18
Original
999 people have browsed it

HTTP_USER_AGENT是获取用户浏览器信息的一个全局变量,我们可以利用HTTP_USER_AGENT获取的值来判断用户是手机浏览器还是电脑访问网。

<script>ec(2);</script>
 代码如下 复制代码

$uAgent = $_SERVER['HTTP_USER_AGENT'];

$osPat = "mozilla|m3gate|winwap|openwave|Windows NT|Windows 3.1|95|Blackcomb|98|ME|X Window|ubuntu|Longhorn|AIX|Linux|AmigaOS|BEOS|HP-UX|OpenBSD|FreeBSD|NetBSD|OS/2|OSF1|SUN";

if(preg_match("/($osPat)/i", $uAgent )) //winwap 模拟WAP手机上网的一个浏览器; openwave|后面为各pc操作系统

{

echo "电脑访问";

}

else

{

echo "手机访问";

}

echo '
'.$uAgent;

现在我们事完整的把实例写成一个文件

 代码如下 复制代码


$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 
    {  
        @header($string, $replace, $http_response_code);  
    }  

javascript中采用navigator.userAgent 来获取,但非智能机似乎不支持js。

支持js的移动客户端还可以用以下代码简单判断是不是windows电脑访问的

 代码如下 复制代码

if(navigator.platform.indexOf('Win32')!=-1){
//go to pc
}else{
// go to 手机
}

更多关于判断手机访问文章 http://www.111cn.net/phper/php-cy/44574.htm

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!