首页 > 编程技术 > php

php 判断访问者是否手机客户端实例

发布时间:2016-11-25 15:43

最近移动互联网火爆了我们需要做一个PC站与WAP站,要实现如果用户是电脑访问WAP站就自动进入PC站,反之一样,下面我整理了一些代码与大家一起来看看。

方法一:判断HTTP_USER_AGENT

 代码如下 复制代码

$agent = strtolower($_SERVER['HTTP_USER_AGENT']); 
if(strpos($agent,"netfront") || strpos($agent,"iphone") || strpos($agent,"midp-2.0") || strpos($agent,"opera mini") || strpos($agent,"ucweb") || strpos($agent,"android") || strpos($agent,"windows ce") || strpos($agent,"symbianos")) {
    Header("HTTP/1.1 301 Moved Permanently");
    header("Location:####");  die;
}


方法二:判断HTTP_ACCEPT

 代码如下 复制代码
if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'],'vnd.wap.wml')!==FALSE) &&(strpos($_SERVER['HTTP_ACCEPT'],'text/html')===FALSE || (strpos($_SERVER['HTTP_ACCEPT'],'vnd.wap.wml') < 
strpos($_SERVER['HTTP_ACCEPT'],'text/html')) )) {//手机访问 
    Header("HTTP/1.1 301 Moved Permanently");
    header("Location:####"); die;
}

以上两个方法都有局限性,

下面将此两种方法整合起来判断

 代码如下 复制代码

function isMobile() {
    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if(isset ($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if(isset($_SERVER['HTTP_USER_AGENT'])) {
        //此数组有待完善
        $clientkeywords = array (
        'nokia',
        'sony',
        'ericsson',
        'mot',
        'samsung',
        'htc',
        'sgh',
        'lg',
        'sharp',
        'sie-',
        'philips',
        'panasonic',
        'alcatel',
        'lenovo',
        'iphone',
        'ipod',
        'blackberry',
        'meizu',
        'android',
        'netfront',
        'symbian',
        'ucweb',
        'windowsce',
        'palm',
        'operamini',
        'operamobi',
        'openwave',
        'nexusone',
        'cldc',
        'midp',
        'wap',
        'mobile'
        );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if(preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
 
    }
 
    //协议法,因为有可能不准确,放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
     
return false;
}

上面的方法也存在一些小问题,这里我根据自己的经验来告诉大我们可以使用屏幕宽度来实现再加机器类型了,因为有时HTTP_USER_AGENT信息在我们上面并未定义过了,不过上面实现几乎兼容了主流手机了。

我们还可以使用js

<html>

 <body>

  <script type="text/javascript">
   function browserRedirect() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";

    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
     window.location.href = 'http://url/mobile.html';
    } else {
     window.location = 'http://url/pc.html';
    }

   }

   browserRedirect();
  </script>

 </body>
</html> 

页面缓存就是把页面保存到一个文件中,下次读出时直接调用文件而不查询数据库,这里我们介绍利用ob_start()来实现。


 代码如下 复制代码

<?php
ob_start(); //打开缓冲区
phpinfo(); //使用phpinfo函数
$info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info
$file=fopen(’info.txt’,’w’); //打开文件info.txt
fwrite($file,$info); //写入信息到info.txt
fclose($file); //关闭文件info.txt
//或直接用 file_put_content('info.txt',$info);
?>

以上的方法,可以把不同用户的phpinfo信息保存下来。

这里我们可以着重看看这个方法的使用技巧,用这个方法可以实现生成静态页面的便利!

并且用这个方法比用file_get_conents()的方法更合理更有效率。

简单的说个应用吧,比如想要把phpinfo()的内容写入文件,可以这样做:

 代码如下 复制代码

ob_start();
$phpinfo = phpinfo();
//写入文件
ob_end_flush();

或者还有这样的用途:

ob_start(); //打开缓冲区
echo "Hellon"; //输出
header("location:index.php"); //把浏览器重定向到index.php
ob_end_flush();//输出全部内容到浏览器

header()会发送一段文件头给浏览器,但是如果在header()之前已经有了任何输出(包括空输出,比如空格,回车和换行)就会报错。但是如果输出在ob_start()和ob_end_flush()之间,就会没有问题。因为在输出前打开了缓冲区,echo后面的字符就不会输出到浏览器,而是保留在服务器,知道使用flush才会输出,所以header()会正常执行。

当然,ob_start()还可以有参数,参数就是一个回调函数。例子如下:

 代码如下 复制代码

< ? php
function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
? >
< html >
< body >
<P>It's like comparing apples to oranges.</P>
< / body >
< / html >
< ?php
ob_end_flush();
? >

以上程序会输出:

< html >
< body >
< p>It's like comparing oranges to oranges.</ p>
< / body >
< / html >

至于更多的,就去官网的手册里看吧。

在php中取整函数有四个函数,如floor,ceil,round,intval这几个了,下面我给大家分别介绍它们之间应用实例。

floor 舍去法取整 语法格式:float floor ( float value )

返回不大于 value 的下一个整数,将 value 的小数部分舍去取整。floor() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大。

 代码如下 复制代码

echo floor(4.3); // 4
echo floor(9.999); // 9


ceil 进一法取整 语法格式: float ceil ( float value )

返回不小于 value 的下一个整数,value 如果有小数部分则进一位。ceil() 返回的类型仍然是 float,因为 float 值的范围通常比 integer 要大

 代码如下 复制代码
echo ceil(4.3); // 5
echo ceil(9.999); // 10

round 对浮点数进行四舍五入

语法:float round ( float val [, int precision] )

 代码如下 复制代码

echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000


intval---对变数转成整数型态

例子intval()

 代码如下 复制代码

<?php

echo intval(4.3);    //4

echo intval(4.6);  // 4  

?>

使用file_get_contents无法请求https连接问题觖方法很简单,我们只要把php_openssl开启就可以了,当然linux系统需要安装openssl模块了。

PHP.ini默认配置下,用file_get_contents读取https的链接,就会如下错误:

Warning: fopen() [function.fopen]: Unable to find the wrapper “https” – did you forget to enable it when you configured PHP?

解决方案有3:

1.windows下的PHP,只需要到php.ini中把extension=php_openssl.dll前面的;删掉,重启服务就可以了。
2.linux下的PHP,就必须安装openssl模块,安装好了以后就可以访问了。

安装方法


OpenSSL库的安装

官网:http://www.openssl.org

下载页面:http://www.openssl.org/source/

选择最新版本下载

http://www.openssl.org/source/openssl-1.0.0a.tar.gz

解压:

tar –zxvf openssl-1.0.0d.tar.gz,解压目录为:openssl-1.0.0d

然后进入到 cd openssl-1.0.0d,进行配置、编译、安装

配置

./configure或./config

编译

make

安装

make install

 

3.如果服务器你不能修改配置的话,那么就使用curl函数来替代file_get_contents函数,当然不是简单的替换啊。还有相应的参数配置才能正常使用curl函数。

对curl函数封装如下:

 代码如下 复制代码

function http_request($url,$timeout=30,$header=array()){
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $data = curl_exec($ch);
        list($header, $data) = explode("rnrn", $data);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302) {
            $matches = array();
            preg_match('/Location:(.*?)n/', $header, $matches);
            $url = trim(array_pop($matches));
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $data = curl_exec($ch);
        }

        if ($data == false) {
            curl_close($ch);
        }
        @curl_close($ch);
        return $data;
}

短网址现在用得比较多很多跳转网站都会生成,像现原微博也有这个功能,下面我来给大家推荐一款PHP网址缩短代码

每个网址用6个字符代替,(32^6) 最多可以拥有1,073,741,824个短网址。当然,你还可以记录更详细的信息,如访问记录,创建时间等。如果真不够用了,还可以删掉很久不用的。

 代码如下 复制代码

function shorturl($input) {

  $base32 = array (

    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',

    'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',

    'q', 'r', 's', 't', 'u', 'v', 'w', 'x',

    'y', 'z', '0', '1', '2', '3', '4', '5'

    );


  $hex = md5($input);

  $hexLen = strlen($hex);

  $subHexLen = $hexLen / 8;

  $output = array();


  for ($i = 0; $i < $subHexLen; $i++) {

    $subHex = substr ($hex, $i * 8, 8);

    $int = 0x3FFFFFFF & (1 * ('0x'.$subHex));

    $out = '';


    for ($j = 0; $j < 6; $j++) {

      $val = 0x0000001F & $int;

      $out .= $base32[$val];

      $int = $int >> 5;

    }


    $output[] = $out;

  }


  return $output;

}


Sample code to test/use the above function:

$input = 'http://www.111cn.net /1';

$output = shorturl($input);


echo "Input  : $inputn";

echo "Output : {$output[0]}n";

echo "         {$output[1]}n";

echo "         {$output[2]}n";

echo "         {$output[3]}n";

echo "n";


$input = 'http://www.111cn.net /2';

$output = shorturl($input);


echo "Input  : $inputn";

echo "Output : {$output[0]}n";

echo "         {$output[1]}n";

echo "         {$output[2]}n";

echo "         {$output[3]}n";

echo "n";


Output:

Input : http://www.111cn.net /1

Output : h0xg4r

bdr3tw

osk2d3

4azfqa


Input : http://www.111cn.net /2

Output : tm5kxb

ceoj2s

yw3dvl

nrmrxl

标签:[!--infotagslink--]

您可能感兴趣的文章: